From a692bdff237855a83d59f8bd3aeb938780a60395 Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 26 Nov 2026 23:49:26 +0000 Subject: [PATCH 1/4] feat(chatbot)!: retire the build chat frontend The build agent is retired. Delete the code that drew its conversation: the proposed-plan, proposed-change, build-result and builder-handoff cards with their detectors and props in plugin-chatbot; the Build Doctor drawer, pending-drafts bar, spreadsheet import bar, maker start chips and empty state, and Studio's copilot panel and topbar entry in app-shell; and the 280 released i18n keys only that UI read. Ask chat (dock and full page) and Studio keep working, and an old /ai/build address still lands on the ask chat. publishHealthFromResponse and PublishHealth stay because the preview's Publish all reads them. Tests that only pinned removed code are deleted; the rest are retargeted to the ask chat. Seventeen tests that reach AiChatPage now preload @object-ui/plugin-grid at module top, which the deleted import bar used to pay for during collection. Co-authored-by: Claude Claude-Session: https://claude.ai/code/session_01Q4EjjMnLQVLzcho6g8WAL3 --- .../37682-i18n-retire-build-chat-keys.md | 332 ++ .../37682-retire-build-chat-frontend.md | 35 + .../openPathObjectReaders-12811.test.ts | 4 - .../app-shell/src/console/ai/AiChatPage.tsx | 1527 +----- .../src/console/ai/BuildDebugDrawer.tsx | 280 - .../src/console/ai/ConversationsSidebar.tsx | 27 +- .../src/console/ai/ExcelImportBar.tsx | 257 - .../src/console/ai/PendingDraftsBar.tsx | 152 - ...ChatPage.appContextComposer-11658.test.tsx | 104 +- ...AiChatPage.appliedCardDoors-12894.test.tsx | 276 - ...age.attachmentNotesLanguage-34461.test.tsx | 1 - ...iChatPage.attachmentsUpload-32749.test.tsx | 1 - ...iChatPage.buildClosedRoutes-36969.test.tsx | 22 +- .../AiChatPage.buildHistorySurvives.test.tsx | 292 -- .../AiChatPage.draftInMainArea-34610.test.tsx | 348 -- .../AiChatPage.draftsBarInFlow-12978.test.tsx | 201 - .../AiChatPage.editChips-7709.test.ts | 75 - ...age.firstMessageDrawnAtOnce-33420.test.tsx | 4 +- ...hatPage.handoffNeverFromUrl-12493.test.tsx | 282 - .../ai/__tests__/AiChatPage.hydration.test.ts | 76 +- ...ChatPage.iterateOrNewReload-27480.test.tsx | 131 - .../AiChatPage.loneAgentHeader-37146.test.tsx | 24 +- ...hatPage.modelCostMultiplier-33660.test.tsx | 26 +- ....modelPickSurvivesFirstSend-32994.test.tsx | 4 +- ...Page.noNavigationAfterBuild-12724.test.tsx | 344 -- .../AiChatPage.onePlanPerTurnReload.test.tsx | 151 - ...lanApprovalReachesLaunchers-11666.test.tsx | 203 - .../AiChatPage.planCardLocale.test.tsx | 310 -- ...Page.publishAdvisoryReachesAuthor.test.tsx | 283 - .../AiChatPage.runtimeMessageSeam.test.tsx | 47 +- ...atPage.seedWarnPackSentence-35303.test.tsx | 269 - ...age.sendOrderWhileUploading-34462.test.tsx | 1 - .../AiChatPage.startChips-1984.test.ts | 67 - .../AiChatPage.studioDraftsBar-12965.test.tsx | 153 - ...AiChatPage.toolLabelsLocale-11667.test.tsx | 71 +- .../AiChatPage.uiLocale-34639.test.tsx | 5 +- .../ai/__tests__/BuildDebugDrawer.test.tsx | 73 - .../ExcelImportBar.importGrant-12082.test.tsx | 164 - ...ExcelImportBar.sharedSelect-11865.test.tsx | 234 - ...dingDraftsBar.sentenceWraps-13088.test.tsx | 111 - .../ai/__tests__/PendingDraftsBar.test.tsx | 153 - .../ai/__tests__/agentEmptyState.test.ts | 46 + .../aiFaces.displayLocale-9909.test.tsx | 28 +- .../ai/__tests__/artifactStudioPath.test.ts | 55 - .../buildDoctor.drawerBody-10969.test.tsx | 147 - .../buildDoctor.locale-10900.test.tsx | 150 - .../changeCardLabels.drafted-32984.test.tsx | 316 -- .../ai/__tests__/deriveBoundPackageId.test.ts | 83 - .../ai/__tests__/editModeEmptyState.test.ts | 93 - .../ai/__tests__/mainAreaDraft-34610.test.ts | 62 - .../ai/__tests__/outboundAgentText.test.ts | 114 - .../src/console/ai/artifactStudioPath.ts | 49 - .../app-shell/src/console/ai/buildDebugApi.ts | 93 - .../src/console/ai/changeCardLabels.ts | 136 - .../app-shell/src/console/ai/mainAreaDraft.ts | 107 - .../src/console/ai/outboundAgentText.ts | 140 +- ...nversation.editKindRoundTrip-10109.test.ts | 94 - ...atConversation.replayedBuild-25887.test.ts | 147 - .../__tests__/useChatConversation.test.tsx | 247 +- .../src/hooks/useChatConversation.ts | 230 +- ui/packages/app-shell/src/layout/ChatDock.tsx | 59 +- .../src/layout/ChatDockConversation.tsx | 182 +- .../ChatDock.appBinding-10926.test.tsx | 435 +- .../ChatDock.requestContext-30043.test.tsx | 8 +- .../src/layout/__tests__/ChatDock.test.tsx | 32 +- .../ConsoleLayout.dockBinding-10926.test.tsx | 7 +- .../layout/__tests__/chatFocus-36999.test.tsx | 4 +- ...ackageFormDialog.newAppStep-36748.test.tsx | 1 - ...ionMatrixEditor.saveSurface-12725.test.tsx | 1 - ...sionMatrixEditor.studioSave-36511.test.tsx | 1 - .../views/studio-design/AutomationsPillar.tsx | 31 - .../CreateItemDialog.labels-13128.test.tsx | 1 - ...taPillar.copilotChangesLine-34725.test.tsx | 22 +- .../src/views/studio-design/DataPillar.tsx | 33 - .../views/studio-design/StudioAiCopilot.tsx | 366 -- ...ignSurface.accessNewSimilar-28573.test.tsx | 1 - ...esignSurface.accessPairCopy-29674.test.tsx | 1 - ...DesignSurface.accessSegment-12452.test.tsx | 1 - ...e.accessSuggestionsReadOnly-33158.test.tsx | 1 - ...DesignSurface.accessWording-34795.test.tsx | 1 - .../StudioDesignSurface.aiChipLabel.test.tsx | 245 - ...udioDesignSurface.backToApp-36501.test.tsx | 1 - ...face.canvasStripServedLabel-36480.test.tsx | 10 - ...oDesignSurface.changesCount-11787.test.tsx | 1 - ...oDesignSurface.copilotDoors-12894.test.tsx | 399 -- ...gnSurface.copilotDraftBadge-12725.test.tsx | 441 -- ...gnSurface.createAppAccessibleName.test.tsx | 1 - ...ioDesignSurface.createTaken-26917.test.tsx | 1 - ...ignSurface.customizePublish-28562.test.tsx | 1 - ...ioDesignSurface.desktopHint-11795.test.tsx | 1 - ...ioDesignSurface.emptyStates-12514.test.tsx | 1 - ...esignSurface.entryReadsOnce-11797.test.tsx | 1 - ...oDesignSurface.flowAutosave-34818.test.tsx | 2 +- ...tudioDesignSurface.graphite-37455.test.tsx | 11 +- ...esignSurface.heldDataCreate-26845.test.tsx | 1 - ...DesignSurface.heldDataLeave-26705.test.tsx | 1 - ...esignSurface.heldFlowCreate-26845.test.tsx | 1 - ...DesignSurface.heldFlowLeave-26705.test.tsx | 1 - ...ioDesignSurface.heldPublish-11786.test.tsx | 1 - ...tudioDesignSurface.homeLoop-12513.test.tsx | 9 - ...gnSurface.interfacesRetired-36502.test.tsx | 1 - ...DesignSurface.itemDraftLine-12725.test.tsx | 1 - ...esignSurface.kernelReadOnly-29567.test.tsx | 1 - ...oDesignSurface.metadataArea-28561.test.tsx | 1 - ...DesignSurface.navRenameHeld-27464.test.tsx | 1 - ...tudioDesignSurface.notFound-26708.test.tsx | 11 +- ...dioDesignSurface.oneSurface-28572.test.tsx | 1 - ...ignSurface.packageLessFlows-11553.test.tsx | 13 +- ...gnSurface.packageListErrorPosture.test.tsx | 1 - ...tudioDesignSurface.pillarNavGuard.test.tsx | 4 - ...ignSurface.pillarsClaimSlot-12725.test.tsx | 135 +- ...face.publishAdvisoryReachesAuthor.test.tsx | 1 - ...signSurface.publishBackfill-12929.test.tsx | 1 - ...oDesignSurface.publishCount-11807.test.tsx | 1 - ...esignSurface.publishPosture-12517.test.tsx | 1 - ...rface.publishReadOnlyReason-12303.test.tsx | 1 - ...esignSurface.publishRefusal-26730.test.tsx | 1 - ...signSurface.readOnlyPosture-12453.test.tsx | 1 - ...udioDesignSurface.rightSlot-12725.test.tsx | 115 +- ...StudioDesignSurface.saveBar-36511.test.tsx | 1 - .../studio-design/StudioDesignSurface.tsx | 122 +- .../studio-design/StudioMetadataArea.tsx | 15 - .../StudioPackageMenu-37139.test.tsx | 1 - .../StudioPackageOverview-37454.test.tsx | 1 - .../studio-design/StudioPermissionSetPage.tsx | 23 - .../views/studio-design/StudioRightSlot.tsx | 209 +- .../studioCopilotSlotBody-12725.test.tsx | 209 - .../studioCopilotWidenInPlace-34610.test.tsx | 97 - .../__tests__/studioRightSlot-12725.test.tsx | 237 +- .../__tests__/studioSurfaceContext.test.tsx | 202 - .../studioSurfaceLabel-8219.test.tsx | 178 - .../packages-io.bearerSession.test.ts | 3 - .../studio-design/studioRightSlotState.ts | 93 +- .../views/studio-design/useSurfaceDeepLink.ts | 4 +- .../__tests__/column-identity.ratchet.test.ts | 11 +- .../core/src/utils/affordanceGrants.ts | 7 +- ui/packages/i18n/scripts/zh-hant.d.mts | 3 - ui/packages/i18n/scripts/zh-hant.mjs | 51 +- .../__tests__/all-locales-key-parity.test.ts | 29 +- .../__tests__/console-namespace-3546.test.tsx | 126 +- .../__tests__/count-families-11445.test.ts | 8 - .../__tests__/de-quote-pairing-3876.test.ts | 10 +- ui/packages/i18n/src/__tests__/i18n.test.ts | 73 +- .../makerEditChips-v1-scope-7709.test.ts | 160 - .../makerEmptyState-v1-scope-8329.test.ts | 236 - .../makerStartChips-v1-scope-1984.test.ts | 148 - .../__tests__/outbound-agent-messages.test.ts | 110 - .../perm-home-namespace-3546.test.tsx | 21 - .../untranslated-identity-4376.test.ts | 1 - .../src/__tests__/zh-hant-generated.test.ts | 10 - ui/packages/i18n/src/locales/ar.ts | 315 -- ui/packages/i18n/src/locales/de.ts | 259 - ui/packages/i18n/src/locales/en.ts | 304 -- ui/packages/i18n/src/locales/es.ts | 273 - ui/packages/i18n/src/locales/fr.ts | 273 - ui/packages/i18n/src/locales/ja.ts | 259 - ui/packages/i18n/src/locales/ko.ts | 259 - ui/packages/i18n/src/locales/pt-BR.ts | 273 - ui/packages/i18n/src/locales/ru.ts | 287 - ui/packages/i18n/src/locales/zh-Hans.ts | 272 - ui/packages/i18n/src/locales/zh-Hant.ts | 272 - ui/packages/i18n/src/namespaces/studio/en.ts | 14 +- ui/packages/i18n/src/namespaces/studio/zh.ts | 14 +- .../plugin-chatbot/src/ChatbotEnhanced.tsx | 4622 +---------------- ...Enhanced.appliedCardPreview-12968.test.tsx | 126 - ...nhanced.awaitingConfirmBuild-8343.test.tsx | 235 - ...hatbotEnhanced.buildCardsV2-12724.test.tsx | 328 -- .../ChatbotEnhanced.buildChat-12724.test.tsx | 314 -- .../ChatbotEnhanced.buildChat-32984.test.tsx | 337 -- ...tEnhanced.buildResultHeader-26469.test.tsx | 196 - ...hatbotEnhanced.changeCardV2-12894.test.tsx | 340 -- ...d.changesActionsWaitForTurn-10965.test.tsx | 297 -- .../ChatbotEnhanced.changesCard.test.tsx | 116 - ...anced.checklistVerification-34627.test.tsx | 159 - ...botEnhanced.draftPreviewAny-12968.test.tsx | 152 - .../ChatbotEnhanced.extendChip-11658.test.tsx | 110 - ...hatbotEnhanced.iterateOrNew-27480.test.tsx | 181 - ...tbotEnhanced.needsAttention-32984.test.tsx | 236 - ...tEnhanced.pendingCountPulse-26471.test.tsx | 135 - ...nced.planActionsWaitForTurn-10925.test.tsx | 224 - ...tEnhanced.planApprovalCount-25943.test.tsx | 151 - ...nhanced.planApprovalPending-11666.test.tsx | 204 - ...anced.planCardGeneratedName-13004.test.tsx | 77 - ...tEnhanced.planCardLifecycle-12994.test.tsx | 77 - ...botEnhanced.planCardPosture-12724.test.tsx | 83 - ...ced.planCardSuggestedLegend-33419.test.tsx | 112 - .../ChatbotEnhanced.queuedSend-32984.test.tsx | 71 + ...atbotEnhanced.quotaBlockedConfirm.test.tsx | 295 -- .../ChatbotEnhanced.replayOutcome.test.tsx | 234 - ...atbotEnhanced.replayedBuild-25887.test.tsx | 118 - .../ChatbotEnhanced.sendError.test.tsx | 136 - .../src/__tests__/ChatbotEnhanced.test.tsx | 1770 +------ .../buildCards.contract-12724.test.ts | 142 - .../__tests__/buildGroupLabel-27419.test.tsx | 56 - .../__tests__/buildPanelI18n-7388.test.tsx | 191 - .../src/__tests__/buildVerify-11988.test.tsx | 169 - .../__tests__/chat-message-contract.test.ts | 24 +- .../src/__tests__/chatMessageAdapter.test.ts | 13 +- .../__tests__/fixtures/build-cards.schema.ts | 799 --- .../__tests__/fixtures/buildCards.fixtures.ts | 401 -- .../fixtures/changePosture.fixtures.ts | 132 - .../mapMessages.buildCards-12724.test.ts | 98 - ...essages.builtAppEditEnvelope-10109.test.ts | 142 - .../mapMessages.changePosture-12894.test.ts | 199 - .../mapMessages.iterateOrNew-27480.test.ts | 98 - ...ssages.planCardGeneratedName-13004.test.ts | 49 - ...apMessages.planCardLifecycle-12994.test.ts | 47 - .../mapMessages.replayOutcome.test.ts | 161 - .../src/__tests__/mapMessages.test.ts | 604 --- .../src/__tests__/recordHandoff.test.ts | 6 +- .../src/__tests__/recordWrite-3565.test.ts | 3 +- .../toolCardHeaderState-7254.test.tsx | 148 - .../src/__tests__/toolCardI18n-7254.test.tsx | 46 +- .../useObjectChat.honestMessages.test.tsx | 42 +- .../plugin-chatbot/src/chatMessageAdapter.ts | 31 +- ui/packages/plugin-chatbot/src/core.ts | 2 +- ui/packages/plugin-chatbot/src/index.tsx | 22 +- ui/packages/plugin-chatbot/src/mapMessages.ts | 1196 +---- .../plugin-chatbot/src/publishHealth.ts | 16 +- .../plugin-chatbot/src/tool-state.test.ts | 93 +- .../plugin-chatbot/src/toolResultParsers.ts | 9 +- .../plugin-chatbot/src/useObjectChat.ts | 10 +- .../src/affordanceGrantMap-12082.test.tsx | 7 +- ui/packages/plugin-grid/src/index.tsx | 2 +- ui/scripts/check-hand-rolled-comment-mask.mjs | 2 - ui/scripts/check-i18n-dead-keys.mjs | 46 +- 226 files changed, 1298 insertions(+), 32684 deletions(-) create mode 100644 .changeset/37682-i18n-retire-build-chat-keys.md create mode 100644 .changeset/37682-retire-build-chat-frontend.md delete mode 100644 ui/packages/app-shell/src/console/ai/BuildDebugDrawer.tsx delete mode 100644 ui/packages/app-shell/src/console/ai/ExcelImportBar.tsx delete mode 100644 ui/packages/app-shell/src/console/ai/PendingDraftsBar.tsx delete mode 100644 ui/packages/app-shell/src/console/ai/__tests__/AiChatPage.appliedCardDoors-12894.test.tsx delete mode 100644 ui/packages/app-shell/src/console/ai/__tests__/AiChatPage.buildHistorySurvives.test.tsx delete mode 100644 ui/packages/app-shell/src/console/ai/__tests__/AiChatPage.draftInMainArea-34610.test.tsx delete mode 100644 ui/packages/app-shell/src/console/ai/__tests__/AiChatPage.draftsBarInFlow-12978.test.tsx delete mode 100644 ui/packages/app-shell/src/console/ai/__tests__/AiChatPage.editChips-7709.test.ts delete mode 100644 ui/packages/app-shell/src/console/ai/__tests__/AiChatPage.handoffNeverFromUrl-12493.test.tsx delete mode 100644 ui/packages/app-shell/src/console/ai/__tests__/AiChatPage.iterateOrNewReload-27480.test.tsx delete mode 100644 ui/packages/app-shell/src/console/ai/__tests__/AiChatPage.noNavigationAfterBuild-12724.test.tsx delete mode 100644 ui/packages/app-shell/src/console/ai/__tests__/AiChatPage.onePlanPerTurnReload.test.tsx delete mode 100644 ui/packages/app-shell/src/console/ai/__tests__/AiChatPage.planApprovalReachesLaunchers-11666.test.tsx delete mode 100644 ui/packages/app-shell/src/console/ai/__tests__/AiChatPage.planCardLocale.test.tsx delete mode 100644 ui/packages/app-shell/src/console/ai/__tests__/AiChatPage.publishAdvisoryReachesAuthor.test.tsx delete mode 100644 ui/packages/app-shell/src/console/ai/__tests__/AiChatPage.seedWarnPackSentence-35303.test.tsx delete mode 100644 ui/packages/app-shell/src/console/ai/__tests__/AiChatPage.startChips-1984.test.ts delete mode 100644 ui/packages/app-shell/src/console/ai/__tests__/AiChatPage.studioDraftsBar-12965.test.tsx delete mode 100644 ui/packages/app-shell/src/console/ai/__tests__/BuildDebugDrawer.test.tsx delete mode 100644 ui/packages/app-shell/src/console/ai/__tests__/ExcelImportBar.importGrant-12082.test.tsx delete mode 100644 ui/packages/app-shell/src/console/ai/__tests__/ExcelImportBar.sharedSelect-11865.test.tsx delete mode 100644 ui/packages/app-shell/src/console/ai/__tests__/PendingDraftsBar.sentenceWraps-13088.test.tsx delete mode 100644 ui/packages/app-shell/src/console/ai/__tests__/PendingDraftsBar.test.tsx create mode 100644 ui/packages/app-shell/src/console/ai/__tests__/agentEmptyState.test.ts delete mode 100644 ui/packages/app-shell/src/console/ai/__tests__/artifactStudioPath.test.ts delete mode 100644 ui/packages/app-shell/src/console/ai/__tests__/buildDoctor.drawerBody-10969.test.tsx delete mode 100644 ui/packages/app-shell/src/console/ai/__tests__/buildDoctor.locale-10900.test.tsx delete mode 100644 ui/packages/app-shell/src/console/ai/__tests__/changeCardLabels.drafted-32984.test.tsx delete mode 100644 ui/packages/app-shell/src/console/ai/__tests__/deriveBoundPackageId.test.ts delete mode 100644 ui/packages/app-shell/src/console/ai/__tests__/editModeEmptyState.test.ts delete mode 100644 ui/packages/app-shell/src/console/ai/__tests__/mainAreaDraft-34610.test.ts delete mode 100644 ui/packages/app-shell/src/console/ai/__tests__/outboundAgentText.test.ts delete mode 100644 ui/packages/app-shell/src/console/ai/artifactStudioPath.ts delete mode 100644 ui/packages/app-shell/src/console/ai/buildDebugApi.ts delete mode 100644 ui/packages/app-shell/src/console/ai/changeCardLabels.ts delete mode 100644 ui/packages/app-shell/src/console/ai/mainAreaDraft.ts delete mode 100644 ui/packages/app-shell/src/hooks/__tests__/useChatConversation.editKindRoundTrip-10109.test.ts delete mode 100644 ui/packages/app-shell/src/hooks/__tests__/useChatConversation.replayedBuild-25887.test.ts delete mode 100644 ui/packages/app-shell/src/views/studio-design/StudioAiCopilot.tsx delete mode 100644 ui/packages/app-shell/src/views/studio-design/StudioDesignSurface.aiChipLabel.test.tsx delete mode 100644 ui/packages/app-shell/src/views/studio-design/StudioDesignSurface.copilotDoors-12894.test.tsx delete mode 100644 ui/packages/app-shell/src/views/studio-design/StudioDesignSurface.copilotDraftBadge-12725.test.tsx delete mode 100644 ui/packages/app-shell/src/views/studio-design/__tests__/studioCopilotSlotBody-12725.test.tsx delete mode 100644 ui/packages/app-shell/src/views/studio-design/__tests__/studioCopilotWidenInPlace-34610.test.tsx delete mode 100644 ui/packages/app-shell/src/views/studio-design/__tests__/studioSurfaceContext.test.tsx delete mode 100644 ui/packages/app-shell/src/views/studio-design/__tests__/studioSurfaceLabel-8219.test.tsx delete mode 100644 ui/packages/i18n/src/__tests__/makerEditChips-v1-scope-7709.test.ts delete mode 100644 ui/packages/i18n/src/__tests__/makerEmptyState-v1-scope-8329.test.ts delete mode 100644 ui/packages/i18n/src/__tests__/makerStartChips-v1-scope-1984.test.ts delete mode 100644 ui/packages/i18n/src/__tests__/outbound-agent-messages.test.ts delete mode 100644 ui/packages/plugin-chatbot/src/__tests__/ChatbotEnhanced.appliedCardPreview-12968.test.tsx delete mode 100644 ui/packages/plugin-chatbot/src/__tests__/ChatbotEnhanced.awaitingConfirmBuild-8343.test.tsx delete mode 100644 ui/packages/plugin-chatbot/src/__tests__/ChatbotEnhanced.buildCardsV2-12724.test.tsx delete mode 100644 ui/packages/plugin-chatbot/src/__tests__/ChatbotEnhanced.buildChat-12724.test.tsx delete mode 100644 ui/packages/plugin-chatbot/src/__tests__/ChatbotEnhanced.buildChat-32984.test.tsx delete mode 100644 ui/packages/plugin-chatbot/src/__tests__/ChatbotEnhanced.buildResultHeader-26469.test.tsx delete mode 100644 ui/packages/plugin-chatbot/src/__tests__/ChatbotEnhanced.changeCardV2-12894.test.tsx delete mode 100644 ui/packages/plugin-chatbot/src/__tests__/ChatbotEnhanced.changesActionsWaitForTurn-10965.test.tsx delete mode 100644 ui/packages/plugin-chatbot/src/__tests__/ChatbotEnhanced.changesCard.test.tsx delete mode 100644 ui/packages/plugin-chatbot/src/__tests__/ChatbotEnhanced.checklistVerification-34627.test.tsx delete mode 100644 ui/packages/plugin-chatbot/src/__tests__/ChatbotEnhanced.draftPreviewAny-12968.test.tsx delete mode 100644 ui/packages/plugin-chatbot/src/__tests__/ChatbotEnhanced.extendChip-11658.test.tsx delete mode 100644 ui/packages/plugin-chatbot/src/__tests__/ChatbotEnhanced.iterateOrNew-27480.test.tsx delete mode 100644 ui/packages/plugin-chatbot/src/__tests__/ChatbotEnhanced.needsAttention-32984.test.tsx delete mode 100644 ui/packages/plugin-chatbot/src/__tests__/ChatbotEnhanced.pendingCountPulse-26471.test.tsx delete mode 100644 ui/packages/plugin-chatbot/src/__tests__/ChatbotEnhanced.planActionsWaitForTurn-10925.test.tsx delete mode 100644 ui/packages/plugin-chatbot/src/__tests__/ChatbotEnhanced.planApprovalCount-25943.test.tsx delete mode 100644 ui/packages/plugin-chatbot/src/__tests__/ChatbotEnhanced.planApprovalPending-11666.test.tsx delete mode 100644 ui/packages/plugin-chatbot/src/__tests__/ChatbotEnhanced.planCardGeneratedName-13004.test.tsx delete mode 100644 ui/packages/plugin-chatbot/src/__tests__/ChatbotEnhanced.planCardLifecycle-12994.test.tsx delete mode 100644 ui/packages/plugin-chatbot/src/__tests__/ChatbotEnhanced.planCardPosture-12724.test.tsx delete mode 100644 ui/packages/plugin-chatbot/src/__tests__/ChatbotEnhanced.planCardSuggestedLegend-33419.test.tsx create mode 100644 ui/packages/plugin-chatbot/src/__tests__/ChatbotEnhanced.queuedSend-32984.test.tsx delete mode 100644 ui/packages/plugin-chatbot/src/__tests__/ChatbotEnhanced.quotaBlockedConfirm.test.tsx delete mode 100644 ui/packages/plugin-chatbot/src/__tests__/ChatbotEnhanced.replayOutcome.test.tsx delete mode 100644 ui/packages/plugin-chatbot/src/__tests__/ChatbotEnhanced.replayedBuild-25887.test.tsx delete mode 100644 ui/packages/plugin-chatbot/src/__tests__/buildCards.contract-12724.test.ts delete mode 100644 ui/packages/plugin-chatbot/src/__tests__/buildGroupLabel-27419.test.tsx delete mode 100644 ui/packages/plugin-chatbot/src/__tests__/buildPanelI18n-7388.test.tsx delete mode 100644 ui/packages/plugin-chatbot/src/__tests__/buildVerify-11988.test.tsx delete mode 100644 ui/packages/plugin-chatbot/src/__tests__/fixtures/build-cards.schema.ts delete mode 100644 ui/packages/plugin-chatbot/src/__tests__/fixtures/buildCards.fixtures.ts delete mode 100644 ui/packages/plugin-chatbot/src/__tests__/fixtures/changePosture.fixtures.ts delete mode 100644 ui/packages/plugin-chatbot/src/__tests__/mapMessages.buildCards-12724.test.ts delete mode 100644 ui/packages/plugin-chatbot/src/__tests__/mapMessages.builtAppEditEnvelope-10109.test.ts delete mode 100644 ui/packages/plugin-chatbot/src/__tests__/mapMessages.changePosture-12894.test.ts delete mode 100644 ui/packages/plugin-chatbot/src/__tests__/mapMessages.iterateOrNew-27480.test.ts delete mode 100644 ui/packages/plugin-chatbot/src/__tests__/mapMessages.planCardGeneratedName-13004.test.ts delete mode 100644 ui/packages/plugin-chatbot/src/__tests__/mapMessages.planCardLifecycle-12994.test.ts delete mode 100644 ui/packages/plugin-chatbot/src/__tests__/mapMessages.replayOutcome.test.ts delete mode 100644 ui/packages/plugin-chatbot/src/__tests__/toolCardHeaderState-7254.test.tsx diff --git a/.changeset/37682-i18n-retire-build-chat-keys.md b/.changeset/37682-i18n-retire-build-chat-keys.md new file mode 100644 index 00000000000..cc492e2f67c --- /dev/null +++ b/.changeset/37682-i18n-retire-build-chat-keys.md @@ -0,0 +1,332 @@ +--- +'@object-ui/i18n': patch +--- + +feat(i18n)!: the 280 translation keys `@object-ui/i18n@18.6.0` shipped for the retired build chat are removed + +Clause-②: no +Metadata-protocol: none + + + +**BREAKING**: released keys are removed. `@object-ui/i18n@18.6.0` shipped every key listed below; objectstack#37682 retired the build chat that read them (the plan, change and build-result cards, the builder handoff, the Build Doctor drawer, the pending-drafts and spreadsheet-import bars, the maker's start chips and empty state, and Studio's copilot panel), and no code in the platform reads them any more. + +If a deployment overrides one of these keys (in its own i18next resources, or a Studio catalogue it registers), that override no longer applies: nothing in the console or Studio asks for the key, so the overriding text is never shown. Remove the override. + +The six `console.ai.*Message` keys were the text the plan and change cards sent to the agent, and only `en` and `zh-Hans` carried them. With them gone, the zh-Hant generator no longer has gate-only keys to leave out, so `GATE_ONLY_KEYS` is removed from the package's `scripts/zh-hant.mjs`. + +The list is reproduced by `node ui/packages/i18n/scripts/released-keys-removed.mjs` (the tag against this change's tree), minus the keys `origin/main` had already removed. + +## Removed translation keys + +### Language packs (`@object-ui/i18n`, `@object-ui/i18n/locales`), 271 keys + +#### Removed from all eleven locales (209 keys) + +Each key below is removed from ar, de, en, es, fr, ja, ko, pt-BR, ru, zh-Hans and zh-Hant. + +- `chatbot.build.addingSampleData` +- `chatbot.build.appFallback` +- `chatbot.build.building` +- `chatbot.build.built` +- `chatbot.build.builtAndLive` +- `chatbot.build.checksPassed` +- `chatbot.build.draftPosture` +- `chatbot.build.group.app` +- `chatbot.build.group.dashboard` +- `chatbot.build.group.dataset` +- `chatbot.build.group.object` +- `chatbot.build.group.other` +- `chatbot.build.group.permission` +- `chatbot.build.group.seed` +- `chatbot.build.group.view` +- `chatbot.build.health.sampleRowsLive` +- `chatbot.build.health.sampleRowsLive_one` +- `chatbot.build.health.sampleRowsLive_other` +- `chatbot.build.health.seeds` +- `chatbot.build.health.seeds_one` +- `chatbot.build.health.seeds_other` +- `chatbot.build.health.verified` +- `chatbot.build.health.views` +- `chatbot.build.health.views_one` +- `chatbot.build.health.views_other` +- `chatbot.build.health.widgets` +- `chatbot.build.health.widgets_one` +- `chatbot.build.health.widgets_other` +- `chatbot.build.issuesCount` +- `chatbot.build.issuesDetails` +- `chatbot.build.moreArtifacts` +- `chatbot.build.needsAttention` +- `chatbot.build.needsAttention_one` +- `chatbot.build.needsAttention_other` +- `chatbot.build.nextStepQuote` +- `chatbot.build.nextStepsLead` +- `chatbot.build.unknownPhase` +- `chatbot.build.verified` +- `chatbot.build.verifyStep` +- `chatbot.build.verifying` +- `chatbot.build.warningsSummary` +- `chatbot.changes.kind.app` +- `chatbot.changes.kind.dashboard` +- `chatbot.changes.kind.field` +- `chatbot.changes.kind.object` +- `chatbot.changes.kind.package` +- `chatbot.changes.kind.seed` +- `chatbot.changes.kind.view` +- `chatbot.changes.planTitle` +- `chatbot.changes.planTitle_one` +- `chatbot.changes.planTitle_other` +- `chatbot.changes.reviewAndPublish` +- `chatbot.changes.saveDraft` +- `chatbot.changes.undo` +- `chatbot.changes.undoCancel` +- `chatbot.changes.undoConfirm` +- `chatbot.changes.undoConfirmAction` +- `chatbot.changes.undoConfirmUnknown` +- `chatbot.changes.undoConfirm_one` +- `chatbot.changes.undoConfirm_other` +- `chatbot.changes.undoFailed` +- `chatbot.changes.undoWithOthers` +- `chatbot.changes.undoWithOthers_one` +- `chatbot.changes.undoWithOthers_other` +- `chatbot.changes.undoing` +- `chatbot.changes.undone` +- `chatbot.phase.build` +- `chatbot.phase.design` +- `chatbot.plan.awaitingConfirm` +- `chatbot.plan.buildFailed` +- `chatbot.plan.confirmed` +- `chatbot.plan.countDashboards` +- `chatbot.plan.countDashboards_one` +- `chatbot.plan.countDashboards_other` +- `chatbot.plan.countObjects` +- `chatbot.plan.countObjects_one` +- `chatbot.plan.countObjects_other` +- `chatbot.plan.countSeedData` +- `chatbot.plan.countViews` +- `chatbot.plan.countViews_one` +- `chatbot.plan.countViews_other` +- `chatbot.plan.extendTarget` +- `chatbot.plan.iterateOrNew.buildNew` +- `chatbot.plan.iterateOrNew.extend` +- `chatbot.plan.iterateOrNew.question` +- `chatbot.plan.iterateOrNew.questionUnnamed` +- `chatbot.plan.iterateOrNew.replyHint` +- `chatbot.plan.nameField` +- `chatbot.plan.objectsAndFields` +- `chatbot.plan.suggestedField` +- `chatbot.plan.suggestedFieldLegend` +- `chatbot.plan.views` +- `console.ai.agentLabels.build` +- `console.ai.agentLabels.metadataAssistant` +- `console.ai.askOrChangeApp` +- `console.ai.buildDoctor` +- `console.ai.buildDoctorDisabledTitle` +- `console.ai.buildDoctorDrawer.allLive` +- `console.ai.buildDoctorDrawer.description` +- `console.ai.buildDoctorDrawer.discrepancies` +- `console.ai.buildDoctorDrawer.issueCount` +- `console.ai.buildDoctorDrawer.missingHint` +- `console.ai.buildDoctorDrawer.missingTitle` +- `console.ai.buildDoctorDrawer.noIssues` +- `console.ai.buildDoctorDrawer.notAvailable` +- `console.ai.buildDoctorDrawer.orphanedHint` +- `console.ai.buildDoctorDrawer.orphanedTitle` +- `console.ai.buildDoctorDrawer.pendingActions` +- `console.ai.buildDoctorDrawer.platformNoise` +- `console.ai.buildDoctorDrawer.reconciling` +- `console.ai.buildDoctorDrawer.summary` +- `console.ai.buildDoctorDrawer.timeline` +- `console.ai.buildDoctorDrawer.toolErrorsHint` +- `console.ai.buildDoctorDrawer.toolErrorsTitle` +- `console.ai.buildDoctorDrawer.untitled` +- `console.ai.buildDoctorDrawer.verifyTitle` +- `console.ai.buildDoctorDrawer.yourApp` +- `console.ai.buildDoctorTitle` +- `console.ai.builderHandoffOpen` +- `console.ai.builderHandoffSuperseded` +- `console.ai.builderHandoffTitle` +- `console.ai.changeVerb.addField` +- `console.ai.changeVerb.createMetadata` +- `console.ai.changeVerb.createObject` +- `console.ai.changeVerb.createPackage` +- `console.ai.changeVerb.createSeed` +- `console.ai.changeVerb.deleteField` +- `console.ai.changeVerb.modifyField` +- `console.ai.changeVerb.updateMetadata` +- `console.ai.changesApplied` +- `console.ai.changesApplying` +- `console.ai.changesConfirm` +- `console.ai.changesConfirmHint` +- `console.ai.changesConfirmed` +- `console.ai.changesDrafted` +- `console.ai.changesFailed` +- `console.ai.changesTitle` +- `console.ai.describeAppToBuild` +- `console.ai.designingPlan` +- `console.ai.designingPlanHint.dashboard` +- `console.ai.designingPlanHint.data` +- `console.ai.designingPlanHint.defaults` +- `console.ai.designingPlanHint.finalize` +- `console.ai.designingPlanHint.forms` +- `console.ai.designingPlanHint.lookups` +- `console.ai.designingPlanHint.objects` +- `console.ai.designingPlanHint.relations` +- `console.ai.designingPlanHint.review` +- `console.ai.designingPlanHint.views` +- `console.ai.empty.build.description` +- `console.ai.empty.build.title` +- `console.ai.empty.editApp.askOrChangeDescription` +- `console.ai.empty.editApp.description` +- `console.ai.empty.editApp.title` +- `console.ai.empty.editApp.titleGeneric` +- `console.ai.newApp` +- `console.ai.nextSteps` +- `console.ai.openBuiltApp` +- `console.ai.pendingDrafts.dismissReceipt` +- `console.ai.pendingDrafts.failed` +- `console.ai.pendingDrafts.publish` +- `console.ai.pendingDrafts.publishFromBar` +- `console.ai.pendingDrafts.publishFromBar_one` +- `console.ai.pendingDrafts.publishFromBar_other` +- `console.ai.pendingDrafts.published` +- `console.ai.pendingDrafts.publishedWithFindings` +- `console.ai.pendingDrafts.receipt` +- `console.ai.pendingDrafts.showDraft` +- `console.ai.pendingDrafts.showDraftToPublish` +- `console.ai.pendingDrafts.showDraftToPublish_one` +- `console.ai.pendingDrafts.showDraftToPublish_other` +- `console.ai.planAdjust` +- `console.ai.planApprove` +- `console.ai.planApproveHint` +- `console.ai.planAssumptions` +- `console.ai.planBuilding` +- `console.ai.planBuilt` +- `console.ai.planDeferred` +- `console.ai.planQuestions` +- `console.ai.planReady` +- `console.ai.planTitle` +- `console.ai.previewDraft` +- `console.ai.publishDrafts` +- `console.ai.publishFailed` +- `console.ai.publishOk` +- `console.ai.published` +- `console.ai.seedWarn` +- `console.ai.suggestions.editApp.addDashboard` +- `console.ai.suggestions.editApp.addField` +- `console.ai.suggestions.editApp.addObject` +- `console.ai.suggestions.editApp.addSampleData` +- `console.ai.suggestions.metadataAssistant.buildApp` +- `console.ai.suggestions.metadataAssistant.buildCrm` +- `console.ai.suggestions.metadataAssistant.buildFlow` +- `console.ai.suggestions.metadataAssistant.buildInventory` +- `console.ai.suggestions.metadataAssistant.buildRecruiting` +- `console.ai.switchApp` +- `console.ai.switchAppLabel` +- `console.ai.viewBuiltAppInStudio` +- `excelImport.dismiss` +- `excelImport.importAction` +- `excelImport.importFrom` +- `excelImport.imported` +- `excelImport.imported_one` +- `excelImport.imported_other` +- `excelImport.into` +- `excelImport.noImportableFields` +- `excelImport.opening` +- `excelImport.schemaReadFailed` + +#### Removed from ar, es, fr, pt-BR, ru (14 keys) + +The other locales never carried these keys (plural slots their languages do not select). + +- `chatbot.build.health.sampleRowsLive_many` +- `chatbot.build.health.seeds_many` +- `chatbot.build.health.views_many` +- `chatbot.build.health.widgets_many` +- `chatbot.build.needsAttention_many` +- `chatbot.changes.planTitle_many` +- `chatbot.changes.undoConfirm_many` +- `chatbot.changes.undoWithOthers_many` +- `chatbot.plan.countDashboards_many` +- `chatbot.plan.countObjects_many` +- `chatbot.plan.countViews_many` +- `console.ai.pendingDrafts.publishFromBar_many` +- `console.ai.pendingDrafts.showDraftToPublish_many` +- `excelImport.imported_many` + +#### Removed from ar, ru (14 keys) + +The other locales never carried these keys (plural slots their languages do not select). + +- `chatbot.build.health.sampleRowsLive_few` +- `chatbot.build.health.seeds_few` +- `chatbot.build.health.views_few` +- `chatbot.build.health.widgets_few` +- `chatbot.build.needsAttention_few` +- `chatbot.changes.planTitle_few` +- `chatbot.changes.undoConfirm_few` +- `chatbot.changes.undoWithOthers_few` +- `chatbot.plan.countDashboards_few` +- `chatbot.plan.countObjects_few` +- `chatbot.plan.countViews_few` +- `console.ai.pendingDrafts.publishFromBar_few` +- `console.ai.pendingDrafts.showDraftToPublish_few` +- `excelImport.imported_few` + +#### Removed from en, zh-Hans (6 keys) + +The other locales never carried these keys (the outbound messages were read from en and zh-Hans only). + +- `console.ai.changesConfirmMessage` +- `console.ai.planAnswerMessage` +- `console.ai.planApproveDefaultsMessage` +- `console.ai.planApproveMessage` +- `console.ai.planBuildNewAppMessage` +- `console.ai.planExtendExistingMessage` + +#### Removed from ar (28 keys) + +The other locales never carried these keys (plural slots their languages do not select). + +- `chatbot.build.health.sampleRowsLive_two` +- `chatbot.build.health.sampleRowsLive_zero` +- `chatbot.build.health.seeds_two` +- `chatbot.build.health.seeds_zero` +- `chatbot.build.health.views_two` +- `chatbot.build.health.views_zero` +- `chatbot.build.health.widgets_two` +- `chatbot.build.health.widgets_zero` +- `chatbot.build.needsAttention_two` +- `chatbot.build.needsAttention_zero` +- `chatbot.changes.planTitle_two` +- `chatbot.changes.planTitle_zero` +- `chatbot.changes.undoConfirm_two` +- `chatbot.changes.undoConfirm_zero` +- `chatbot.changes.undoWithOthers_two` +- `chatbot.changes.undoWithOthers_zero` +- `chatbot.plan.countDashboards_two` +- `chatbot.plan.countDashboards_zero` +- `chatbot.plan.countObjects_two` +- `chatbot.plan.countObjects_zero` +- `chatbot.plan.countViews_two` +- `chatbot.plan.countViews_zero` +- `console.ai.pendingDrafts.publishFromBar_two` +- `console.ai.pendingDrafts.publishFromBar_zero` +- `console.ai.pendingDrafts.showDraftToPublish_two` +- `console.ai.pendingDrafts.showDraftToPublish_zero` +- `excelImport.imported_two` +- `excelImport.imported_zero` + +### Studio namespace (`@object-ui/i18n/namespaces/studio`), 9 keys + +Each key below is removed from both locales the namespace ships: en, zh. + +- `engine.studio.aiCopilot` +- `engine.studio.copilot.subject.access` +- `engine.studio.copilot.subject.flow` +- `engine.studio.slot.backToChat` +- `engine.studio.slot.history` +- `engine.studio.slot.openFullPage` +- `engine.studio.slot.pendingCount` +- `engine.studio.slot.planPending` +- `engine.studio.slot.switchHint` diff --git a/.changeset/37682-retire-build-chat-frontend.md b/.changeset/37682-retire-build-chat-frontend.md new file mode 100644 index 00000000000..1131dc9a191 --- /dev/null +++ b/.changeset/37682-retire-build-chat-frontend.md @@ -0,0 +1,35 @@ +--- +'@object-ui/plugin-chatbot': patch +'@object-ui/app-shell': patch +--- + +feat(chatbot)!: the build chat's frontend is retired — the plan, change, build-result and handoff cards, their detectors and the props that fed them are removed + +Clause-②: no +Metadata-protocol: none + + + +**BREAKING** for a host that imports any export or passes any prop listed below. The console's chat (the dock and the full page `/ai/ask`) and Studio keep working; what goes is the code that drew the build conversation: the "Proposed plan" card, the change card, the build-result checklist and publish line, the builder handoff, the Build Doctor drawer, the pending-drafts bar, the spreadsheet import bar and Studio's copilot panel. An old `/ai/build/…` address still lands on the ask chat. + +`publishHealthFromResponse` and `PublishHealth` stay at both entry points of `@object-ui/plugin-chatbot`; the preview's Publish all still reads them. + +In `@object-ui/app-shell`, `ConversationsSidebar` no longer takes `includeAskConversations`: the sidebar lists the active agent's conversations. Delete the prop where a host passes it. + +## What leaves, and what to write instead + +Every name below leaves `@object-ui/plugin-chatbot`; `PublishOutcome` also leaves `@object-ui/plugin-chatbot/core`. `ChatbotEnhancedProps` loses the same 59 props as `FloatingChatbotProps`, and the seam types `SeamToolInvocation` and `SeamChatMessage` lose the same fields as `ChatbotEnhancedToolInvocation` and `ChatbotEnhancedMessage`; the fix for those is the same deletion. + +| FROM | TO | +|:--|:--| +| `detectDraftResult`, `detectProposedPlan`, `detectProposedChanges`, `detectBuilderHandoff`, `detectBuiltAppPackage`, `detectAuthoringVerdict`, `detectReplayOutcome` | delete the import; a tool result is read as plain output, and a pending approval still through `detectPendingApproval` | +| `buildProgressFromDraftReview` | delete the call; nothing draws a build panel any more | +| `DraftReview`, `ProposedPlan`, `ProposedChanges`, `BuilderHandoff`, `ReplayOutcome`, `PublishOutcome` | delete the type import | +| `FloatingChatbotProps.onBuildMaterialized`, `FloatingChatbotProps.onBuildResult`, `FloatingChatbotProps.onDesignBuiltApp`, `FloatingChatbotProps.onDiscardDrafts`, `FloatingChatbotProps.onDraftArtifacts`, `FloatingChatbotProps.onOpenBuilder`, `FloatingChatbotProps.onOpenBuiltApp`, `FloatingChatbotProps.onPlanApprovalPendingChange`, `FloatingChatbotProps.onPreviewDraft`, `FloatingChatbotProps.onPreviewDraftApp`, `FloatingChatbotProps.onPublishDrafts`, `FloatingChatbotProps.onReviewDraft`, `FloatingChatbotProps.onReviewDrafts` | delete the handler; the chat raises no build event any more | +| `FloatingChatbotProps.builderHandoffOpenLabel`, `FloatingChatbotProps.builderHandoffSupersededTitle`, `FloatingChatbotProps.builderHandoffTitleLabel`, `FloatingChatbotProps.changesAppliedLabel`, `FloatingChatbotProps.changesApplyingLabel`, `FloatingChatbotProps.changesConfirmedLabel`, `FloatingChatbotProps.changesConfirmHintLabel`, `FloatingChatbotProps.changesConfirmLabel`, `FloatingChatbotProps.changesConfirmMessage`, `FloatingChatbotProps.changesDraftedLabel`, `FloatingChatbotProps.changesFailedLabel`, `FloatingChatbotProps.changesTitleLabel`, `FloatingChatbotProps.changeVerbLabels`, `FloatingChatbotProps.designBuiltAppLabel`, `FloatingChatbotProps.nextStepsLabel`, `FloatingChatbotProps.openBuiltAppLabel`, `FloatingChatbotProps.planAdjustLabel`, `FloatingChatbotProps.planAnswerMessage`, `FloatingChatbotProps.planApproveDefaultsMessage`, `FloatingChatbotProps.planApproveHintLabel`, `FloatingChatbotProps.planApproveLabel`, `FloatingChatbotProps.planApproveMessage`, `FloatingChatbotProps.planAssumptionsLabel`, `FloatingChatbotProps.planBuildingLabel`, `FloatingChatbotProps.planBuildNewAppMessage`, `FloatingChatbotProps.planBuiltLabel`, `FloatingChatbotProps.planDeferredLabel`, `FloatingChatbotProps.planExtendExistingMessage`, `FloatingChatbotProps.planExtendLabel`, `FloatingChatbotProps.planQuestionsLabel`, `FloatingChatbotProps.planReadyLabel`, `FloatingChatbotProps.planTitleLabel`, `FloatingChatbotProps.previewDraftLabel`, `FloatingChatbotProps.publishDraftsLabel`, `FloatingChatbotProps.publishedLabel`, `FloatingChatbotProps.resolveAppLabel`, `FloatingChatbotProps.resolveFieldLabel`, `FloatingChatbotProps.resolveFieldTypeLabel`, `FloatingChatbotProps.resolveObjectLabel`, `FloatingChatbotProps.toolReviewLabel`, `FloatingChatbotProps.verifiedLabel` | delete the label or message; the card that read it is gone | +| `FloatingChatbotProps.autoPublishDrafts`, `FloatingChatbotProps.fetchPendingDraftCount`, `FloatingChatbotProps.getArtifactAction`, `FloatingChatbotProps.publishFromShellBar`, `FloatingChatbotProps.subscribeMetadataRefresh` | delete the prop; the build panel that read it is gone | +| `ChatbotEnhancedToolInvocation.builderHandoff`, `ChatbotEnhancedToolInvocation.draftReview`, `ChatbotEnhancedToolInvocation.proposedChanges`, `ChatbotEnhancedToolInvocation.proposedPlan`, `ChatbotEnhancedToolInvocation.replayOutcome` | stop reading or setting the field; the mapper no longer lifts it out of a tool result | +| `ChatbotEnhancedMessage.blueprintProgress`, `ChatbotEnhancedMessage.buildProgress` | stop reading or setting the field; no message carries build progress any more | +| `ChatbotLabels.designingPlanHints`, `ChatbotLabels.designingPlanLabel` | delete the label; the plan-design wait is gone | + +The one-line fix: delete every import, prop and field named above. Keeping one fails `tsc` after the upgrade, because none of them is declared any more. diff --git a/ui/packages/app-shell/src/console/__tests__/openPathObjectReaders-12811.test.ts b/ui/packages/app-shell/src/console/__tests__/openPathObjectReaders-12811.test.ts index 81a9efff4f1..08296e33e9e 100644 --- a/ui/packages/app-shell/src/console/__tests__/openPathObjectReaders-12811.test.ts +++ b/ui/packages/app-shell/src/console/__tests__/openPathObjectReaders-12811.test.ts @@ -81,10 +81,6 @@ const OBJECTS_READERS: Record = { why: 'read when a label is resolved for a nav entry without its own label, or a view entry; with { byName: true } (Home, recent rows) the object is read by name', }, 'packages/app-shell/src/hooks/useNavTargetIcon.ts': { kind: 'byName', why: "an object nav entry with no icon, its object's icon by name, as the sidebar reads that entry's label (objectstack#30126)" }, - 'packages/app-shell/src/console/ai/changeCardLabels.ts': { - kind: 'byName', - why: "the chat pane's change card names its objects and fields by label, each object by name when a card asks (the published registry, then the draft overlay); the chat dock mounts the pane on an app open (objectstack#32984)", - }, 'packages/app-shell/src/hooks/useRecentItemLabel.ts': { kind: 'byName', why: "a recent object or view entry's object, by name (objectstack#29121)" }, 'packages/app-shell/src/layout/ActivityObjectLabel.tsx': { kind: 'byName', why: "the inbox's and the home rail's activity rows, each row's object by name (objectstack#29121)" }, 'packages/app-shell/src/views/UserAssignedWorkPanel.tsx': { kind: 'byName', why: "the ban dialog's assigned-work panel, each counted object by name (objectstack#30205)" }, diff --git a/ui/packages/app-shell/src/console/ai/AiChatPage.tsx b/ui/packages/app-shell/src/console/ai/AiChatPage.tsx index 367e81975b8..243df6fba47 100644 --- a/ui/packages/app-shell/src/console/ai/AiChatPage.tsx +++ b/ui/packages/app-shell/src/console/ai/AiChatPage.tsx @@ -14,27 +14,12 @@ */ import React, { useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState } from 'react'; -import { useLocation, useNavigate, useParams, useSearchParams } from 'react-router-dom'; +import { useNavigate, useParams, useSearchParams } from 'react-router-dom'; import { useAuth } from '@object-ui/auth'; import { useObjectTranslation } from '@object-ui/i18n'; -import { useServedAppLabel } from '../../hooks/useServedAppLabel.js'; -import { toast } from 'sonner'; -import { Package as PackageIcon, Sparkles as SparklesIcon } from 'lucide-react'; -import { useAdapter } from '../../providers/AdapterProvider.js'; import { CONSOLE_FULL_HEIGHT } from '../../layout/chromeBannerHost.js'; -import { isPlatformBuiltinApp } from '../../utils/platformApp.js'; -import { useMetadata } from '../../providers/MetadataProvider.js'; -import { formatPublishFailures, type PublishFailure } from '../../views/studio-design/metadataError.js'; -import { useMetadataClient } from '../../views/metadata-admin/useMetadata.js'; import { translateMetadataType } from '../../views/metadata-admin/i18n.js'; -import { useMetadataLocale } from '../../views/metadata-admin/i18n.js'; -import { fieldTypeName } from '../../views/metadata-admin/previews/fieldTypeName.js'; -import { readEnvelopeFailureText } from '../../utils/apiErrorEnvelope.js'; -import { resolveKeyedI18nLabel } from '../../utils/index.js'; import { resolvePublicShareBase } from '../organizations/resolveHomeUrl.js'; -import { ExcelImportBar } from './ExcelImportBar.js'; -import { useChangeCardLabels } from './changeCardLabels.js'; -import { PendingDraftsBar } from './PendingDraftsBar.js'; import { Select, SelectContent, @@ -51,33 +36,19 @@ import { SheetDescription, SheetHeader, SheetTitle, - DropdownMenu, - DropdownMenuTrigger, - DropdownMenuContent, - DropdownMenuItem, - DropdownMenuLabel, - DropdownMenuSeparator, cn, } from '@object-ui/components'; -import { Bug, Check, ChevronDown, PanelLeft, PanelLeftClose, PanelLeftOpen, PanelRightOpen, Share2 } from 'lucide-react'; +import { PanelLeft, PanelLeftClose, PanelLeftOpen, PanelRightOpen, Share2 } from 'lucide-react'; import { ChatbotEnhanced, useObjectChat, useAiModels, useHitlInChat, - detectDraftResult, - detectProposedPlan, - detectBuilderHandoff, detectRecordHandoff, detectRecordWrite, detectAnswerSource, detectSampleDataCleanup, detectPackageRemoval, - detectProposedChanges, - detectReplayOutcome, - detectAuthoringVerdict, - detectBuiltAppPackage, - buildProgressFromDraftReview, storedAnswerData, // The authoring/honest -> runtime message seam (objectui#4399 / PR #4416), // consumed here one hop up from the plugin's own renderers (objectui#4437). @@ -85,7 +56,7 @@ import { toRuntimeMessages, type ChatbotEnhancedToolInvocation, // The ENHANCED message shape — the one `` renders and the - // one this file actually produces (`toolInvocations`, `buildProgress`). + // one this file actually produces (`toolInvocations`, `charts`). // // `ChatbotEnhancedMessage` is the plugin's one name for its RUNTIME // chat-message contract, not an alias of anything. The plugin root publishes @@ -109,18 +80,14 @@ import { agentRouteName, resolveAgentParam, isBuiltinAgentName, - isBuildAgent, agentHasCapability, isAskAgent, - publishHealthFromResponse, detectPendingApproval, type AgentDescriptor, } from '@object-ui/plugin-chatbot/core'; import { AppHeader } from '../../layout/AppHeader.js'; -import { readBuilderHandoffState, type BuilderHandoffState } from '../../layout/chatDockTarget.js'; -import { useChatDockControl, useOpenAssistant } from '../../layout/chatDockControl.js'; -import { markPreviewExit, usePreviewDrafts } from '../../preview/PreviewModeContext.js'; +import { useOpenAssistant } from '../../layout/chatDockControl.js'; import { CONSOLE_TOP_BAR } from '../../layout/consoleTopBar.js'; import { armChatDockExpanded, readDockReturnLocation } from '../../layout/chatDockState.js'; import type { ChatSurfaceContext } from '../../layout/chatSurfaceContext.js'; @@ -131,18 +98,7 @@ import { type AdvertisedShortcut, type ShortcutLabelTranslate, } from '../../chrome/advertisedShortcuts.js'; -import { fetchPendingDraftCount } from '../../preview/draftStatus.js'; -import { appPackageOf } from '../../preview/usePendingDrafts.js'; -import { draftPreviewPath } from '../../preview/draftSurface.js'; -import { - emitCanvasInvalidate, - emitMetadataRefresh, - publishPlanApprovalPending, - subscribeMetadataRefresh, -} from '../../assistant/assistantBus.js'; -import { getRuntimeConfig, getUpgradeUrl, isAiStudioEnabled } from '../../runtime-config.js'; -import { makerConvergedOnBuild, makerVisibleAgents } from '../../hooks/surfaceAgent.js'; -import { useCanAuthorMetadata } from '../../hooks/useCanAuthorMetadata.js'; +import { getUpgradeUrl } from '../../runtime-config.js'; import { useHomePath } from '../../hooks/useHomePath.js'; import { cloudConsoleUrl } from '../marketplace/marketplaceApi.js'; import { useNavigationContext } from '../../context/NavigationContext.js'; @@ -158,17 +114,8 @@ import { useReconcileOnError } from '../../hooks/useReconcileOnError.js'; import { useAiUsage } from '../../hooks/useAiUsage.js'; import { chatConversationScope, chatProductOfAgent } from '../../hooks/chatScope.js'; import { ConversationsSidebar } from './ConversationsSidebar.js'; -import { mainAreaDraftMove, type MainAreaDraftTarget } from './mainAreaDraft.js'; -import { artifactStudioPath } from './artifactStudioPath.js'; -import { studioChangesReviewTarget } from '../../views/studio-design/studioChangesLink.js'; -import { BuildDebugDrawer } from './BuildDebugDrawer.js'; import { isConversationZh } from './conversationLanguage.js'; -import { - resolveAttachmentNoteText, - resolveOutboundAgentText, - type AttachmentNoteKey, - type OutboundAgentTextKey, -} from './outboundAgentText.js'; +import { resolveAttachmentNoteText, type AttachmentNoteKey } from './outboundAgentText.js'; import { resolveApiBase } from './resolveApiBase.js'; import { appOfObject } from './appOfObject.js'; import { RECORD_SECTION_OPENED_STATE, RECORD_SECTION_PARAM } from '../../urlParams.js'; @@ -176,7 +123,6 @@ import { AiUnavailable } from './AiUnavailable.js'; import { recordWriteFormTarget } from '../../utils/recordFormAiDraft.js'; import { useUpload } from '@object-ui/fields'; import { isSpreadsheetAttachment, uploadChatAttachments, chatAttachmentNotes } from './chatAttachments.js'; -import { studioHomePath } from '../../views/studio-design/studioAddress.js'; /** * objectstack#31869 — the console address of the list a chat list link names: @@ -257,7 +203,7 @@ function partToolState(part: HydratedUIMessagePart): ChatbotEnhancedToolInvocati // Hydrated history is never a live stream: the turn that drove these // tools has ENDED, so a dangling mid-stream state means the terminal // state was never snapshotted server-side — promote to Completed or a - // reloaded build conversation shows every tool "Running" forever (the + // reloaded conversation shows every tool "Running" forever (the // same incident mapMessages fixed for the floating-chat path). case 'input-streaming': case 'input-available': @@ -283,7 +229,6 @@ function partToolState(part: HydratedUIMessagePart): ChatbotEnhancedToolInvocati export function hydratedMessagesToChatMessages(messages: HydratedUIMessage[]): ChatMessage[] { return messages.map((message) => { const toolInvocations: ChatbotEnhancedToolInvocation[] = []; - let buildProgress: ReturnType; const content = message.parts .filter((part) => part.type === 'text') .map((part) => part.text ?? '') @@ -296,24 +241,12 @@ export function hydratedMessagesToChatMessages(messages: HydratedUIMessage[]): C const toolCallId = partString(part, 'toolCallId') ?? `${message.id}-${toolName}`; const state = partToolState(part); // The tool RESULT (merged onto the call part by toUIMessages from the - // separate `tool` row) carries the ADR-0033 draft envelope. Rebuild - // `draftReview` so the publish / preview / review affordances return, - // and synthesize the "Built X" panel so the blueprint summary survives - // a refresh (the live progress bar is transient and not persisted). + // separate `tool` row) carries the structured envelopes the cards read. + // Each is lifted here as the live floating-chat mapper + // (extractToolInvocations) lifts it, so a card survives a reload or a + // cache restore. const result = (part as { output?: unknown }).output ?? (part as { result?: unknown }).result; - const draftReview = detectDraftResult(result); - // The pre-build PLAN (propose_blueprint → blueprint_proposed) rides the - // same merged tool result; lift it so the "Proposed plan" review card - // survives a reload on this surface, not just in the floating chat. - const proposedPlan = detectProposedPlan(result); - // The ask-agent's structured decline (suggest_builder → build_handoff) - // and the confirm-before-change preview (changes_proposed) ride the same - // merged tool result. Lift both so the "Open in Builder →" handoff card - // and the "确认修改" changes card survive a reload / cache restore — the - // live floating-chat mapper (extractToolInvocations) already lifts all - // four; this is its hydration counterpart. - const builderHandoff = detectBuilderHandoff(result); const recordHandoff = detectRecordHandoff(result); // cloud#3565 — the record-write card rides the pending approval the // id below is lifted from; it must survive a reload like the rest. @@ -324,18 +257,6 @@ export function hydratedMessagesToChatMessages(messages: HydratedUIMessage[]): C const answerSource = detectAnswerSource(result); const sampleDataCleanup = detectSampleDataCleanup(result); const packageRemoval = detectPackageRemoval(result); - const proposedChanges = detectProposedChanges(result); - // objectui#5695 — a confirm-replay result becomes a terminal state on - // the original 确认修改 card; it must never rehydrate as an ordinary - // draft card (a rolled-back publish would get a live Publish button). - // Mirrors the live mapper's suppression exactly, its one exception - // included: a drafted whole-app build has no confirm card and keeps - // its review, so the thread binds to the package it built - // (objectstack#25887, mapMessages `replayedBuildReview`). - const replayOutcome = detectReplayOutcome(toolCallId, result); - const keepsDraftReview = - !replayOutcome || - (replayOutcome.kind === 'drafted' && Boolean(detectBuiltAppPackage(result))); // objectui#8442 — the two halves of an actionable approval, dropped // here until now, and they arrive from DIFFERENT places: // * the AI SDK's `approval` envelope rides the persisted PART (the @@ -354,8 +275,8 @@ export function hydratedMessagesToChatMessages(messages: HydratedUIMessage[]): C // SERVER path the id exists only inside the result, so `??` never // reaches its right-hand side and this line behaves exactly as // objectui#8442 left it. The fallback exists for the CACHE path, where - // `output` holds one envelope and a turn carrying both a draft and a - // pending approval has to put its draft there — leaving the part key as + // `output` holds one envelope and a turn carrying both another envelope + // and a pending approval has to put that envelope there — leaving the part key as // the only place the id can ride. `sanitizeChatMessagesForCache` is the // only writer of that key. const pendingActionId = @@ -367,22 +288,13 @@ export function hydratedMessagesToChatMessages(messages: HydratedUIMessage[]): C ...(result !== undefined ? { result } : {}), ...(approval ? { approval } : {}), ...(pendingActionId ? { pendingActionId } : {}), - ...(draftReview && keepsDraftReview ? { draftReview } : {}), - ...(proposedPlan ? { proposedPlan } : {}), - ...(builderHandoff ? { builderHandoff } : {}), ...(recordHandoff ? { recordHandoff } : {}), ...(recordWrite ? { recordWrite } : {}), ...(answerSource ? { answerSource } : {}), ...(sampleDataCleanup ? { sampleDataCleanup } : {}), ...(packageRemoval ? { packageRemoval } : {}), - ...(proposedChanges ? { proposedChanges } : {}), - ...(replayOutcome ? { replayOutcome } : {}), ...(part.errorText ? { errorText: String(part.errorText) } : {}), }); - if (!buildProgress) { - const synthesized = buildProgressFromDraftReview(draftReview); - if (synthesized) buildProgress = synthesized; - } } } @@ -402,114 +314,12 @@ export function hydratedMessagesToChatMessages(messages: HydratedUIMessage[]): C role: message.role, content, ...(toolInvocations.length > 0 ? { toolInvocations } : {}), - ...(buildProgress ? { buildProgress } : {}), ...(charts ? { charts } : {}), ...(recordCitations ? { recordCitations } : {}), }; }); } -/** - * #2458 / ADR-0057 Amendment A1.a — the package a build conversation is bound to: - * the explicit `?package=` edit target (ADR-0070) if present, else the most - * recent package a build/draft in THIS thread produced (`draftReview` / - * `builderHandoff` tool results, newest wins). `undefined` = not-yet-bound — - * the magic-flow "New app" draft, which binds the moment its build mints a - * package. Exported for unit testing. - */ -interface PackageBearingMessage { - toolInvocations?: ReadonlyArray<{ - draftReview?: { packageId?: string }; - builderHandoff?: { packageId?: string }; - }>; -} -/** - * objectstack#34610 — what the LAST turn drafted, read off its own tool - * results: the newest draft review after the last user message, or null when - * the turn drafted nothing. `items` are what it drafted; `packageId` is the - * review's (absent when the producer named none); `materialized` is - * ADR-0045's in-turn build. Exported for tests. - */ -export function turnDraftPackage( - messages: readonly { - role?: string; - toolInvocations?: ReadonlyArray<{ - draftReview?: { packageId?: string; materialized?: boolean; items?: ReadonlyArray<{ type: string; name: string }> }; - }>; - }[], -): { packageId?: string; materialized?: boolean; items: ReadonlyArray<{ type: string; name: string }> } | null { - for (let i = messages.length - 1; i >= 0; i--) { - const message = messages[i]; - if (message.role === 'user') return null; - const tools = message.toolInvocations ?? []; - for (let j = tools.length - 1; j >= 0; j--) { - const dr = tools[j].draftReview; - if (dr?.items && dr.items.length > 0) { - return { - items: dr.items, - ...(dr.packageId ? { packageId: dr.packageId } : {}), - ...(dr.materialized ? { materialized: true } : {}), - }; - } - } - } - return null; -} - -export function deriveBoundPackageId( - messages: readonly PackageBearingMessage[], - editPackageId: string | undefined, -): string | undefined { - if (editPackageId) return editPackageId; - let latest: string | undefined; - for (const message of messages) { - for (const tool of message.toolInvocations ?? []) { - const pkg = tool.draftReview?.packageId || tool.builderHandoff?.packageId; - if (pkg) latest = pkg; - } - } - return latest; -} - -/** - * ADR-0057 Amendment A1.b migration read — is a product-only (legacy-scope) - * build thread bound to `packageId` by its OWN history (the latest - * draft/handoff package)? The adopt predicate every `app:X:build` surface - * that runs the migration read hands `useChatConversation`: the full page's - * `?package=` entry and the console dock bound to the current app - * (objectui#10926). One predicate, so whichever surface resolves first adopts - * the same thread. Exported for that second caller. - */ -export function isThreadBoundToPackage( - messages: HydratedUIMessage[], - packageId: string, -): boolean { - return ( - deriveBoundPackageId( - hydratedMessagesToChatMessages(messages) as unknown as readonly PackageBearingMessage[], - undefined, - ) === packageId - ); -} - -// #2466 / ADR-0057 Amendment A1.b — the switcher lists only authorable -// packages. Which apps are code-loaded platform built-ins is one criterion, -// shared with the first-run checklist (`utils/platformApp.ts`); re-exported -// here for the importers that already read it from this module. -export { isPlatformBuiltinApp }; - -/** - * The app-metadata fields this surface reads. `useMetadata().apps` is loosely - * typed and the provider grafts `_packageId` onto each app; narrowing to this - * shape ONCE at the hook boundary lets the call sites read `.name` / - * `.label` / `._packageId` without per-access `as` casts. - */ -interface MetadataAppItem { - name: string; - label?: Parameters[0]; - _packageId?: string; -} - function firstUserMessageText(messages: HydratedUIMessage[]): string | undefined { const message = messages.find((item) => item.role === 'user'); const text = message?.parts @@ -524,7 +334,6 @@ function firstUserMessageText(messages: HydratedUIMessage[]): string | undefined // id, and the route segment all localize to the same label. const PLATFORM_AGENT_LABEL_KEYS: Record = { ask: { key: 'console.ai.agentLabels.ask', defaultValue: 'Ask' }, - build: { key: 'console.ai.agentLabels.build', defaultValue: 'Build' }, }; function localizeAgentLabel( @@ -538,47 +347,14 @@ function localizeAgentLabel( } /** - * Per-surface empty-state branding. The split gives each assistant its own - * identity: the Build surface reads as authoring ("describe an app"), the Ask - * surface as data Q&A ("ask about your records"). Keyed by friendly name; falls - * back to the generic empty state for custom agents. + * Per-surface empty-state branding: the Ask surface reads as data Q&A ("ask + * about your records"). Keyed by friendly name; falls back to the generic + * empty state for custom agents. */ export function agentEmptyState( t: (key: string, options?: Record) => string, agentName: string | undefined, - // ADR-0057 A1.b — when the build surface is opened to EDIT an existing app - // (`?package=`), the empty-state guidance switches from "describe an app to - // build" (magic flow) to "what do you want to change in ". `appLabel` is - // the resolved app name, or undefined until metadata loads (never a raw - // package id — see the caller). - editContext?: { appLabel?: string }, ): { title: string; description: string } { - if (isBuildAgent(agentName)) { - if (editContext) { - return { - title: editContext.appLabel - ? t('console.ai.empty.editApp.title', { - defaultValue: 'Editing “{{app}}”', - app: editContext.appLabel, - }) - : t('console.ai.empty.editApp.titleGeneric', { defaultValue: 'Edit this app' }), - // objectstack#34608 item 4 — the maker's one composer answers data - // questions too (build is a data superset, cloud#1673), so the empty - // state offers both: asking about the app's data, and changing it. - description: t('console.ai.empty.editApp.askOrChangeDescription', { - defaultValue: - 'Ask about this app’s data — counts, lists and summaries — or tell me what to change, and I’ll modify the app in place: a field, an object, a view or a dashboard.', - }), - }; - } - return { - title: t('console.ai.empty.build.title', { defaultValue: 'Build with AI' }), - description: t('console.ai.empty.build.description', { - defaultValue: - 'Describe an app in plain language — I draft the objects, screens and sample data, then you review and publish.', - }), - }; - } if (isAskAgent(agentName)) { return { title: t('console.ai.empty.ask.title', { defaultValue: 'Ask your data' }), @@ -1078,26 +854,6 @@ export function AiChatPage({ apiBase: apiBaseProp, defaultAgent: defaultAgentPro // existing conversation, and the flag is stripped once the fresh id is // mirrored into the URL. const forceNewConversation = searchParams.get('new') !== null; - // ADR-0070 "Edit with AI": the package the user opened to edit (from the app - // list's per-app action). Forwarded to the build agent as `context.packageId` - // so its metadata reads scope to that app and edits bind to it from the first - // message (the agent seeds it as the conversation's active package). - const editPackageId = searchParams.get('package')?.trim() || undefined; - // ADR-0057 P4 — a build prompt handed off from the `ask` surface's - // "Open in Builder →" (suggest_builder), carried as NAVIGATION STATE - // (objectui#12493): the URL is never read for it, so no link can put a message - // in the user's mouth. Seeded as the build surface's first message below, and - // consumed from the history entry as it is seeded, so a reload never re-sends. - const location = useLocation(); - const builderHandoff = useMemo(() => readBuilderHandoffState(location.state), [location.state]); - const handoffPrompt = builderHandoff.handoffPrompt; - // ADR-0057 P4 / cloud#817 — the source `ask` conversation id handed off to the - // Builder alongside the prompt (same navigation state). Forwarded to ChatPane → - // useObjectChat, which sends it as `context.parentConversationId` on the build - // surface's FIRST turn so the agent starts with the ask thread as context - // (never a cold start). The URL-mirror below navigates without state once the - // build conversation id is minted, which drops it. - const handoffParentConversationId = builderHandoff.parentConversationId; const navigate = useNavigate(); // objectui#7373 — both exits out of this page (the "no agent here" screen's // Home button, and the collapse-to-dock landing on a cold deep link) follow @@ -1139,24 +895,13 @@ export function AiChatPage({ apiBase: apiBaseProp, defaultAgent: defaultAgentPro // here, then stripped as the route is canonicalized to `/ai/:agent`. const legacyAgentParam = !agentSegment ? searchParams.get('agent') ?? undefined : undefined; - // cloud#1674 maker convergence — the ONE predicate for this page's ask→build - // collapse (shared with ChatPane's launcher filter via surfaceAgent.ts). - const canAuthorMetadata = useCanAuthorMetadata(); - const makerConverged = makerConvergedOnBuild(agents, canAuthorMetadata, isAiStudioEnabled()); - // App/platform default — used for a bare `/ai` (respecting the legacy // `?agent=`), and as the endpoint while a legacy bare-id link is being // redirected to its real agent surface. - const fallbackAgent = useMemo(() => { - const resolved = resolveDefaultAgentName(agents, legacyAgentParam ?? defaultAgentProp ?? envDefaultAgent); - // cloud#1674 — a maker's bare `/ai` (or an ask-preferring `?agent=` link) - // lands on the converged build composer: ask is no longer a start surface - // for principals who can author. Custom-agent preferences pass through. - if (makerConverged && isAskAgent(resolved)) { - return resolveAgentParam('build', catalogNames) ?? resolved; - } - return resolved; - }, [agents, legacyAgentParam, defaultAgentProp, envDefaultAgent, makerConverged, catalogNames]); + const fallbackAgent = useMemo( + () => resolveDefaultAgentName(agents, legacyAgentParam ?? defaultAgentProp ?? envDefaultAgent), + [agents, legacyAgentParam, defaultAgentProp, envDefaultAgent], + ); // Resolved backend agent name for this surface (route agent wins; else default). const activeAgent = useMemo(() => { @@ -1186,40 +931,18 @@ export function AiChatPage({ apiBase: apiBaseProp, defaultAgent: defaultAgentPro : undefined; // ADR-0057: key the conversation on `(user, app, product)`, not on surface. - // When this full-page surface was deep-linked to edit a package - // (`/ai/build?package=X`, the ADR-0070 "Edit with AI" entry), it shares the - // Studio copilot's `app:X:build` thread instead of forking a separate one; a - // generic `/ai/:agent` visit (no `?package=`) degrades to the product alone, - // unchanged from before. `undefined` while the agent is still resolving. + // The full page names no app, so its scope is the product alone. + // `undefined` while the agent is still resolving. const chatScope = activeAgent - ? chatConversationScope({ appId: editPackageId, product: chatProductOfAgent(activeAgent) }) + ? chatConversationScope({ product: chatProductOfAgent(activeAgent) }) : undefined; - // A1.b migration read: an "Edit with AI" entry (`?package=X`) whose - // `app:X:build` scope has never been cached may still have its thread under - // the product-only key — a build conversation from before bind-on-create - // shipped (or whose re-key never ran in this browser). Offer that thread to - // the resolve; adopt it only if its own history is actually bound to X - // (latest draft/handoff package), so an unrelated product-scoped thread - // never gets hijacked into an app scope. - const activeProduct = activeAgent ? chatProductOfAgent(activeAgent) : undefined; - const legacyBuildScope = - editPackageId && activeProduct === 'build' && chatScope !== activeProduct - ? activeProduct - : undefined; - const adoptLegacyBuildThread = useCallback( - (messages: HydratedUIMessage[]) => - editPackageId !== undefined && isThreadBoundToPackage(messages, editPackageId), - [editPackageId], - ); - // The user the conversation resolves for (none until the agent is known). const conversationUserId = activeAgent ? userId : undefined; const { conversationId, conversationScope, initialMessages, - rekeyScope, ensureConversation, createError: conversationCreateError, } = useChatConversation({ @@ -1233,16 +956,14 @@ export function AiChatPage({ apiBase: apiBaseProp, defaultAgent: defaultAgentPro apiBase, activeId: urlConversationId ?? legacyConversationId, forceNew: forceNewConversation, - legacyScope: legacyBuildScope, - adoptLegacy: legacyBuildScope ? adoptLegacyBuildThread : undefined, }); // #2450 — feed ONLY a scope-matched conversation. Right after a - // launcher/handoff switch (ask→build), `conversationId` still holds the OLD + // launcher switch between agents, `conversationId` still holds the OLD // scope's id until the hook re-resolves — the same stale window the // URL-mirror below already guards. A pane mounted on that stale id is DOOMED // (it remounts the moment the id re-resolves), and the deferred first-send - // replay could consume the handoff stash into it, where the send dies with + // replay could consume the held first message into it, where the send dies with // the unmount before reaching the wire (the observed zero-POST). Handing the // pane `undefined` during the window makes it mount as `…:pending`, hold the // stash, and replay exactly once in the correctly-scoped pane. @@ -1272,65 +993,10 @@ export function AiChatPage({ apiBase: apiBaseProp, defaultAgent: defaultAgentPro if (conversationUserId) markFocusSending(); return ensureConversation(); }, [conversationUserId, markFocusSending, ensureConversation]); - // Bumped whenever the pending ref is set OUT OF BAND (the handoff seed below). - // ChatPane's deferred-send replay lists this in its deps, so it re-runs and - // fires the seed even when the conversation id was ALREADY minted. Without it a - // seed that lands after the id resolves is never replayed — the swallow (the - // replay otherwise only re-runs on id / doSend changes). - const [pendingFirstMessageSeq, setPendingFirstMessageSeq] = useState(0); - const stashPendingFirstMessage = useCallback((m: PendingFirstMessage) => { - pendingFirstMessageRef.current = m; - setPendingFirstMessageSeq((s) => s + 1); - }, []); - - // ADR-0057 P4 — seed the handed-off build prompt as this surface's first - // message; `useDeferredFirstSend` (in ChatPane) replays it once the id lands. - // Gate on the ROUTE (`agentSegment`), known synchronously — NOT on the - // async-resolved `activeAgent`, which can settle AFTER the id is minted and so - // seed too late for the replay to see it (the swallow race, cloud#817 P4 - // follow-up #1). Arm once per history entry (`location.key`), so a SECOND - // handoff re-seeds into the singleton build conversation (#2) even with the - // same text. - // - // objectui#12493 — the prompt is CONSUMED from the history entry as it is - // seeded: the entry's state is replaced by one without `handoffPrompt` (the - // parent conversation id stays until the URL-mirror drops it). Browser - // history keeps state across a reload, so without this a reload would send - // the prompt again. Declared BEFORE the canonicalization and URL-mirror - // effects so that, in a shared effect flush, their later navigations win - // over this same-URL replace. - const lastSeededHandoffKeyRef = useRef(null); - useEffect(() => { - if (!handoffPrompt || agentSegment !== 'build') return; - if (lastSeededHandoffKeyRef.current === location.key) return; - lastSeededHandoffKeyRef.current = location.key; - // Target the stash at the BUILD pane (#2450): mid ask→build transition a - // doomed pane (stale conversation id, about to remount) must not consume it. - stashPendingFirstMessage({ content: handoffPrompt, targetAgentRoute: 'build' }); - const remaining: BuilderHandoffState | null = handoffParentConversationId - ? { parentConversationId: handoffParentConversationId } - : null; - navigate( - { pathname: location.pathname, search: location.search, hash: location.hash }, - { replace: true, state: remaining }, - ); - }, [ - handoffPrompt, - handoffParentConversationId, - agentSegment, - location.key, - location.pathname, - location.search, - location.hash, - navigate, - stashPendingFirstMessage, - ]); - // ── Route canonicalization ────────────────────────────────────────────── // Back-compat redirects (the agent is now in the path): bare `/ai` → the // default agent surface (or the `?agent=` deep-link target); a legacy built-in - // id in the agent slot (`/ai/metadata_assistant`) → its friendly form - // (`/ai/build`). Custom agents already route by their own name and no-op here. + // id in the agent slot → its friendly form. Custom agents already route by their own name and no-op here. // The `?new=1` intent is preserved; the consumed legacy `agent` param is // stripped so it doesn't linger in the canonical URL. useEffect(() => { @@ -1354,20 +1020,11 @@ export function AiChatPage({ apiBase: apiBaseProp, defaultAgent: defaultAgentPro navigate(`/ai/${friendly}${tail}${preservedQuery}`, { replace: true }); return; } - // cloud#1674 — a maker landing on BARE `/ai/ask` (no conversation) is - // redirected to the converged build composer; ask stopped being a start - // surface for authoring principals. WITH a conversation id the link keeps - // working, so existing ask threads (sidebar rows, old deep links) still - // open and render. - if (makerConverged && segmentIsAgent && isAskAgent(activeAgent) && !urlConversationId) { - navigate(`/ai/build${preservedQuery}`, { replace: true }); - return; - } if (segmentIsAgent && agentSegment !== friendly) { const tail = urlConversationId ? `/${encodeURIComponent(urlConversationId)}` : ''; navigate(`/ai/${friendly}${tail}${preservedQuery}`, { replace: true }); } - }, [agents.length, activeAgent, agentSegment, segmentIsAgent, unavailableKnownAgent, makerConverged, urlConversationId, searchString, navigate]); + }, [agents.length, activeAgent, agentSegment, segmentIsAgent, unavailableKnownAgent, urlConversationId, searchString, navigate]); // ── Legacy `/ai/:conversationId` (bare id) ────────────────────────────── // Resolve the conversation's own agent and 301 to `/ai/:agent/:conversationId` @@ -1396,7 +1053,6 @@ export function AiChatPage({ apiBase: apiBaseProp, defaultAgent: defaultAgentPro const [refreshKey, setRefreshKey] = useState(0); const [titleHints, setTitleHints] = useState>({}); const [shareOpen, setShareOpen] = useState(false); - const [debugOpen, setDebugOpen] = useState(false); const [mobileChatsOpen, setMobileChatsOpen] = useState(false); const { collapsed: chatsCollapsed, toggle: toggleChatsCollapsed } = useCollapsibleChatsList(); // Keyboard shortcuts (ChatGPT/Claude parity): ⌘⇧O new chat, ⌘⇧S toggle list. @@ -1455,54 +1111,9 @@ export function AiChatPage({ apiBase: apiBaseProp, defaultAgent: defaultAgentPro // until the hook re-resolves under the new one. Mirroring it would write // it onto the new agent's URL and resume the wrong chat. if (conversationScope !== chatScope) return; - // Preserve the `?package=` binding (ADR-0070 "Edit with AI") across the - // mirror. Without it the rewrite to `/ai/:agent/:conversationId` drops the - // query, so `editPackageId` goes undefined and the conversation scope falls - // back from `app:${package}:${product}` to the product alone (ADR-0057) — - // which would then let a bare `/ai/build` visit resume this package-scoped - // thread. The consumed `agent`/`new` params stay stripped as before. - const pkgQuery = editPackageId ? `?package=${encodeURIComponent(editPackageId)}` : ''; - navigate(`/ai/${activeAgentRoute}/${conversationId}${pkgQuery}`, { replace: true }); - }, [segmentIsAgent, urlConversationId, conversationId, conversationScope, chatScope, activeAgentRoute, editPackageId, navigate]); - - // ── A1.b bind-on-create ───────────────────────────────────────────────── - // The pane's build just minted (or its hydrated history reveals) package - // `pkg` while this conversation is keyed product-only: re-key it to - // `app:${pkg}:build` so a later "Edit with AI" entry for that app resumes - // THIS thread (the untitled-document idiom — named on first save), then put - // `?package=` on the URL so the scope survives a reload. Order matters: - // `rekeyScope` flips `conversationScope` synchronously BEFORE the navigate - // re-render recomputes `chatScope`, so the #2450 scope gate stays matched - // and the mounted pane (and any in-flight stream) is never remounted. - // Only fires with the conversation id already in the URL (post-mirror) — - // the single-navigator rule: the URL-mirror effect above is dormant once - // `urlConversationId` is set, so the two can never fight over the URL from - // stale closures. Idempotent under StrictMode double-effects. - const handlePackageBound = useCallback( - (pkg: string) => { - if (!pkg || editPackageId || activeProduct !== 'build' || !activeAgentRoute) return; - // Re-key only a settled, scope-matched, product-only conversation whose - // id already reached the URL. - if (chatScope !== activeProduct || conversationScope !== chatScope) return; - if (!conversationId || urlConversationId !== conversationId) return; - rekeyScope(chatConversationScope({ appId: pkg, product: activeProduct })); - navigate( - `/ai/${activeAgentRoute}/${encodeURIComponent(conversationId)}?package=${encodeURIComponent(pkg)}`, - { replace: true }, - ); - }, - [ - editPackageId, - activeProduct, - activeAgentRoute, - chatScope, - conversationScope, - conversationId, - urlConversationId, - rekeyScope, - navigate, - ], - ); + // The consumed `agent`/`new` params are stripped by the rewrite. + navigate(`/ai/${activeAgentRoute}/${conversationId}`, { replace: true }); + }, [segmentIsAgent, urlConversationId, conversationId, conversationScope, chatScope, activeAgentRoute, navigate]); const titledRef = useRef>(new Set()); @@ -1623,7 +1234,6 @@ export function AiChatPage({ apiBase: apiBaseProp, defaultAgent: defaultAgentPro userId={userId} apiBase={apiBase} activeAgent={activeAgent} - includeAskConversations={makerConverged} refreshKey={refreshKey} titleHints={titleHints} className="h-full border-r-0" @@ -1642,14 +1252,6 @@ export function AiChatPage({ apiBase: apiBaseProp, defaultAgent: defaultAgentPro publicBaseUrl={publicShareBase} /> )} - {conversationId && agentHasCapability(agents, activeAgent, 'debug') && ( - - )} {/* Uniform `bg-background` across the chat area: the centered chat column is `bg-background`, so a `bg-muted` backdrop here produced a hard seam between the column and its side gutters (read as accidental). The @@ -1666,7 +1268,6 @@ export function AiChatPage({ apiBase: apiBaseProp, defaultAgent: defaultAgentPro userId={userId} apiBase={apiBase} activeAgent={activeAgent} - includeAskConversations={makerConverged} refreshKey={refreshKey} titleHints={titleHints} className="w-72 min-h-0 flex-1 border-r-0" @@ -1707,21 +1308,14 @@ export function AiChatPage({ apiBase: apiBaseProp, defaultAgent: defaultAgentPro conversationId={paneConversationId} requestedConversationId={urlConversationId ?? legacyConversationId} conversationFocus={conversationFocus} - editPackageId={editPackageId} - onPackageBound={handlePackageBound} - canBind={Boolean(urlConversationId)} - parentHandoffConversationId={handoffParentConversationId} initialMessages={paneInitialMessages} pendingFirstMessageRef={pendingFirstMessageRef} - pendingFirstMessageSeq={pendingFirstMessageSeq} ensureConversation={ensureConversationForSend} conversationCreateError={conversationCreateError} selectedModelId={selectedModelId} onSelectedModelChange={setSelectedModelId} onSent={handleSent} onShare={() => setShareOpen(true)} - onDebug={() => setDebugOpen(true)} - showDebug={agentHasCapability(agents, activeAgent, 'debug')} /> @@ -1772,36 +1366,16 @@ interface ChatPaneProps { * none. A draft typed before this pane knew its id is carried into the * replacing pane only while this is unchanged. See {@link useComposerDraftHandoff}. */ requestedConversationId?: string; - /** ADR-0070 "Edit with AI": the package the user opened to edit (from `?package=`), - * forwarded to the build agent as `context.packageId` to scope it to that app. */ - editPackageId?: string; /** * objectstack#30043 — the app the user has selected, by its package: the * console app the dock sits in, whichever agent it runs. Sent as - * `context.activeApp`; absent, `editPackageId` (the app picked for editing) - * is the selection, and with neither the key is omitted, never a placeholder. + * `context.activeApp`; absent, the key is omitted, never a placeholder. */ activeAppPackageId?: string; - /** A1.b bind-on-create: fired when this pane's build history binds to a package - * while the surface has no `?package=` — the page re-keys the conversation to - * `app:${pkg}:build` and writes `?package=` onto the URL. */ - onPackageBound?: (pkg: string) => void; - /** A1.b — true once the conversation id is mirrored into the URL. Binding is - * deferred until then (single-navigator rule vs the page's URL-mirror effect); - * keeping it in the bind effect's deps re-fires the notification when the - * mirror lands, covering a hydrated bound thread opened via bare `/ai/build`. */ - canBind?: boolean; - /** ADR-0057 P4 / cloud#817 — source `ask` conversation id (from the handoff's navigation state), - * forwarded to the build agent's FIRST turn as `context.parentConversationId` so it - * starts with the ask thread as context. Undefined outside a handoff. */ - parentHandoffConversationId?: string; initialMessages: HydratedUIMessage[]; /** Page-owned stash for a first message sent before the conversation id resolved * (survives this pane's id-keyed remount). See {@link useDeferredFirstSend}. */ pendingFirstMessageRef: React.MutableRefObject; - /** Bumps when the page seeds `pendingFirstMessageRef` out of band (handoff), so - * the deferred-send replay re-runs. See {@link useDeferredFirstSend}. */ - pendingFirstMessageSeq?: number; /** objectstack#32031 — creates the conversation on the first send (the host's * `useChatConversation().ensureConversation`); no row exists before it. * See {@link useDeferredFirstSend}. */ @@ -1822,22 +1396,17 @@ interface ChatPaneProps { onSelectedModelChange?: (modelId: string) => void; onSent: (firstUserMessage?: string) => void; onShare: () => void; - /** Opens the Build Doctor drawer (build agent only). */ - onDebug?: () => void; - /** Show the Build Doctor button — true only for build-agent conversations. */ - showDebug?: boolean; /** - * objectstack#34725 — the host draws the panel's one title bar itself (the - * Studio right slot: 属性 | AI 助手, History, widen, Close), so the pane - * omits its own header row: the agent switcher, the app chip, Share and the - * Build Doctor button. The host then offers Share where it chooses. + * objectstack#34725 — the host draws the panel's one title bar itself, so + * the pane omits its own header row: the agent switcher and Share. The host + * then offers Share where it chooses. * @default false */ hideHeader?: boolean; /** - * objectstack#35445 — the host offers Share and the Build Doctor in its own - * title bar (the console drawer's 「···」 menu), so the pane's header row - * draws neither. The rest of the row (the agent switcher, the app chip) stays. + * objectstack#35445 — the host offers Share in its own title bar (the + * console drawer's 「···」 menu), so the pane's header row does not draw it. + * The rest of the row (the agent switcher) stays. * @default false */ actionsInHost?: boolean; @@ -1852,74 +1421,30 @@ export function ChatPane({ apiBase, conversationId, requestedConversationId, - editPackageId, activeAppPackageId, surfaceContext, surfaceArtifactLabel, conversationFocus, - onPackageBound, - canBind, - parentHandoffConversationId, initialMessages, pendingFirstMessageRef, - pendingFirstMessageSeq, ensureConversation, conversationCreateError, selectedModelId: hostSelectedModelId, onSelectedModelChange, onSent, onShare, - onDebug, - showDebug, hideHeader = false, actionsInHost = false, }: ChatPaneProps) { const { t, language } = useObjectTranslation(); const navigate = useNavigate(); - // The advisory seam for this pane's draft-card publish. `useMetadataClient` - // is the layer that hands the console's advisory toast renderer to the - // client, so taking the client from here — rather than firing the route by - // hand — is what makes the runtime authoring gate's per-draft findings reach - // the author at all (objectui#10039). - const metadataClient = useMetadataClient(); // The agent dropdown is a LAUNCHER now (not an in-surface mode toggle): it // navigates to `/ai/:agent`, so it naturally lists custom agents and can stay // always-available. Shown only when there's more than one agent to switch to. - // - // cloud#1674 maker convergence: for an authoring-capable principal the - // built-in `ask` leaves the launcher — build subsumes it (data superset since - // cloud#1673), so Ask/Build stop being peer modes and the maker gets ONE - // composer. Computed INSIDE ChatPane so every host (full `/ai` page, Studio - // copilot, console dock) converges identically. Custom agents stay listed; - // ask conversations stay openable — only the "start here" affordance goes. - const canAuthorMetadata = useCanAuthorMetadata(); - const launcherAgents = makerVisibleAgents(agents, canAuthorMetadata, isAiStudioEnabled()); - const showAgentLauncher = launcherAgents.length > 1; - - // ADR-0057 P4 — the `ask` agent declined an authoring request (suggest_builder). - // Open the full-page BUILD surface seeded with the handoff prompt, sent on - // arrival because the user's click on the card is the action (ADR-0063 - // decline-and-redirect — an explicit, user-initiated switch, never a silent - // re-route). The prompt rides NAVIGATION STATE, never the URL - // (objectui#12493): only this in-app call can set it, so no link can make the - // build agent receive a message the user did not send. Prefer the handoff's - // own packageId, else this surface's edit package (`?package=` only scopes the - // surface; it sends nothing). cloud#817: also carry THIS (ask) thread's id so - // the Builder's first turn starts with the ask conversation as context. - // - // objectstack#34608 — inside the console's drawer this retargets the drawer - // in place; under no drawer host it navigates to `/ai/build` as before. + // objectstack#34608 — inside the console's drawer a pick retargets the + // drawer in place; under no drawer host it navigates. + const showAgentLauncher = agents.length > 1; const openAssistant = useOpenAssistant(); - const openBuilder = useCallback( - (handoff: { prompt: string; packageId?: string }) => { - const pkg = handoff.packageId || editPackageId; - const state: BuilderHandoffState = {}; - if (handoff.prompt) state.handoffPrompt = handoff.prompt; - if (conversationId) state.parentConversationId = conversationId; - openAssistant({ agent: 'build', packageId: pkg }, state); - }, - [openAssistant, editPackageId, conversationId], - ); // cloud#1658 — land the user on the record an `open_record` hand-off names. // The payload has objectName + recordId but the canonical record route needs @@ -1984,52 +1509,6 @@ export function ChatPane({ [navigate], ); - // objectui#12894 — 查看变更并发布 on the applied card of a change the copilot - // saved as a draft (cloud#2924): open Studio's 变更 drawer for the package - // through its one declared way in, `?changes=review` (`studioChangesLink.ts`). - // Inside that package's Studio (the copilot) the param goes onto the current - // location, so the surface stays mounted; anywhere else (this full page, the - // console dock) the link opens the package's Studio with the drawer open. - const location = useLocation(); - const reviewDrafts = useCallback( - (packageId: string) => { - const target = studioChangesReviewTarget(packageId, location); - navigate(target.to, { replace: target.replace }); - }, - [navigate, location], - ); - - // cloud#797 Excel→App: the attached spreadsheet the user can load real rows - // from (into a built object) via ExcelImportBar. Set when a sheet is sent, - // cleared on import/dismiss. `dataSource` drives the wizard's schema + import. - const dataSource = useAdapter(); - // objectui#12894 — 撤销 on the same applied card: `POST - // /packages/:id/discard-drafts`, which drops EVERY pending draft of the - // package (the card asks first when others are pending). Through the SDK - // client the console's adapter holds — `packages.discardDrafts`, typed by the - // spec's `DiscardPackageDraftsResponse` — rather than a second bare fetch of - // the route. A draft the server could not drop is a failure the card shows, - // with the server's reason. Either way every pending-drafts surface re-reads - // on the assistant bus's pulse, Studio's 变更 badge among them. - const discardDrafts = useCallback( - async (packageId: string): Promise<{ ok: boolean; error?: string }> => { - if (!dataSource) return { ok: false }; - try { - const result = await dataSource.getClient().packages.discardDrafts(packageId); - if (!result.success || result.failedCount > 0) { - const reasons = result.failed.map((f) => `${f.type}/${f.name}: ${f.error}`).join('\n'); - return { ok: false, ...(reasons ? { error: reasons } : {}) }; - } - return { ok: true }; - } catch (e) { - return { ok: false, ...(e instanceof Error && e.message ? { error: e.message } : {}) }; - } finally { - emitMetadataRefresh(); - } - }, - [dataSource], - ); - const [pendingSheet, setPendingSheet] = useState(null); // The pane's root, measured by the composer-draft handoff below. const paneRef = useRef(null); // objectstack#33674 — what is typed into the composer before this pane knows @@ -2075,7 +1554,7 @@ export function ChatPane({ }); const allowanceUsedFraction = aiUsage && !aiUsage.pool.unmetered && aiUsage.pool.fraction !== null ? aiUsage.pool.fraction : undefined; - const selectedApp = activeAppPackageId || editPackageId || undefined; + const selectedApp = activeAppPackageId || undefined; // The pick outlives this pane only when the host holds it (see the props). const [paneSelectedModelId, setPaneSelectedModelId] = useState(undefined); const hostHoldsModel = onSelectedModelChange !== undefined; @@ -2100,9 +1579,6 @@ export function ChatPane({ } = useObjectChat({ api: chatApi, conversationId, - // ADR-0057 P4 / cloud#817 — on a handoff, carry the ask thread as the build - // agent's first-turn context (consumed once inside useObjectChat). - parentConversationId: parentHandoffConversationId, // ADR-0028: the user's picked model (or the env default) rides each request. model: effectiveModelId, onError: handleChatError, @@ -2113,12 +1589,6 @@ export function ChatPane({ // when nothing is selected. ...(selectedApp ? { activeApp: selectedApp } : {}), agentName: activeAgent, - // Tell the agent the environment's publish posture so its narration - // matches reality (an auto-published build is live, not "to publish"). - autoPublishAiBuilds: getRuntimeConfig().features.autoPublishAiBuilds, - // ADR-0070 "Edit with AI": scope the build agent to the app the user - // opened to edit. Cloud seeds it as the conversation's active package. - ...(editPackageId ? { packageId: editPackageId } : {}), // cloud#1610 — what the user is currently discussing (advisory; the // transport reads the body per send, so this stays fresh per turn). // The console dock sends the page in view too (objectstack#30043). @@ -2159,7 +1629,7 @@ export function ChatPane({ // (`renderer.tsx`, objectui#4399), with each narrowing decision named and // tested in `chatMessageAdapter.ts`: `'tool'` renders as an assistant bubble, // legacy tool states map to their v6 equivalents, and every render-only key - // (`buildProgress`, `draftReview`, `pendingActionId`, …) is spread through. + // (`charts`, `recordCitations`, `pendingActionId`, …) is spread through. // Memoized on `messages` exactly as those renderers do, so this array's // identity is neither more nor less stable than the hook's own output. // @@ -2177,9 +1647,9 @@ export function ChatPane({ // validator then rejects, so the message vanished on a cache-fallback // reload. Folded, it restores as the assistant bubble it renders as. // - sanitize gates tool serialization on `role === 'assistant'`, so that - // message's tool invocations — including the re-serialized draft envelope - // behind "Review N changes / Publish" — were dropped from the cache - // entirely. Folded, they survive the reload they exist to survive. + // message's tool invocations — including the pending approval a card + // acts on — were dropped from the cache entirely. Folded, they survive + // the reload they exist to survive. // Not reachable from this page's own paths today (hydration and `mapMessages` // both produce runtime roles and v6 states already), so nothing on screen // moves; this closes the hole ahead of a value that can reach it. @@ -2190,63 +1660,10 @@ export function ChatPane({ ); }, [conversationId, runtimeMessages]); - // #772 — the confirm-card SEND messages must match the CONVERSATION's - // language, not the console UI locale: a Chinese thread under an English UI - // was sending "Looks good — build it as proposed." into its own chat. The - // gate (service-ai-studio) accepts both languages, so this is a cosmetic — - // but jarring — mismatch. Button LABELS stay on the UI locale. - // - // That last clause is load-bearing: `planBuildingLabel` had drifted into this - // gate (#2632) and shipped the plan card's only Chinese word to English-UI - // readers while making the zh pack's `console.ai.planBuilding` unreachable for - // zh conversations (#3837). Nothing but OUTBOUND message text belongs below — - // a pin in `packages/i18n/src/__tests__/console-namespace-3546.test.tsx` fails - // if a `*Label` rejoins the gate. - // - // #3896 — the OTHER half of that rule. These sites used to read - // `convZh ? '' : t(key)`, and `t()` is the UI pack, so a zh console - // holding an English conversation sent Chinese into an English thread, and the - // ungated `planAnswerMessage` sent the UI locale in both directions. - // `outboundAgentText` resolves all four from the `zh`/`en` packs by - // conversation language and never consults the UI pack. - // Fold-insensitive, measured: the probe reads `role === 'user'` and the text, - // and the fold only maps `'tool'` -> `'assistant'` — it can neither create nor - // destroy a user turn, and it leaves `content`/`parts` untouched. - const convZh = useMemo( - () => isConversationZh(runtimeMessages) || isConversationZh(initialMessages), - [runtimeMessages, initialMessages], - ); - const outboundText = useCallback( - (key: OutboundAgentTextKey, vars?: Readonly>) => - resolveOutboundAgentText(convZh, key, vars), - [convZh], - ); // The thread so far, read when a turn is prepared (objectstack#34461) // without making the send callbacks change identity on every message. const threadMessagesRef = useRef({ runtimeMessages, initialMessages }); threadMessagesRef.current = { runtimeMessages, initialMessages }; - const planApproveMessage = outboundText('planApproveMessage'); - const planApproveDefaultsMessage = outboundText('planApproveDefaultsMessage'); - // Same rule for the granular change-confirm card. It used to send a hard-coded - // Chinese sentence regardless of the conversation, so an English user clicking - // Confirm flipped the agent into Chinese for the rest of the thread (#2884). - const changesConfirmMessage = outboundText('changesConfirmMessage'); - // Verb column of the change rows. Unlike the message above these are LABELS, - // so they follow the UI locale like every other label on the card. - const changeVerbLabels = useMemo( - () => ({ - create_object: t('console.ai.changeVerb.createObject', { defaultValue: 'Create object' }), - add_field: t('console.ai.changeVerb.addField', { defaultValue: 'Add field' }), - modify_field: t('console.ai.changeVerb.modifyField', { defaultValue: 'Modify field' }), - delete_field: t('console.ai.changeVerb.deleteField', { defaultValue: 'Delete field' }), - create_metadata: t('console.ai.changeVerb.createMetadata', { defaultValue: 'Create' }), - update_metadata: t('console.ai.changeVerb.updateMetadata', { defaultValue: 'Modify' }), - create_seed: t('console.ai.changeVerb.createSeed', { defaultValue: 'Generate sample data' }), - create_package: t('console.ai.changeVerb.createPackage', { defaultValue: 'Create app package' }), - }), - [t], - ); - const hitl = useHitlInChat({ messages: runtimeMessages, apiBase, @@ -2350,11 +1767,6 @@ export function ChatPane({ onSent(content); return; } - // Retain the first sheet so ExcelImportBar can load its REAL rows into a - // built object (cloud#797) — the agent got a brief; the user gets an - // import affordance without re-picking the file. - const firstSheet = attached.find(isSpreadsheetAttachment); - if (firstSheet) setPendingSheet(firstSheet); preparingCountRef.current += 1; setPreparingTurn(true); // The reading starts now, so two turns' uploads overlap; the send waits @@ -2379,7 +1791,7 @@ export function ChatPane({ }); sendChainRef.current = turn; }, - [resetSuppression, sendMessage, onSent, prepareTurn, setPendingSheet], + [resetSuppression, sendMessage, onSent, prepareTurn], ); // Guards the empty-state first send against the conversation-id remount race: @@ -2392,9 +1804,8 @@ export function ChatPane({ conversationId, pendingRef: pendingFirstMessageRef, doSend, - pendingSignal: pendingFirstMessageSeq, // #2450 — this pane's agent surface; a stash targeted at another surface - // (the handoff seed → 'build') is held, never consumed here. + // is held, never consumed here. agentRoute: activeAgent ? agentRouteName(activeAgent) : undefined, ensureConversation, onHeldChange: setHeldFirstMessage, @@ -2416,398 +1827,19 @@ export function ChatPane({ [runtimeMessages, heldFirstMessage], ); - // #2458 / ADR-0057 Amendment A1.a — the package this build conversation is - // bound to, surfaced as a header chip so the edit blast-radius is always - // visible (the Claude-Code-shows-the-repo idiom). The magic flow starts - // unbound ("New app") and binds the moment its build mints a package. - const isBuildSurface = activeAgent ? agentRouteName(activeAgent) === 'build' : false; - const metadata = useMetadata(); - const { apps } = metadata; - // Narrow the loosely-typed provider apps once (see MetadataAppItem) so the - // derivations below read fields without per-access casts. - const metadataApps = apps as MetadataAppItem[] | undefined; - const { appLabel } = useServedAppLabel(); - // Fold-insensitive, measured: this walks every message irrespective of role - // and reads `draftReview`/`builderHandoff`, which the adapter spreads through. - const boundPackageId = useMemo( - () => deriveBoundPackageId(runtimeMessages, editPackageId), - [runtimeMessages, editPackageId], - ); - // objectui#12965 — is this pane on one of its bound package's own Studio - // pillars, i.e. hosted by that package's Studio copilot? The same reading the - // applied card's review door makes (`reviewDrafts` above): the target - // replaces the entry exactly when the location is already on that package's - // Studio pillar. The full-page chat (`/ai/...`) and the console dock - // (`/apps/...`) are never on one. - const onBoundPackageStudio = boundPackageId - ? studioChangesReviewTarget(boundPackageId, location).replace - : false; - const boundPackageLabel = useMemo(() => { - if (!boundPackageId) return undefined; - const app = (metadataApps ?? []).find( - (a) => a._packageId === boundPackageId, - ); - return app ? appLabel(app) : boundPackageId; - }, [boundPackageId, metadataApps, appLabel, t]); - - // ADR-0057 A1.b edit mode — the resolved name of the app being EDITED - // (`?package=`). Returns undefined until the app is found in metadata, so the - // empty-state title falls back to a generic label rather than flashing a raw - // package id (`app.xadv`) while metadata loads. - const editAppLabel = useMemo(() => { - if (!editPackageId) return undefined; - const app = (metadataApps ?? []).find( - (a) => a._packageId === editPackageId, - ); - return app ? appLabel(app) : undefined; - }, [editPackageId, metadataApps, appLabel, t]); - - // objectui#11658 — the plan card's extend-mode scope chip names the existing - // app it would add to by that app's label; the plan carries its machine name. - // An app not (yet) in metadata answers undefined and the chip shows the name. - const resolveAppLabel = useCallback( - (appName: string) => { - const app = (metadataApps ?? []).find((a) => a.name === appName); - return app ? appLabel(app) : undefined; - }, - [metadataApps, appLabel, t], - ); - - // objectstack#32984 — the change card names objects, fields and field types - // by their labels (the producer sends machine names only: 「字段 - // b6bl_quote_item · line_total · currency」). A name the published registry - // does not know is read from the draft overlay (`useChangeCardLabels`); one - // the change is about to create answers undefined, and the card then shows - // the name as given. The revision moves when a message lands or a turn - // starts or ends, which is when a change may have drafted a new name. - const { resolveObjectLabel, resolveFieldLabel } = useChangeCardLabels( - metadata, - metadataClient, - `${shownMessages.length}:${isLoading ? 'turn' : 'idle'}`, - ); - const metadataLocale = useMetadataLocale(); - const resolveFieldTypeLabel = useCallback( - (type: string) => { - const name = fieldTypeName(type, metadataLocale); - return name === type ? undefined : name; - }, - [metadataLocale], - ); - - // Per-surface empty-state branding (Build = authoring, Ask = data Q&A). On the - // build surface, `?package=` flips it to edit mode: "what do you want to - // change in " + change-oriented starters, instead of the from-scratch - // magic-flow guidance. Computed here (not earlier) so it can read the app name. - const editing = isBuildSurface && Boolean(editPackageId); - // objectstack#34608 item 4 — bound to an app, the maker's starters lead with - // two data questions before the change-oriented ones. - const suggestions = useMemo(() => { - if (hydrated.length > 0) return undefined; - const starters = buildAgentSuggestions(activeAgent, activeAgentLabel, t, editing); - return editing ? [...editAppDataSuggestions(t), ...starters] : starters; - }, [hydrated.length, activeAgent, activeAgentLabel, t, editing]); - const emptyState = useMemo( - () => agentEmptyState(t, activeAgent, editing ? { appLabel: editAppLabel } : undefined), - [t, activeAgent, editing, editAppLabel], + const suggestions = useMemo( + () => (hydrated.length > 0 ? undefined : buildAgentSuggestions(activeAgent, activeAgentLabel, t)), + [hydrated.length, activeAgent, activeAgentLabel, t], ); - - // A1.b bind-on-create: report the binding to the page (which re-keys the - // conversation and puts `?package=` on the URL). Deferred behind `canBind` - // (the conversation id must be in the URL first — see ChatPaneProps) AND - // behind the turn being idle: the binding draft lands mid-stream, but - // re-keying then races the live stream (the scope-change refetch reads the - // conversation BEFORE the server persists the turn, and a stream hiccup's - // reconcile can then replace the live thread with that not-yet-persisted - // EMPTY history — the blanked-pane failure seen live). Waiting for - // `isLoading` to drop means the turn is fully persisted server-side, so - // every post-bind read returns the real history; the chip binding a moment - // after the build lands also matches the "named on first save" idiom. The - // deps re-fire the notification on each gate opening (mirror landed, stream - // ended, hydrated reload of a bound thread missing `?package=`). - useEffect(() => { - if (!isBuildSurface || !canBind || !boundPackageId || editPackageId || isLoading) return; - onPackageBound?.(boundPackageId); - }, [isBuildSurface, canBind, boundPackageId, editPackageId, isLoading, onPackageBound]); - - // ── objectstack#34610 — the draft is the main area ───────────────────────── - // The build runs in the console's drawer, and what it builds shows in the - // page beside it (ADR-0057 Amendment A3, ADR-0037 as amended): no nested - // preview. Under a drawer host (`useChatDockControl`, the console and Home - // shells) the main area moves to the app, in the regime the build is in - // (ADR-0045): the real unpublished app for a materialized build or an app - // not published yet, `?preview=draft` for changes to a published app. With - // no drawer host (the Studio copilot, whose design surface already shows - // the drafts) nothing moves; only the per-artifact refresh below runs. - const dockControl = useChatDockControl(); - const showsMainArea = dockControl !== null; - const mainAreaInPreview = usePreviewDrafts(); - // An app the registry lists as materialized-but-unpublished (ADR-0045) - // takes no draft overlay: its changes materialize into it directly, and in - // preview mode its own Publish bar would yield to an empty draft bar. - const unpublishedApp = useCallback( - (segment: string) => - (metadataApps ?? []).some( - (a) => (a._packageId === segment || a.name === segment) && (a as { _unpublished?: unknown })._unpublished === true, - ), - [metadataApps], - ); - // Only a turn THIS pane streamed moves the main area. The chat reports a - // reopened conversation's drafts and materialized builds on mount too, and - // opening an old thread from the history must not navigate the page. - const liveTurnRef = useRef(false); - useEffect(() => { - if (isLoading) liveTurnRef.current = true; - }, [isLoading]); - // Keyed by the conversation: another conversation is another build session, - // and its target (none yet) is not this one's. - const [mainAreaState, setMainAreaState] = useState<{ - conversationId: string | undefined; - target: MainAreaDraftTarget; - } | null>(null); - const mainAreaTarget = - mainAreaState && mainAreaState.conversationId === conversationId ? mainAreaState.target : null; - const shownTargetRef = useRef(null); - // Move the main area to the latest target. Entering draft mode on the page - // the user is on is a query change and happens at once; a move to another - // page waits for the turn to end (A1: the main area keeps its page until - // the build binds, and the bind lands when the turn does), so a stream in - // flight is never cut by a shell switch. - useEffect(() => { - if (!showsMainArea || !mainAreaTarget || shownTargetRef.current === mainAreaTarget) return; - const move = mainAreaDraftMove(mainAreaTarget, location, mainAreaTarget.segment === activeAppPackageId); - if (move && !move.replace && isLoading) return; - shownTargetRef.current = mainAreaTarget; - if (!move) return; - if (move.leavesPreview) markPreviewExit(); - navigate(move.to, { replace: move.replace }); - }, [showsMainArea, mainAreaTarget, location, activeAppPackageId, isLoading, navigate]); - const showAppInMainArea = useCallback( - (packageId: string, opts: { materialized?: boolean; path?: string } = {}) => { - // An edit to a code-shipped app is drafted into its customization pair - // (ADR-0146): the app it shows in is the pair's base. - const segment = appPackageOf(packageId); - const materialized = opts.materialized === true || unpublishedApp(segment); - setMainAreaState({ - conversationId, - target: { - segment, - ...(materialized ? { materialized: true } : {}), - ...(opts.path && !materialized ? { path: opts.path } : {}), - }, - }); - }, - [unpublishedApp, conversationId], - ); - // ADR-0037 Phase 2 — refresh in place per artifact: each drafted artifact is - // announced on the assistant bus, and every metadata tree in preview mode - // (the main area's) refetches that type. Coalesced (~200 ms) by type, so a - // whole-app build is not an invalidation storm. - const invalidateTimerRef = useRef(null); - const pendingInvalidationsRef = useRef>(new Map()); - useEffect( - () => () => { - if (invalidateTimerRef.current) window.clearTimeout(invalidateTimerRef.current); - }, - [], - ); - const queueInvalidations = useCallback((artifacts: ReadonlyArray<{ type: string; name: string }>) => { - for (const a of artifacts) { - if (!pendingInvalidationsRef.current.has(a.type)) pendingInvalidationsRef.current.set(a.type, a); - } - if (invalidateTimerRef.current) window.clearTimeout(invalidateTimerRef.current); - invalidateTimerRef.current = window.setTimeout(() => { - const batch = [...pendingInvalidationsRef.current.values()]; - pendingInvalidationsRef.current.clear(); - for (const inv of batch) emitCanvasInvalidate(inv); - }, 200); - }, []); - const handleDraftArtifacts = useCallback( - (artifacts: Array<{ type: string; name: string }>, appSegment?: string) => { - queueInvalidations(artifacts); - // The app the draft belongs to: the drafted set's own package, else the - // package this conversation is bound to (an edit drafts no `app`). - // Unbound (a new build before its package exists), the page stays. - const segment = appSegment ?? boundPackageId; - if (liveTurnRef.current && segment) showAppInMainArea(segment); - }, - [boundPackageId, showAppInMainArea, queueInvalidations], - ); - // ADR-0045: the build materialized — the real, unlisted app. - const handleBuildMaterialized = useCallback( - (appName: string, opts?: { appSegment?: string }) => { - if (liveTurnRef.current) showAppInMainArea(opts?.appSegment ?? appName, { materialized: true }); - }, - [showAppInMainArea], - ); - // A finished turn refreshes the main area once more (and every pending - // count): an incremental edit can land without growing the drafted set, so - // the per-artifact signal above does not always fire for it. - // - // objectstack#34610 — for the same reason a finished turn that drafted - // shows its app in the main area itself: an edit that re-drafts an artifact - // the conversation already listed (the object a build made, edited in the - // next turn) never reaches `handleDraftArtifacts`, and read live it left the - // main area out of draft mode with the edit pending. - const prevLoadingRef = useRef(false); - useEffect(() => { - const ended = prevLoadingRef.current && !isLoading; - prevLoadingRef.current = isLoading; - if (!ended) return; - if (liveTurnRef.current) { - const drafted = turnDraftPackage(messages); - const segment = drafted?.packageId ?? (drafted ? boundPackageId : undefined); - if (drafted && segment) { - showAppInMainArea(segment, drafted.materialized ? { materialized: true } : {}); - // …and refreshes what it drafted, once the main area is in draft - // mode (the coalescing delay outlasts the move). - queueInvalidations(drafted.items); - } - } - if (shownTargetRef.current) emitMetadataRefresh(); - // Re-runs on the other deps find no turn end (`prevLoadingRef` already - // holds the current value), so only the end of a turn acts. - }, [isLoading, messages, boundPackageId, showAppInMainArea, queueInvalidations]); - - // objectui#12724 — a finished build STAYS on the conversation. The - // built-moment transition (objectui#5799) used to move the thread into the - // Studio workbench the moment a whole-app build existed, and objectui#11658 - // pointed it at the running app; the maintainer's AiBuild ruling retires - // both: the result card's 打开应用 / 在 Studio 中查看 buttons are the only - // ways out, and the user picks one. What stays is the binding: the build's - // package re-keys this conversation to `app::build` (A1.b), the key the - // Studio dock resolves, so 在 Studio 中查看 resumes THIS thread. Derived from - // the persisted envelopes (#2623 lesson: never canvasApp runtime state), so a - // REOPENED built conversation binds too. - const builtPackageId = useMemo(() => { - for (let i = messages.length - 1; i >= 0; i--) { - for (const tool of messages[i].toolInvocations ?? []) { - // Posture-independent: read the raw envelope, not draftReview — an - // auto-publish env rewrites the build envelope to status:'published' - // and the drafted-only lift never fires there. - const pkg = detectBuiltAppPackage(tool.result); - if (pkg) return pkg; - // objectui#10109 — an INCREMENTAL edit's draft review can list the `app` - // it re-staged; the producer's `kind: 'edit'` says it is not a build. - const dr = tool.draftReview; - if (dr?.packageId && dr.kind !== 'edit' && dr.items?.some((it) => it.type === 'app')) { - return dr.packageId; - } - } - } - return undefined; - }, [messages]); - useEffect(() => { - if (!isBuildSurface || isLoading || !canBind || !builtPackageId) return; - // Idempotent: the page's handler re-keys a product-only thread once and - // ignores every later call. - onPackageBound?.(builtPackageId); - }, [isBuildSurface, isLoading, canBind, builtPackageId, onPackageBound]); - - // objectui#5801 — when a tool STAGES or PUBLISHES something, announce it on - // the bus so every pending-drafts surface (Studio topbar, home banner, the - // bar above this pane) converges immediately — previously an agent-staged - // draft lit only the chat bar (its own idle refetch) while the Studio topbar - // count stayed dark until a manual draft save. Precise on purpose: only tool - // results that carry an authoring envelope emit (a drafted result's - // `draftReview`, or a confirm-replay's `replayOutcome`), so an ordinary Q&A - // turn does not trigger an env-wide registry refetch. - // - // objectui#12725 — announced the moment each result LANDS, not when its turn - // ends. The draft is written before the tool answers (the envelope's own - // `draftState` is read after that write), so the Studio 变更 badge can - // count it while the agent is still narrating; waiting for the stream to - // finish left the badge behind the chat card by the whole narration. Each - // result is announced once, keyed by its message and its position in that - // message: a streamed message is re-mapped on every chunk, and a tool part - // without a `toolCallId` is given a fresh random one each time. The results - // already in the thread when this pane mounts are history, not a landing. - // - // A `status: 'published'` result that is not a confirm-replay carries - // neither: the chat lifts `draftReview` for `drafted` only and - // `replayOutcome` for `replay_` ids only. Cloud's `maybeAutoPublish` - // publishes in the turn and rewrites the tool's envelope to it, promoting - // EVERY pending draft of the package, so the badge must re-read on it too - // (objectui#12725). `detectAuthoringVerdict` is the chat package's one - // reader of the authoring envelope, whatever its posture. - const announcedAuthoringRef = useRef | null>(null); - useEffect(() => { - const authored: string[] = []; - for (const message of messages) { - (message.toolInvocations ?? []).forEach((tool, index) => { - if (tool.draftReview || tool.replayOutcome || detectAuthoringVerdict(tool.result)) { - authored.push(`${message.id}#${index}`); - } - }); - } - const announced = announcedAuthoringRef.current; - if (announced === null) { - announcedAuthoringRef.current = new Set(authored); - return; - } - let landed = false; - for (const key of authored) { - if (announced.has(key)) continue; - announced.add(key); - landed = true; - } - if (landed) emitMetadataRefresh(); - }, [messages]); - - // objectui#11666 — the launchers (console FAB, ChatDock edge launcher) show - // a marker while a proposed plan awaits the user's approval, and they are on - // screen only while this pane is NOT mounted. So the chat's own reading — - // `ChatbotEnhanced` reports it from the producer its plan card renders — is - // published on the assistant bus, per conversation and per user, and outlives - // this pane's unmount. `undefined` until the chat has reported once, so a - // mount never announces a reading it has not taken. Nothing here clears it on - // open: an open re-reads the same thread and reports the same state. - const { user: planApprovalUser } = useAuth(); - const planApprovalUserId = planApprovalUser?.id; - // objectstack#25943 — the reading carries the count of items awaiting - // confirmation too (Studio's right slot shows 「N 项待确认」). - const [planApprovalPending, setPlanApprovalPending] = useState(undefined); - const [planApprovalCount, setPlanApprovalCount] = useState(0); - const onPlanApprovalPendingChange = useCallback((pending: boolean, count: number) => { - setPlanApprovalPending(pending); - setPlanApprovalCount(count); - }, []); - useEffect(() => { - if (!conversationId || planApprovalPending === undefined) return; - publishPlanApprovalPending({ - userId: planApprovalUserId, - conversationId, - pending: planApprovalPending, - count: planApprovalCount, - }); - }, [planApprovalUserId, conversationId, planApprovalPending, planApprovalCount]); - - // A1.b switcher menu: every published app with a package identity, deduped - // by package (apps sharing a package share the build thread — the scope is - // per-package). Selecting one navigates to its Edit-with-AI surface, which - // resumes (or mints) that app's own build conversation. - const switchablePackages = useMemo(() => { - const byPackage = new Map(); - for (const app of metadataApps ?? []) { - const pkg = app._packageId; - // Skip platform built-ins (setup / account …): they're code-delivered - // packages the build agent can't author, so they must not appear as - // switch targets — A1.b lists authorable packages only. - if (!pkg || byPackage.has(pkg) || isPlatformBuiltinApp(app)) { - continue; - } - byPackage.set(pkg, appLabel(app)); - } - return Array.from(byPackage, ([id, label]) => ({ id, label })); - }, [metadataApps, appLabel, t]); + const emptyState = useMemo(() => agentEmptyState(t, activeAgent), [t, activeAgent]); // objectstack#37146 — with one launchable agent there is nothing to switch, // so the row names no agent (it read only 「提问」 once the in-app build - // entry closed). Where the host lifts Share and the Build Doctor into its - // own title bar (the drawer, objectstack#35445) and nothing else is left — - // no switcher, no build package chip, no offline note — the row is not - // drawn at all, so no empty band or border remains. - const headerHasContent = - showAgentLauncher || isBuildSurface || !actionsInHost || Boolean(agentsError); + // entry closed). Where the host lifts Share into its own title bar (the + // drawer, objectstack#35445) and nothing else is left — no switcher, no + // offline note — the row is not drawn at all, so no empty band or border + // remains. + const headerHasContent = showAgentLauncher || !actionsInHost || Boolean(agentsError); const headerSlot = (
{showAgentLauncher ? ( - launcherAgents.length <= 3 ? ( + agents.length <= 3 ? ( // Claude-Code-style segmented switcher (mirrors the floating // assistant) so Ask/Build read as visible peer modes, not a hidden // dropdown. Each tab navigates to that agent's surface. Falls back @@ -2829,7 +1861,7 @@ export function ChatPane({ data-testid="ai-chat-agent-picker" aria-label={t('console.ai.switchAssistant', { defaultValue: 'Switch assistant' })} > - {launcherAgents.map((agent) => ( + {agents.map((agent) => ( - {launcherAgents.map((agent) => ( + {agents.map((agent) => ( {localizeAgentLabel(t, agent.name, agent.label)} @@ -2872,85 +1904,9 @@ export function ChatPane({ ) ) : null} - {isBuildSurface ? ( - // A1.b — the binding chip is a SWITCHER now: each app gets its own - // build conversation (the scope is per-package), so picking one here - // switches threads via its Edit-with-AI entry; "New app" opens a - // fresh unbound draft (`?new=1` mints a separate thread). - - - {boundPackageId ? ( - <> - - {boundPackageLabel} - - ) : ( - <> - - {t('console.ai.newApp', { defaultValue: 'New app' })} - - )} - - - - - {t('console.ai.switchAppLabel', { defaultValue: 'Build conversations by app' })} - - {switchablePackages.map((pkg) => ( - { - if (pkg.id !== boundPackageId) { - openAssistant({ agent: 'build', packageId: pkg.id }); - } - }} - > - - {pkg.label} - {pkg.id === boundPackageId ? : null} - - ))} - {switchablePackages.length > 0 ? : null} - openAssistant({ agent: 'build', fresh: true })} - > - - {t('console.ai.newApp', { defaultValue: 'New app' })} - - - - ) : null}
{actionsInHost ? null : (
- {showDebug && onDebug ? ( - - ) : null} - -
- ); -} diff --git a/ui/packages/app-shell/src/console/ai/PendingDraftsBar.tsx b/ui/packages/app-shell/src/console/ai/PendingDraftsBar.tsx deleted file mode 100644 index ba7d7ec35eb..00000000000 --- a/ui/packages/app-shell/src/console/ai/PendingDraftsBar.tsx +++ /dev/null @@ -1,152 +0,0 @@ -/** - * ObjectUI - * Copyright (c) 2024-present ObjectStack Inc. - * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. - */ - -/** - * Standing "unpublished changes" line for the AI build surface - * (objectui#5694), above the composer while the conversation's bound package - * has pending drafts, so it survives scrolling. - * - * objectstack#34610 — the line no longer publishes. The screen has one - * Publish, the shell's bar for the regime the main area is in (the draft bar - * for changes to a published app, the unpublished-app bar for an app not - * published yet), and the chat points to it: - * - * - while the main area shows this package's draft (`draftBarShown`), the - * line says where the Publish is; - * - otherwise it offers to show the draft (`onShowDraft`), which puts the - * main area on the app in draft mode, the draft bar on top. - * - * The count is the package's pending drafts (`_drafts?package=`), the scope - * the draft bar, its changes panel and the draft cards read, so the chat and - * the bar show one number. A publish from the shell's bar lands here as a - * receipt (`subscribePublishReceipt`), shown until the package has pending - * drafts again or the user dismisses it. - * - * Count freshness: re-read when the package binding changes and whenever the - * turn goes idle (`idle` flips true) — tool results that stage drafts land - * inside a turn, so idle edges are exactly when the count can have changed. - * The shared source (objectui#5801) also re-reads on the metadata-refresh - * pulse every publish sends. - */ - -import { useEffect, useState } from 'react'; -import { CheckCircle2, Eye, X } from 'lucide-react'; -import { Button } from '@object-ui/components'; -import { useObjectTranslation } from '@object-ui/i18n'; -import { appPackageOf, usePendingDrafts } from '../../preview/usePendingDrafts.js'; -import { subscribePublishReceipt } from '../../assistant/assistantBus.js'; - -export interface PendingDraftsBarProps { - /** The conversation's bound package (ADR-0057 A1.a); undefined = not bound yet. */ - packageId: string | undefined; - /** True while no turn is streaming — the count refetch trigger. */ - idle: boolean; - /** The main area shows this package's draft, with the draft bar on top. */ - draftBarShown?: boolean; - /** Put the main area on this package's draft; absent where there is no main area to move. */ - onShowDraft?: () => void; -} - -export function PendingDraftsBar({ packageId, idle, draftBarShown = false, onShowDraft }: PendingDraftsBarProps) { - const { t } = useObjectTranslation(); - // The app's drafts, as the shell's draft bar counts them: its package and - // its customization pair (`appDraftPackages`), so the two numbers agree. - const { count, refresh: refreshCount } = usePendingDrafts({ - appPackageId: packageId, - enabled: Boolean(packageId), - }); - // The package a landed publish covered, as its receipt; shown while it is - // this conversation's package and nothing is pending again. - const [receiptFor, setReceiptFor] = useState(null); - - useEffect(() => { - if (!packageId || !idle) return; - void refreshCount(); - }, [idle, packageId, refreshCount]); - - // A publish from the shell's bar that covered this package (or the whole - // environment) is this conversation's receipt. - useEffect(() => { - if (!packageId) return; - return subscribePublishReceipt((r) => { - if (r.packageId === null || appPackageOf(r.packageId) === appPackageOf(packageId)) setReceiptFor(packageId); - }); - }, [packageId]); - // New drafts after the publish supersede its receipt (adjusted while - // rendering, the React pattern for state derived from a changed value). - const pending = (count ?? 0) > 0; - const [wasPending, setWasPending] = useState(pending); - if (pending !== wasPending) { - setWasPending(pending); - if (pending) setReceiptFor(null); - } - const receipt = receiptFor !== null && receiptFor === packageId; - - if (!packageId) return null; - - if (!pending) { - if (!receipt) return null; - return ( -
-
- ); - } - - return ( -
- {/* objectui#13088 — the sentence wraps: it takes the row's free width - and breaks onto more lines, never cut to one with an ellipsis. On a - phone the row is narrower than the sentence, and the cut half is - the part that says where to publish. */} - - {draftBarShown || !onShowDraft - ? t('console.ai.pendingDrafts.publishFromBar', { - defaultValue: '{{count}} unpublished changes. Publish them from the draft bar at the top.', - count, - }) - : t('console.ai.pendingDrafts.showDraftToPublish', { - defaultValue: '{{count}} unpublished changes. Show the draft to review and publish them.', - count, - })} - - {!draftBarShown && onShowDraft ? ( - - ) : null} -
- ); -} diff --git a/ui/packages/app-shell/src/console/ai/__tests__/AiChatPage.appContextComposer-11658.test.tsx b/ui/packages/app-shell/src/console/ai/__tests__/AiChatPage.appContextComposer-11658.test.tsx index 9b020a15eb9..72968987de9 100644 --- a/ui/packages/app-shell/src/console/ai/__tests__/AiChatPage.appContextComposer-11658.test.tsx +++ b/ui/packages/app-shell/src/console/ai/__tests__/AiChatPage.appContextComposer-11658.test.tsx @@ -1,27 +1,17 @@ // Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. /** - * objectui#11658 — what ChatPane hands the composer inside an app. + * objectui#11658 — what ChatPane hands the composer: the ask agent's own + * placeholder, the "Ask {agent}…" template for any other agent, and + * (objectui#12724) the composer footer's newline half of its key hint. * - * Item 2: the build agent scoped to a package (`editPackageId` — the console - * dock in a running app, the Studio dock, `/ai/build?package=`) used the - * generic "Ask {agent}…" placeholder, which a zh-CN user read as「向 构建 提问…」: - * the agent's name, not the task. Inside an app the placeholder names what the - * user can do there. objectui#12724 extends that to the cold-start build - * surface (no package): it reads「描述你想搭建的应用,或要改的地方…」, and the - * composer footer gains the newline half of its key hint. The ask agent and - * an agent that is neither build nor ask keep their placeholders — they are - * the controls. - * - * Item 5 (host half): the plan card's extend-mode chip names the existing app - * by its label. ChatPane hands ChatbotEnhanced a resolver over the apps the - * console's metadata already holds; the chip half is pinned in - * `ChatbotEnhanced.extendChip-11658.test.tsx`. - * - * Same harness as `AiChatPage.planCardLocale.test.tsx`: the real pane under a - * real `I18nProvider`, with `ChatbotEnhanced` replaced by a prop recorder. + * The real pane under a real `I18nProvider`, with `ChatbotEnhanced` replaced + * by a prop recorder. */ +// AiChatPage reads a dropped spreadsheet through `import('@object-ui/plugin-grid')`; load it +// here so collection pays that transform, not a clocked case (check-test-source-alias). +import '@object-ui/plugin-grid'; import '@testing-library/jest-dom/vitest'; import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; import { cleanup, render } from '@testing-library/react'; @@ -78,12 +68,11 @@ window.matchMedia = ((query: string) => ({ })) as unknown as typeof window.matchMedia; const AGENTS = [ - { name: 'build', label: 'Build' }, { name: 'ask', label: 'Ask' }, { name: 'analyst', label: 'Analyst' }, ] as unknown as AgentDescriptor[]; -function renderPane(uiLocale: string, opts: { agent: 'build' | 'ask' | 'analyst'; editPackageId?: string }) { +function renderPane(uiLocale: string, opts: { agent: 'ask' | 'analyst'; activeAppPackageId?: string }) { cleanup(); captured = {}; render( @@ -97,7 +86,7 @@ function renderPane(uiLocale: string, opts: { agent: 'build' | 'ask' | 'analyst' chatApi={`/api/v1/ai/agents/${opts.agent}/chat`} apiBase="/api/v1/ai" conversationId="conv-1" - editPackageId={opts.editPackageId} + activeAppPackageId={opts.activeAppPackageId} initialMessages={[]} pendingFirstMessageRef={{ current: null }} onSent={vi.fn()} @@ -111,8 +100,7 @@ function renderPane(uiLocale: string, opts: { agent: 'build' | 'ask' | 'analyst' beforeEach(() => { window.localStorage.clear(); - // An app-scoped pane asks for that package's pending drafts; serve the probe - // from a double, never the network (objectui#6640). + // Serve any probe from a double, never the network (objectui#6640). vi.stubGlobal( 'fetch', vi.fn(async () => @@ -128,77 +116,19 @@ afterEach(() => { vi.unstubAllGlobals(); }); -describe('objectui#11658 item 2 — the in-app composer names the task, not the agent', () => { - it('zh: the build agent inside an app reads「问问数据,或让我改改这个应用…」', () => { - const props = renderPane('zh', { agent: 'build', editPackageId: 'app.crm' }); - expect(props.placeholder).toBe('问问数据,或让我改改这个应用…'); - expect(String(props.placeholder)).not.toContain('构建'); - }); - - it('en: the build agent inside an app reads "Ask about your data, or ask me to change this app…"', () => { - const props = renderPane('en', { agent: 'build', editPackageId: 'app.crm' }); - expect(props.placeholder).toBe('Ask about your data, or ask me to change this app…'); - }); - - // objectui#12724 retired the old control here ("the cold-start build surface - // keeps 'Ask Build…'"): outside an app the build agent's composer names the - // task too. The third agent below is the control that keeps the template. - it('objectui#12724 zh: the build agent outside an app reads「描述你想搭建的应用,或要改的地方…」', () => { - const props = renderPane('zh', { agent: 'build' }); - expect(props.placeholder).toBe('描述你想搭建的应用,或要改的地方…'); - expect(String(props.placeholder)).not.toContain('构建'); - }); - - it('objectui#12724 en: the build agent outside an app reads "Describe the app you want to build, or what to change…"', () => { - const props = renderPane('en', { agent: 'build' }); - expect(props.placeholder).toBe('Describe the app you want to build, or what to change…'); - expect(String(props.placeholder)).not.toContain('Build…'); - }); - - it('control: an agent that is neither build nor ask keeps the "Ask {agent}…" template', () => { +describe('objectui#11658 — the composer placeholder and footer', () => { + it('an agent other than ask keeps the "Ask {agent}…" template', () => { expect(renderPane('en', { agent: 'analyst' }).placeholder).toBe('Ask Analyst…'); }); it('objectui#12724: the composer footer reads「↵ 发送 · Shift+↵ 换行」', () => { - const labels = renderPane('zh', { agent: 'build' }).labels as Record; + const labels = renderPane('zh', { agent: 'ask' }).labels as Record; expect(labels.sendHint).toBe('发送'); expect(labels.newlineHint).toBe('换行'); }); - it('control: the ask agent keeps its own placeholder, app or not', () => { - expect(renderPane('en', { agent: 'ask', editPackageId: 'app.crm' }).placeholder).toBe('Ask anything…'); - }); -}); - -describe('objectui#11658 item 5 — the host resolves the scope chip\'s app label', () => { - it('a known app resolves to its label in the UI locale; an unknown one to undefined', () => { - const props = renderPane('zh', { agent: 'build', editPackageId: 'app.crm' }); - const resolve = props.resolveAppLabel as (name: string) => string | undefined; - expect(typeof resolve).toBe('function'); - expect(resolve('customer_management')).toBe('客户管理'); - expect(resolve('no_such_app')).toBeUndefined(); - }); -}); - -// objectstack#34608 — acceptance 3: a builder's empty state inside an app -// shows data suggestions (the ruling:「问数据,或者让我改这个应用」), ahead of -// the change starters; the empty-state description names both halves. -describe('the build agent inside an app offers data questions too (objectstack#34608)', () => { - it('en: the starters lead with data questions, then the change starters', () => { - const props = renderPane('en', { agent: 'build', editPackageId: 'app.crm' }); - const suggestions = props.suggestions as string[]; - expect(suggestions.slice(0, 2)).toEqual([ - 'List the 5 most recently created records.', - 'Count records for each object.', - ]); - expect(suggestions.join(' ')).toMatch(/Add a field/); - const labels = props.labels as { emptyDescription: string }; - expect(labels.emptyDescription).toMatch(/Ask about this app’s data/); - }); - - it('control: the from-scratch build surface (no app) offers no data questions', () => { - const props = renderPane('en', { agent: 'build' }); - const suggestions = (props.suggestions as string[] | undefined) ?? []; - expect(suggestions).not.toContain('Count records for each object.'); + it('the ask agent keeps its own placeholder, app or not', () => { + expect(renderPane('en', { agent: 'ask' }).placeholder).toBe('Ask anything…'); + expect(renderPane('en', { agent: 'ask', activeAppPackageId: 'app.crm' }).placeholder).toBe('Ask anything…'); }); }); diff --git a/ui/packages/app-shell/src/console/ai/__tests__/AiChatPage.appliedCardDoors-12894.test.tsx b/ui/packages/app-shell/src/console/ai/__tests__/AiChatPage.appliedCardDoors-12894.test.tsx deleted file mode 100644 index d5a675cd6ba..00000000000 --- a/ui/packages/app-shell/src/console/ai/__tests__/AiChatPage.appliedCardDoors-12894.test.tsx +++ /dev/null @@ -1,276 +0,0 @@ -// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. - -/** - * objectui#12894 (the console wiring) and objectui#12725 phase 6 — what - * `ChatPane` hands `ChatbotEnhanced` for the copilot's applied card, and the - * column it hosts the chat in. - * - * - 查看变更并发布 (`onReviewDrafts`) opens Studio's 变更 drawer through its one - * declared way in, `?changes=review`: on one of the package's Studio pillars - * the param goes onto the current location (replace, nothing remounts; the - * in-place half is pinned end to end in - * `StudioDesignSurface.copilotDoors-12894.test.tsx`); anywhere else — this - * full-page chat, the console dock — the link opens the package's Studio. - * - 撤销 (`onDiscardDrafts`) is the SDK client's `packages.discardDrafts`, and - * is offered only while the console's adapter is up. - * - The chat column is bounded by its parent (`min-w-0`), so the chat follows - * the Studio copilot's slot instead of the min-content width of a one-line - * tool summary. No layout runs here; the measured widths, before and after, - * are on objectui#12725 phase 6's evidence branch. - * - * Same harness as `AiChatPage.appContextComposer-11658.test.tsx`: the real pane, - * with `ChatbotEnhanced` replaced by a prop recorder. - */ - -import '@testing-library/jest-dom/vitest'; -import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; -import { act, cleanup, render, screen } from '@testing-library/react'; -import { MemoryRouter, useLocation } from 'react-router-dom'; -import React from 'react'; - -let captured: Record = {}; -// objectstack#32984 — the conversation the pane reads, and the field a change -// card in it names (the recorder resolves it during its render, as the card does). -let chatMessages: Array<{ id: string; role: string; content: string }> = []; -let cardField: [objectName: string, fieldName: string] | null = null; - -vi.mock('@object-ui/plugin-chatbot', async (importOriginal) => { - const actual = await importOriginal>(); - return { - ...actual, - ChatbotEnhanced: (props: Record) => { - captured = props; - const resolve = props.resolveFieldLabel as ((o: string, f: string) => string | undefined) | undefined; - const named = cardField ? (resolve?.(cardField[0], cardField[1]) ?? cardField[1]) : null; - return ( -
- {named !== null ? {named} : null} -
- ); - }, - useObjectChat: () => ({ - messages: chatMessages, - isLoading: false, - error: undefined, - sendMessage: vi.fn(), - stop: vi.fn(), - reload: vi.fn(), - clear: vi.fn(), - setMessages: vi.fn(), - }), - useAiModels: () => ({ models: [], defaultModelId: undefined }), - }; -}); - -const discardDrafts = vi.fn(); -let adapter: unknown = null; -vi.mock('../../../providers/MetadataProvider', async (importOriginal) => { - const actual = await importOriginal>(); - return { ...actual, useMetadata: () => ({ apps: [] }) }; -}); -// objectstack#32984 — the draft overlay's by-name read, served from `overlay`. -let overlay: Record }> = {}; -const overlayGet = vi.fn(async (_type: string, name: string) => structuredClone(overlay[name]) ?? null); -const overlayClients = new WeakMap(); -vi.mock('../../../views/metadata-admin/useMetadata', async (importOriginal) => { - const actual = await importOriginal>(); - const realHook = actual.useMetadataClient as (environmentId?: string) => object; - return { - ...actual, - useMetadataClient: (environmentId?: string) => { - const real = realHook(environmentId); - const cached = overlayClients.get(real); - if (cached) return cached; - const wrapped: object = Object.assign(Object.create(real) as object, { - withPreviewDrafts: () => ({ get: overlayGet }), - }); - overlayClients.set(real, wrapped); - return wrapped; - }, - }; -}); -vi.mock('../../../providers/AdapterProvider', async (importOriginal) => { - const actual = await importOriginal>(); - return { ...actual, useAdapter: () => adapter }; -}); - -import { I18nProvider } from '@object-ui/i18n'; -import type { AgentDescriptor } from '@object-ui/plugin-chatbot'; -import { ChatPane } from '../AiChatPage'; - -window.matchMedia = ((query: string) => ({ - matches: false, - media: query, - onchange: null, - addEventListener: () => {}, - removeEventListener: () => {}, - addListener: () => {}, - removeListener: () => {}, - dispatchEvent: () => false, -})) as unknown as typeof window.matchMedia; - -const AGENTS = [{ name: 'build', label: 'Build' }] as unknown as AgentDescriptor[]; - -function LocationProbe(): React.ReactElement { - const location = useLocation(); - return
{`${location.pathname}${location.search}`}
; -} - -function renderPane(entry: string, editPackageId?: string) { - cleanup(); - captured = {}; - render( - - - - - - , - ); - return captured; -} - -beforeEach(() => { - window.localStorage.clear(); - chatMessages = []; - cardField = null; - overlay = {}; - overlayGet.mockClear(); - discardDrafts.mockReset(); - adapter = { getClient: () => ({ packages: { discardDrafts } }) }; - vi.stubGlobal( - 'fetch', - vi.fn(async () => - new Response(JSON.stringify({ success: true, data: [] }), { - status: 200, - headers: { 'Content-Type': 'application/json' }, - }), - ), - ); -}); -afterEach(() => { - cleanup(); - vi.unstubAllGlobals(); -}); - -describe('objectui#12894 — 查看变更并发布 opens Studio\'s 变更 drawer', () => { - it('from the full-page chat: the package\'s Studio, with the drawer requested', () => { - const props = renderPane('/ai/build/conv-1?package=app.hcpl', 'app.hcpl'); - const onReviewDrafts = props.onReviewDrafts as (packageId: string) => void; - expect(typeof onReviewDrafts).toBe('function'); - act(() => onReviewDrafts('app.hcpl')); - expect(screen.getByTestId('location').textContent).toBe('/studio/app.hcpl/data?changes=review'); - }); - - it('on one of the package\'s Studio pillars: the same pillar and selection, with the param added', () => { - const props = renderPane('/studio/app.hcpl/data?surface=object%3Ahcpl_borrowing', 'app.hcpl'); - act(() => (props.onReviewDrafts as (packageId: string) => void)('app.hcpl')); - expect(screen.getByTestId('location').textContent).toBe( - '/studio/app.hcpl/data?surface=object%3Ahcpl_borrowing&changes=review', - ); - }); - - it('CONTROL: on ANOTHER package\'s Studio, the card\'s own package opens', () => { - const props = renderPane('/studio/app.other/data', 'app.other'); - act(() => (props.onReviewDrafts as (packageId: string) => void)('app.hcpl')); - expect(screen.getByTestId('location').textContent).toBe('/studio/app.hcpl/data?changes=review'); - }); -}); - -describe('objectui#12894 — 撤销 is the SDK client\'s discard-drafts', () => { - it('calls `packages.discardDrafts` with the card\'s package and reports success', async () => { - discardDrafts.mockResolvedValue({ success: true, discardedCount: 2, failedCount: 0, discarded: [], failed: [] }); - const props = renderPane('/ai/build/conv-1?package=app.hcpl', 'app.hcpl'); - const onDiscardDrafts = props.onDiscardDrafts as (packageId: string) => Promise; - await expect(onDiscardDrafts('app.hcpl')).resolves.toEqual({ ok: true }); - expect(discardDrafts).toHaveBeenCalledWith('app.hcpl'); - }); - - it('a thrown request is a failure carrying its message', async () => { - discardDrafts.mockRejectedValue(new Error('Forbidden')); - const props = renderPane('/ai/build/conv-1?package=app.hcpl', 'app.hcpl'); - await expect((props.onDiscardDrafts as (p: string) => Promise)('app.hcpl')).resolves.toEqual({ - ok: false, - error: 'Forbidden', - }); - }); - - it('CONTROL: with no adapter yet, no 撤销 is offered', () => { - adapter = null; - const props = renderPane('/ai/build/conv-1?package=app.hcpl', 'app.hcpl'); - expect(props.onDiscardDrafts).toBeUndefined(); - expect(typeof props.onReviewDrafts).toBe('function'); - }); -}); - -describe('objectui#12725 — the chat column follows its slot', () => { - it('the column that hosts the chat is bounded by its parent (`min-w-0`), not by its content', () => { - renderPane('/studio/app.hcpl/interfaces', 'app.hcpl'); - const column = screen.getByTestId('ai-chat-panel').closest('[data-chat-column]'); - expect(column).not.toBeNull(); - expect(column!.className.split(/\s+/)).toContain('min-w-0'); - }); -}); - -describe('objectstack#32984 — a field a later change drafts is named on the next card', () => { - /** The pane as `renderPane` draws it, re-rendered in place (same conversation, same pane). */ - function paneElement() { - return ( - - - - - - ); - } - - it('the overlay gains the field after the first card; one message later the card shows its label', async () => { - overlay = { b6bl_quote_item: { name: 'b6bl_quote_item', label: '报价明细', fields: { line_total: { label: '小计' } } } }; - chatMessages = [{ id: 'u1', role: 'user', content: '给报价明细加一个折扣字段' }]; - cardField = ['b6bl_quote_item', 'discount']; - cleanup(); - const view = render(paneElement()); - - // The first card: the overlay is read, and does not hold the field yet. - await act(async () => { - await new Promise((r) => setTimeout(r, 0)); - }); - expect(overlayGet).toHaveBeenCalledWith('object', 'b6bl_quote_item'); - expect(screen.getByTestId('card-field').textContent).toBe('discount'); - - // The change applies (the field is drafted) and the conversation moves on one message. - overlay.b6bl_quote_item!.fields!.discount = { label: '折扣' }; - chatMessages = [...chatMessages, { id: 'a1', role: 'assistant', content: '已添加折扣字段。' }]; - view.rerender(paneElement()); - await act(async () => { - await new Promise((r) => setTimeout(r, 0)); - }); - expect(screen.getByTestId('card-field').textContent).toBe('折扣'); - }); -}); diff --git a/ui/packages/app-shell/src/console/ai/__tests__/AiChatPage.attachmentNotesLanguage-34461.test.tsx b/ui/packages/app-shell/src/console/ai/__tests__/AiChatPage.attachmentNotesLanguage-34461.test.tsx index bbd32a7d8c0..63f7fb9c57e 100644 --- a/ui/packages/app-shell/src/console/ai/__tests__/AiChatPage.attachmentNotesLanguage-34461.test.tsx +++ b/ui/packages/app-shell/src/console/ai/__tests__/AiChatPage.attachmentNotesLanguage-34461.test.tsx @@ -97,7 +97,6 @@ vi.mock('../../../providers/AdapterProvider', async (importOriginal) => ({ vi.mock('../../../hooks/useCanAuthorMetadata', () => ({ useCanAuthorMetadata: () => true })); vi.mock('../ConversationsSidebar', () => ({ ConversationsSidebar: () => null })); -vi.mock('../PendingDraftsBar', () => ({ PendingDraftsBar: () => null })); import { I18nProvider } from '@object-ui/i18n'; import { UploadProvider } from '@object-ui/fields'; diff --git a/ui/packages/app-shell/src/console/ai/__tests__/AiChatPage.attachmentsUpload-32749.test.tsx b/ui/packages/app-shell/src/console/ai/__tests__/AiChatPage.attachmentsUpload-32749.test.tsx index 9df424f90cd..2611991296f 100644 --- a/ui/packages/app-shell/src/console/ai/__tests__/AiChatPage.attachmentsUpload-32749.test.tsx +++ b/ui/packages/app-shell/src/console/ai/__tests__/AiChatPage.attachmentsUpload-32749.test.tsx @@ -106,7 +106,6 @@ vi.mock('../../../providers/AdapterProvider', async (importOriginal) => ({ vi.mock('../../../hooks/useCanAuthorMetadata', () => ({ useCanAuthorMetadata: () => true })); vi.mock('../ConversationsSidebar', () => ({ ConversationsSidebar: () => null })); -vi.mock('../PendingDraftsBar', () => ({ PendingDraftsBar: () => null })); import { I18nProvider } from '@object-ui/i18n'; import { UploadProvider } from '@object-ui/fields'; diff --git a/ui/packages/app-shell/src/console/ai/__tests__/AiChatPage.buildClosedRoutes-36969.test.tsx b/ui/packages/app-shell/src/console/ai/__tests__/AiChatPage.buildClosedRoutes-36969.test.tsx index ef859417853..11277531493 100644 --- a/ui/packages/app-shell/src/console/ai/__tests__/AiChatPage.buildClosedRoutes-36969.test.tsx +++ b/ui/packages/app-shell/src/console/ai/__tests__/AiChatPage.buildClosedRoutes-36969.test.tsx @@ -8,10 +8,10 @@ * - `/ai/build/ID` lands on the default surface WITH the conversation: * `/ai/ask/ID`, and that conversation is the one read, so an old build * thread still opens. It used to land on `/ai/ask` and drop the id. - * - the cloud#1674 maker convergence (a maker's bare `/ai/ask` → `/ai/build`) - * does not fire: there is no build to converge on. - * - regression: where `build` is served, `/ai/build/ID` stays where it is and - * a maker's bare `/ai/ask` still converges on `/ai/build`. + * - a maker's bare `/ai/ask` stays where it is: the cloud#1674 maker + * convergence left with the in-app build entry (objectstack#37682). + * - regression: where `build` is served, `/ai/build/ID` stays where it is, + * and a maker's bare `/ai/ask` still stays on ask. * * Real subjects: `AiChatPage` under a real router, its route canonicalization * and `useChatConversation`. Stand-ins: the agent catalog, the authoring @@ -19,6 +19,9 @@ * empty) and the side panels; `fetch` answers the conversation API from memory. */ +// AiChatPage reads a dropped spreadsheet through `import('@object-ui/plugin-grid')`; load it +// here so collection pays that transform, not a clocked case (check-test-source-alias). +import '@object-ui/plugin-grid'; import '@testing-library/jest-dom/vitest'; import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; import { act, cleanup, render, screen, waitFor } from '@testing-library/react'; @@ -169,10 +172,9 @@ describe('in-app building closed: the catalog serves `ask`, not `build` (objects expect(visited.some((p) => p === '/ai/build' || p === '/ai/ask')).toBe(false); }); - it('the maker convergence (cloud#1674) never sends a maker\'s bare /ai/ask to /ai/build', async () => { + it('a maker\'s bare /ai/ask is never sent to /ai/build', async () => { state.canAuthor = true; visit('/ai/ask'); - // The same window in which the served-build leg below is redirected. await act(async () => { await new Promise((resolve) => setTimeout(resolve, 500)); }); @@ -193,9 +195,13 @@ describe('regression: where the catalog serves `build`, the addresses are unchan expect(visited.every((p) => p === '/ai/build/c-42')).toBe(true); }); - it('a maker\'s bare /ai/ask still converges on /ai/build (cloud#1674)', async () => { + it('a maker\'s bare /ai/ask stays on ask (objectstack#37682)', async () => { state.canAuthor = true; visit('/ai/ask'); - await waitFor(() => expect(visited.some((p) => p.startsWith('/ai/build'))).toBe(true)); + await act(async () => { + await new Promise((resolve) => setTimeout(resolve, 500)); + }); + expect(screen.getByTestId('location')).toHaveTextContent(/^\/ai\/ask/); + expect(visited.some((p) => p.startsWith('/ai/build'))).toBe(false); }); }); diff --git a/ui/packages/app-shell/src/console/ai/__tests__/AiChatPage.buildHistorySurvives.test.tsx b/ui/packages/app-shell/src/console/ai/__tests__/AiChatPage.buildHistorySurvives.test.tsx deleted file mode 100644 index a1621415913..00000000000 --- a/ui/packages/app-shell/src/console/ai/__tests__/AiChatPage.buildHistorySurvives.test.tsx +++ /dev/null @@ -1,292 +0,0 @@ -// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. - -/** - * objectui#2627 — the conversation history must survive the build→preview - * transition, including when the re-key refetch that transition fires fails. - * - * The magic-moment sequence this drives is the reported one: a build turn - * streams, `apply_blueprint`'s draft lands (Live Canvas opens — the full-screen - * chat becomes the chat|preview split), the turn ends, and the A1.b bind-on- - * create effect re-keys the conversation to `app::build` and puts - * `?package=` on the URL. That scope flip re-resolves the SAME conversation — - * one more GET, fired at the instant the server is still finishing the heaviest - * turn of the session. - * - * What made that refetch load-bearing is the pane key: `AiChatPage` mounts - * ``, and the - * thread itself lives inside the chat hook's instance (`useObjectChat` seeds - * from `initialMessages` ONCE — `aiInitialMessages` has `[]` deps and useChat's - * Chat object is created once per mount). So anything that makes - * `conversationId` go momentarily `undefined` does not merely re-render the - * pane, it REPLACES it, and every message goes with the old instance — - * "blueprint card, summary and Publish button all gone, only the composer - * left, until you switch threads and back". - * - * `useChatConversation` already refused to let an EMPTY re-read wipe hydrated - * messages; a FAILED one still cleared the id. This pins both the happy path - * and the failing-refetch path through the real page. - * - * The chat hook is faked, deliberately — but faked to the property that makes - * this bug possible: messages live in the hook INSTANCE and are seeded once at - * mount. A remount is therefore visible as lost history, exactly as in - * production. - */ - -import '@testing-library/jest-dom/vitest'; -import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; -import { act, cleanup, render, screen, waitFor } from '@testing-library/react'; -import { MemoryRouter, Route, Routes } from 'react-router-dom'; -import React from 'react'; - -interface FakeMsg { - id: string; - role: string; - content: string; - toolInvocations?: unknown[]; -} - -/** One entry per `useObjectChat` MOUNT — a remount is what loses the thread. */ -const paneMounts: string[] = []; -/** Drives the faked chat hook from the test body. */ -const chat = { - isLoading: true, - /** Appends a live turn INSIDE the mounted instance (lost on a remount). */ - append: undefined as ((m: FakeMsg) => void) | undefined, -}; -let capturedProps: Record = {}; - -vi.mock('@object-ui/plugin-chatbot', async (importOriginal) => { - const actual = await importOriginal>(); - const React2 = await import('react'); - return { - ...actual, - useAiModels: () => ({ models: [], defaultModelId: undefined }), - useHitlInChat: () => ({ decide: vi.fn(), decisions: {} }), - useObjectChat: (opts: { initialMessages?: FakeMsg[] }) => { - // Seeded ONCE, like the real hook: the thread belongs to this instance. - const [messages, setMessages] = React2.useState( - () => (opts.initialMessages ?? []) as FakeMsg[], - ); - React2.useEffect(() => { - paneMounts.push('mount'); - return () => { - paneMounts.push('unmount'); - }; - }, []); - chat.append = (m: FakeMsg) => setMessages((prev) => [...prev, m]); - return { - messages, - isLoading: chat.isLoading, - error: undefined, - sendMessage: vi.fn(), - stop: vi.fn(), - reload: vi.fn(), - clear: vi.fn(), - setMessages: vi.fn(), - }; - }, - ChatbotEnhanced: (props: Record) => { - capturedProps = props; - const msgs = (props.messages ?? []) as FakeMsg[]; - return ( -
- {msgs.map((m) => m.id).join(',')} -
- ); - }, - }; -}); -vi.mock('@object-ui/plugin-chatbot/core', async (importOriginal) => ({ - ...(await importOriginal()), - useAgents: () => ({ - agents: [{ name: 'metadata_assistant', label: 'Build', capabilities: ['build'] }], - loading: false, - error: undefined, - refetch: vi.fn(), - }), -})); - -vi.mock('@object-ui/auth', async (importOriginal) => { - const actual = await importOriginal>(); - return { ...actual, useAuth: () => ({ user: { id: 'u1' } }) }; -}); -vi.mock('../../../providers/MetadataProvider', async (importOriginal) => { - const actual = await importOriginal>(); - return { ...actual, useMetadata: () => ({ apps: [] }) }; -}); -vi.mock('../../../providers/AdapterProvider', async (importOriginal) => { - const actual = await importOriginal>(); - return { ...actual, useAdapter: () => null }; -}); -// The rail runs its own listing fetch and is not part of this invariant. -vi.mock('../ConversationsSidebar', () => ({ - ConversationsSidebar: () =>
, -})); - - -import { AiChatPage } from '../AiChatPage'; - -// happy-dom has no matchMedia — `useIsMobile` (mobile canvas overlay) needs it. -window.matchMedia = ((query: string) => ({ - matches: false, - media: query, - onchange: null, - addEventListener: () => {}, - removeEventListener: () => {}, - addListener: () => {}, - removeListener: () => {}, - dispatchEvent: () => false, -})) as unknown as typeof window.matchMedia; - -/** The persisted thread the page hydrates from (raw `ServerConversation`). */ -const PERSISTED_TURNS = [ - { id: 'r1', role: 'user', content: [{ type: 'text', text: 'build me a CRM' }] }, - { - id: 'r2', - role: 'assistant', - content: [ - { type: 'text', text: 'Here is the plan.' }, - { type: 'tool-call', toolCallId: 't1', toolName: 'propose_blueprint' }, - ], - }, -]; - -let serverTurns: unknown[] = []; -let conversationGets = 0; -/** 1-based index of the conversation GET that should fail (0 = none fail). */ -let failGetNumber = 0; - -function installFetch(): void { - vi.stubGlobal( - 'fetch', - vi.fn(async (input: RequestInfo | URL, init?: RequestInit) => { - const url = String(input); - const method = init?.method ?? 'GET'; - if (/\/conversations\/conv-1$/.test(url) && method === 'GET') { - conversationGets += 1; - if (conversationGets === failGetNumber) { - return new Response('upstream busy', { status: 502 }); - } - return new Response(JSON.stringify({ id: 'conv-1', messages: serverTurns }), { - status: 200, - headers: { 'Content-Type': 'application/json' }, - }); - } - return new Response(JSON.stringify({ success: true, data: [] }), { - status: 200, - headers: { 'Content-Type': 'application/json' }, - }); - }), - ); -} - -function thread(): string { - return screen.getByTestId('thread').textContent ?? ''; -} - -function mountCount(): number { - return paneMounts.filter((m) => m === 'mount').length; -} - -/** - * Drive the reported sequence and return the pane-mount count at the moment - * the preview opened, so the caller can assert nothing remounted after it. - */ -async function driveBuildToPreview(): Promise { - render( - - - } /> - } /> - - , - ); - await waitFor(() => expect(screen.getByTestId('pane')).toBeInTheDocument()); - // Hydrated: the plan card and the turn that proposed it are on screen. - await waitFor(() => expect(thread()).toBe('r1,r2')); - - // The build turn is now streaming. The server persists a turn at COMPLETION, - // so a read taken right now returns nothing — that is the race window. - serverTurns = []; - - // `apply_blueprint`'s draft lands mid-stream and the thread starts carrying - // the package the build just minted. - await act(async () => { - chat.append?.({ - id: 'live-build', - role: 'assistant', - content: '', - toolInvocations: [ - { toolCallId: 't2', toolName: 'apply_blueprint', draftReview: { packageId: 'app.crm' } }, - ], - }); - (capturedProps.onDraftArtifacts as (a: unknown[], seg?: string) => void)( - [{ type: 'app', name: 'crm' }], - 'app.crm', - ); - }); - // objectstack#34610 — the draft no longer switches this pane's layout (the - // app shows in the console's main area, not in a split beside the chat), so - // the remount this file guards against has one cause fewer. The bind-on- - // create re-key below is still the transition under test. - expect(screen.queryByTestId('ai-chat-split-handle')).not.toBeInTheDocument(); - const mountsAtPreview = mountCount(); - - // The turn ends. A1.b bind-on-create waits for exactly this edge, then - // re-keys the conversation and navigates to `?package=app.crm` — the scope - // flip that fires the re-resolve of the conversation we already hold. - await act(async () => { - chat.isLoading = false; - chat.append?.({ id: 'live-summary', role: 'assistant', content: 'Your CRM is ready.' }); - }); - await act(async () => { - await new Promise((resolve) => setTimeout(resolve, 50)); - }); - return mountsAtPreview; -} - -describe('AiChatPage — the thread survives the build→preview transition (#2627)', () => { - beforeEach(() => { - paneMounts.length = 0; - conversationGets = 0; - failGetNumber = 0; - chat.isLoading = true; - chat.append = undefined; - serverTurns = PERSISTED_TURNS; - localStorage.clear(); - installFetch(); - }); - - afterEach(() => { - cleanup(); - vi.unstubAllGlobals(); - }); - - it('keeps the whole thread when the A1.b re-key refetch succeeds', async () => { - const mountsAtPreview = await driveBuildToPreview(); - - // The re-key DID re-resolve the same conversation (this is the GET the - // failing case below breaks) — otherwise the next test proves nothing. - expect(conversationGets).toBeGreaterThan(1); - expect(mountCount()).toBe(mountsAtPreview); - expect(thread()).toBe('r1,r2,live-build,live-summary'); - }); - - it('keeps the whole thread when that refetch FAILS (the blanked-pane report)', async () => { - // Fail the SECOND conversation GET: the first is the page's hydration, the - // second is the re-key's re-resolve fired as the build turn lands. - failGetNumber = 2; - - const mountsAtPreview = await driveBuildToPreview(); - - expect(conversationGets).toBe(2); - // Before the fix this remounted the pane with an empty seed: the hook - // cleared `conversationId` on the failure, the key fell back to `pending`, - // and the thread went with the discarded instance. - expect(mountCount()).toBe(mountsAtPreview); - expect(thread()).toBe('r1,r2,live-build,live-summary'); - // The plan card / summary / publish affordances all derive from these - // messages, so an empty thread is the reported "everything disappeared". - expect(thread()).not.toBe(''); - }); -}); diff --git a/ui/packages/app-shell/src/console/ai/__tests__/AiChatPage.draftInMainArea-34610.test.tsx b/ui/packages/app-shell/src/console/ai/__tests__/AiChatPage.draftInMainArea-34610.test.tsx deleted file mode 100644 index f65f79c5ab4..00000000000 --- a/ui/packages/app-shell/src/console/ai/__tests__/AiChatPage.draftInMainArea-34610.test.tsx +++ /dev/null @@ -1,348 +0,0 @@ -// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. - -/** - * objectstack#34610 (ui ADR-0057 Amendment A3, ADR-0037 as amended) — under - * the console's drawer host the build's app shows in the MAIN AREA: the pane - * moves the router, it opens no nested preview. - * - * - A draft card's Preview puts the main area on what it drafted, at the - * path `draftPreviewPath` builds (objectui#12968), in draft mode; the app - * draft's Preview opens the app; a materialized build opens the real app. - * - A turn this pane streams moves the main area to the app it drafted, and - * a move to another page waits for the turn to end. - * - Drafts the chat reports outside a live turn (a reopened conversation) - * move nothing. - * - Each drafted artifact refreshes the main area in place: one coalesced - * `emitCanvasInvalidate` per type (ADR-0037 Phase 2). - * - CONTROL: with no drawer host (the Studio copilot) nothing moves and the - * cards get no Preview door. - * - * The chat is faked so the test drives the callbacks the real - * `ChatbotEnhanced` calls (its own Preview buttons are pinned in - * `ChatbotEnhanced.draftPreviewAny-12968.test.tsx`). - */ - -import '@testing-library/jest-dom/vitest'; -import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; -import { act, cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react'; -import React from 'react'; - -type Items = Array<{ type: string; name: string }>; - -const chatCtl = vi.hoisted(() => ({ - setLoading: null as null | ((v: boolean) => void), - setMessages: null as null | ((v: unknown[]) => void), -})); - -vi.mock('@object-ui/plugin-chatbot', async (importOriginal) => { - const actual = await importOriginal>(); - const R = await import('react'); - return { - ...actual, - useAiModels: () => ({ models: [], defaultModelId: undefined }), - useHitlInChat: () => ({ decide: vi.fn(), decisions: {} }), - useObjectChat: () => { - const [isLoading, setLoading] = R.useState(false); - const [messages, setMessages] = R.useState([]); - chatCtl.setLoading = setLoading; - chatCtl.setMessages = setMessages; - return { - messages, - isLoading, - error: undefined, - sendMessage: vi.fn(), - stop: vi.fn(), - reload: vi.fn(), - clear: vi.fn(), - setMessages: vi.fn(), - }; - }, - ChatbotEnhanced: (props: Record) => { - const preview = props.onPreviewDraft as ((items: Items, opts: { appSegment: string }) => void) | undefined; - const previewApp = props.onPreviewDraftApp as - | ((app: string, opts?: { appSegment?: string; materialized?: boolean }) => void) - | undefined; - const drafted = props.onDraftArtifacts as (artifacts: Items, appSegment?: string) => void; - const materialized = props.onBuildMaterialized as (app: string, opts?: { appSegment?: string }) => void; - return ( -
-
- ); - }, - }; -}); -vi.mock('@object-ui/plugin-chatbot/core', async (importOriginal) => ({ - ...(await importOriginal()), - useAgents: () => ({ - agents: [{ name: 'metadata_assistant', label: 'Build', capabilities: ['build'] }], - loading: false, - error: undefined, - refetch: vi.fn(), - }), -})); - -vi.mock('@object-ui/auth', async (importOriginal) => { - const actual = await importOriginal>(); - return { ...actual, useAuth: () => ({ user: { id: 'u1' } }) }; -}); -vi.mock('../../../providers/MetadataProvider', async (importOriginal) => { - const actual = await importOriginal>(); - return { ...actual, useMetadata: () => ({ apps: [] }) }; -}); -vi.mock('../../../providers/AdapterProvider', async (importOriginal) => { - const actual = await importOriginal>(); - return { ...actual, useAdapter: () => null }; -}); -vi.mock('../ConversationsSidebar', () => ({ - ConversationsSidebar: () =>
, -})); - -import { MemoryRouter, Route, Routes, useLocation } from 'react-router-dom'; -import { AiChatPage } from '../AiChatPage'; -import { ChatDockControlProvider, type ChatDockControl } from '../../../layout/chatDockControl'; -import { subscribeCanvasInvalidate, type CanvasInvalidation } from '../../../assistant/assistantBus'; - -window.matchMedia = ((query: string) => ({ - matches: false, - media: query, - onchange: null, - addEventListener: () => {}, - removeEventListener: () => {}, - addListener: () => {}, - removeListener: () => {}, - dispatchEvent: () => false, -})) as unknown as typeof window.matchMedia; - -function installFetch(): void { - vi.stubGlobal( - 'fetch', - vi.fn(async (input: RequestInfo | URL, init?: RequestInit) => { - const url = String(input); - const method = init?.method ?? 'GET'; - if (/\/conversations\/conv-1$/.test(url) && method === 'GET') { - return new Response(JSON.stringify({ id: 'conv-1', messages: [] }), { - status: 200, - headers: { 'Content-Type': 'application/json' }, - }); - } - return new Response(JSON.stringify({ success: true, data: [] }), { - status: 200, - headers: { 'Content-Type': 'application/json' }, - }); - }), - ); -} - -function Where() { - const location = useLocation(); - return
; -} - -const dockControl: ChatDockControl = { expanded: true, fullWindow: false, toggle: vi.fn(), open: vi.fn() }; - -function renderPage({ dockHost }: { dockHost: boolean }) { - const page = ( - - - } /> - - - - - ); - render(dockHost ? {page} : page); -} - -const at = () => screen.getByTestId('where').getAttribute('data-at'); - -beforeEach(() => { - window.localStorage.clear(); - window.sessionStorage.clear(); - installFetch(); -}); - -afterEach(() => { - cleanup(); - vi.unstubAllGlobals(); - vi.useRealTimers(); -}); - -async function paneUp() { - await waitFor(() => expect(screen.getByTestId('pane')).toBeInTheDocument(), { timeout: 4000 }); -} - -describe('the build shows its app in the main area (objectstack#34610)', () => { - it('the cards draw no Publish of their own: the shell bar is the one', async () => { - renderPage({ dockHost: true }); - await paneUp(); - expect(screen.getByTestId('pane')).toHaveAttribute('data-publish-from-shell-bar', 'true'); - }); - - it.each([ - ['a field draft → the object default list', 'preview-field', '/apps/app.k9/k9_task?preview=draft'], - ['a page draft → that page', 'preview-page', '/apps/app.k9/page/k9_home?preview=draft'], - ['the app draft → the app', 'preview-app', '/apps/app.k9?preview=draft'], - ])("%s: a card's Preview moves the main area, in draft mode", async (_label, button, path) => { - renderPage({ dockHost: true }); - await paneUp(); - expect(screen.getByTestId('pane')).toHaveAttribute('data-has-preview-draft', 'true'); - fireEvent.click(screen.getByTestId(button)); - await waitFor(() => expect(at()).toBe(path)); - }); - - it('drafts reported outside a live turn (a reopened conversation) move nothing', async () => { - renderPage({ dockHost: true }); - await paneUp(); - fireEvent.click(screen.getByTestId('drafted')); - fireEvent.click(screen.getByTestId('materialized')); - await new Promise((r) => setTimeout(r, 50)); - expect(at()).toBe('/ai/build/conv-1'); - }); - - it('a live turn moves the main area to the app it drafted, once the turn ends', async () => { - renderPage({ dockHost: true }); - await paneUp(); - act(() => chatCtl.setLoading?.(true)); - fireEvent.click(screen.getByTestId('drafted')); - await new Promise((r) => setTimeout(r, 50)); - // Another page: the move waits, so the stream in flight is not cut. - expect(at()).toBe('/ai/build/conv-1'); - act(() => chatCtl.setLoading?.(false)); - await waitFor(() => expect(at()).toBe('/apps/app.k9?preview=draft')); - }); - - // Read live: an edit re-drafting the object a build made never grows the - // chat's drafted set, so `onDraftArtifacts` stays silent; the turn's own - // draft review still moves the main area when the turn ends. - const editTurn = (packageId: string) => [ - { id: 'u1', role: 'user', content: 'Add a priority field to tasks' }, - { - id: 'a1', - role: 'assistant', - content: 'Done.', - toolInvocations: [ - { - toolCallId: 'call-edit', - toolName: 'apply_edit', - state: 'output-available', - draftReview: { items: [{ type: 'object', name: 'k9_task' }], packageId, kind: 'edit' }, - }, - ], - }, - ]; - - it.each([ - ['in the app package', 'app.k9'], - ["in the app's customization pair (ADR-0146)", 'app.k9.custom'], - ])('a live turn whose drafts the chat reported before still moves at its end: drafted %s', async (_label, pkg) => { - renderPage({ dockHost: true }); - await paneUp(); - act(() => chatCtl.setLoading?.(true)); - act(() => chatCtl.setMessages?.(editTurn(pkg))); - act(() => chatCtl.setLoading?.(false)); - await waitFor(() => expect(at()).toMatch(/^\/apps\/app\.k9\?preview=draft/)); - }); - - // The same turn end refreshes what the turn drafted in place. Read where the - // pane stays mounted (no drawer host: nothing moves, so this route keeps it). - it('…and refreshes what that turn drafted, once, at its end', async () => { - const seen: CanvasInvalidation[] = []; - const unsubscribe = subscribeCanvasInvalidate((inv) => seen.push(inv)); - try { - renderPage({ dockHost: false }); - await paneUp(); - act(() => chatCtl.setLoading?.(true)); - act(() => chatCtl.setMessages?.(editTurn('app.k9'))); - act(() => chatCtl.setLoading?.(false)); - await waitFor(() => expect(seen.map((s) => s.type)).toEqual(['object'])); - // No main area moved: only the conversation's own binding (A1.b) touched the URL. - expect(at()).toMatch(/^\/ai\/build\/conv-1(\?package=app\.k9)?$/); - } finally { - unsubscribe(); - } - }); - - it('CONTROL: a turn that drafted nothing moves nothing at its end', async () => { - renderPage({ dockHost: true }); - await paneUp(); - act(() => chatCtl.setLoading?.(true)); - act(() => - chatCtl.setMessages?.([ - { id: 'u1', role: 'user', content: 'How many tasks are open?' }, - { id: 'a1', role: 'assistant', content: 'Three.' }, - ]), - ); - act(() => chatCtl.setLoading?.(false)); - await new Promise((r) => setTimeout(r, 50)); - expect(at()).toBe('/ai/build/conv-1'); - }); - - it('a materialized build in a live turn opens the real app, no draft overlay (ADR-0045)', async () => { - renderPage({ dockHost: true }); - await paneUp(); - act(() => chatCtl.setLoading?.(true)); - fireEvent.click(screen.getByTestId('materialized')); - act(() => chatCtl.setLoading?.(false)); - await waitFor(() => expect(at()).toBe('/apps/app.k9')); - }); - - it('each drafted artifact refreshes the main area in place: one invalidation per type, coalesced', async () => { - const seen: CanvasInvalidation[] = []; - const unsubscribe = subscribeCanvasInvalidate((inv) => seen.push(inv)); - try { - renderPage({ dockHost: true }); - await paneUp(); - fireEvent.click(screen.getByTestId('drafted')); - fireEvent.click(screen.getByTestId('drafted')); - expect(seen).toEqual([]); - await waitFor(() => expect(seen.map((s) => s.type).sort()).toEqual(['app', 'object'])); - } finally { - unsubscribe(); - } - }); - - it('CONTROL: with no drawer host (the Studio copilot) nothing moves and there is no Preview door', async () => { - renderPage({ dockHost: false }); - await paneUp(); - expect(screen.getByTestId('pane')).toHaveAttribute('data-has-preview-draft', 'false'); - act(() => chatCtl.setLoading?.(true)); - fireEvent.click(screen.getByTestId('drafted')); - act(() => chatCtl.setLoading?.(false)); - await new Promise((r) => setTimeout(r, 50)); - expect(at()).toBe('/ai/build/conv-1'); - }); -}); diff --git a/ui/packages/app-shell/src/console/ai/__tests__/AiChatPage.draftsBarInFlow-12978.test.tsx b/ui/packages/app-shell/src/console/ai/__tests__/AiChatPage.draftsBarInFlow-12978.test.tsx deleted file mode 100644 index a28160ecb76..00000000000 --- a/ui/packages/app-shell/src/console/ai/__tests__/AiChatPage.draftsBarInFlow-12978.test.tsx +++ /dev/null @@ -1,201 +0,0 @@ -// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. - -/** - * objectui#12978 — with a draft pending, the pending-drafts bar - * (`PendingDraftsBar`, objectui#5694) does not cover the composer's input, on - * the full-page chat and in the console dock. - * - * The bar used to float (`absolute bottom-20`) as a sibling of the chat column, - * and on the full-page chat that box sat over the input's first line, so the - * placeholder and the first typed line were hidden. It is a row of the - * composer's own area now, handed to `ChatbotEnhanced` through - * `promptHeaderSlot`, laid out in flow above the input. - * - * ## What is read here, and what is not - * - * This environment runs no layout: every box reads as zeros, so a test that - * compared the bar's box with the input's would pass whatever the layout was. - * What is read instead is the structure that decides the boxes, and each - * reading is one the old float fails: - * - * - the nearest element holding both the bar and the input is the composer's - * own area: it does not hold the conversation (`role="log"`). The float's - * nearest common element was the pane root, which holds the conversation; - * - nothing between the bar and that element, nor between the input and it, - * is taken out of flow (`absolute`, `fixed`, `sticky`, by class or inline - * style). The float's wrapper was `absolute`; - * - in that element the bar's row comes before the input's row, so in that - * flow it is the row above the input, and it sits outside the input's form, - * so its button can never submit the chat. - * - * The boxes themselves were measured in Chromium at 1010 and 1280 px, before - * and after, and are recorded on this change's pull request. - * - * ## Real subjects - * - * The real full-page `AiChatPage`, the real `ChatDockPanel` with its real - * default body (so the dock's own agent resolution decides that it hosts the - * build agent here), the real `ChatPane`, the real `ChatbotEnhanced` and the - * real `PendingDraftsBar`. The stand-ins: the agent catalog (one `build` - * agent), the authoring capability, the signed-in user, the metadata apps - * list, the chat transport (an idle, empty conversation) and the side panels - * this reading does not need. The `fetch` stub answers the drafts ledger with - * one draft for the bound package and the conversation API from memory. - */ - -import '@testing-library/jest-dom/vitest'; -import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; -import { cleanup, render, screen } from '@testing-library/react'; -import { MemoryRouter, Route, Routes } from 'react-router-dom'; -import React from 'react'; - -vi.mock('@object-ui/plugin-chatbot', async (importOriginal) => { - const actual = await importOriginal>(); - return { - ...actual, - useAiModels: () => ({ models: [], defaultModelId: undefined }), - useHitlInChat: () => ({ decide: vi.fn(), decisions: {} }), - useObjectChat: () => ({ - messages: [], - isLoading: false, - error: undefined, - sendMessage: vi.fn(), - stop: vi.fn(), - reload: vi.fn(), - clear: vi.fn(), - setMessages: vi.fn(), - }), - }; -}); -vi.mock('@object-ui/plugin-chatbot/core', async (importOriginal) => ({ - ...(await importOriginal()), - useAgents: () => ({ - agents: [{ name: 'build', label: 'Build' }], - isLoading: false, - error: undefined, - refetch: vi.fn(), - }), -})); -vi.mock('../../../hooks/useCanAuthorMetadata', () => ({ - useCanAuthorMetadata: () => true, -})); -vi.mock('@object-ui/auth', async (importOriginal) => ({ - ...(await importOriginal>()), - useAuth: () => ({ user: { id: 'u1' } }), -})); - -const PKG = 'app.hcpl'; -const APPS = [{ name: 'hcpl', label: 'Library', _packageId: PKG }]; -vi.mock('../../../providers/MetadataProvider', async (importOriginal) => ({ - ...(await importOriginal>()), - useMetadata: () => ({ apps: APPS }), -})); -vi.mock('../../../providers/AdapterProvider', async (importOriginal) => ({ - ...(await importOriginal>()), - useAdapter: () => null, -})); -vi.mock('../../../layout/AiUsageIndicator', () => ({ AiUsageIndicator: () => null })); -vi.mock('../ConversationsSidebar', () => ({ - ConversationsSidebar: () =>
, -})); - - -import { I18nProvider } from '@object-ui/i18n'; -import { ChatDockPanel, type ChatDockState } from '../../../layout/ChatDock'; -import { AiChatPage } from '../AiChatPage'; -import { IN_FLOW_ABOVE, readPlacement } from './inFlowPlacement'; - -window.matchMedia = ((query: string) => ({ - matches: false, - media: query, - onchange: null, - addEventListener: () => {}, - removeEventListener: () => {}, - addListener: () => {}, - removeListener: () => {}, - dispatchEvent: () => false, -})) as unknown as typeof window.matchMedia; - -const API = '/api/v1/ai'; -const DRAFT = { type: 'object', name: 'hcpl_borrowing', label: 'Borrowing', packageId: PKG }; - -beforeEach(() => { - window.localStorage.clear(); - window.sessionStorage.clear(); - let minted = 0; - vi.stubGlobal( - 'fetch', - vi.fn(async (input: RequestInfo | URL, init?: RequestInit) => { - const url = String(input); - const method = init?.method ?? 'GET'; - const json = (body: unknown) => - new Response(JSON.stringify(body), { status: 200, headers: { 'Content-Type': 'application/json' } }); - if (url.includes('/meta/_drafts')) return json({ drafts: [DRAFT] }); - if (url === `${API}/conversations` && method === 'POST') { - minted += 1; - return json({ id: `conv-${minted}`, messages: [] }); - } - if (/\/conversations\/[^/?]+$/.test(url)) return json({ id: 'conv-1', messages: [] }); - return json({ success: true, data: [] }); - }), - ); -}); -afterEach(() => { - cleanup(); - vi.unstubAllGlobals(); -}); - -function dockState(): ChatDockState { - return { - expanded: true, - width: 420, - dragging: false, - fullWindow: false, - setFullWindow: vi.fn(), - toggle: vi.fn(), - expand: vi.fn(), - collapse: vi.fn(), - onResizePointerDown: vi.fn(), - }; -} - -function renderFullPage() { - render( - - - - } /> - } /> - - - , - ); -} - -function renderDock() { - render( - - - - - , - ); -} - -/** How the bar sits against the composer's input, read from the DOM. */ -async function readBarPlacement() { - const bar = await screen.findByTestId('pending-drafts-bar', undefined, { timeout: 4000 }); - const input = document.querySelector('form textarea'); - expect(input).not.toBeNull(); - return readPlacement(bar, input!); -} - -describe('objectui#12978 — the pending-drafts bar is a row above the composer, never over it', () => { - it.each([ - ['the full-page chat', renderFullPage], - ['the console dock, inside the running app', renderDock], - ])('%s, with a draft pending: the bar is laid out in flow above the input', async (_host, mount) => { - mount(); - expect(await readBarPlacement()).toEqual(IN_FLOW_ABOVE); - }); -}); diff --git a/ui/packages/app-shell/src/console/ai/__tests__/AiChatPage.editChips-7709.test.ts b/ui/packages/app-shell/src/console/ai/__tests__/AiChatPage.editChips-7709.test.ts deleted file mode 100644 index 6092bb209f6..00000000000 --- a/ui/packages/app-shell/src/console/ai/__tests__/AiChatPage.editChips-7709.test.ts +++ /dev/null @@ -1,75 +0,0 @@ -/** - * ObjectUI - * Copyright (c) 2024-present ObjectStack Inc. - * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. - */ - -/** - * objectui#7709 — the CALL-SITE half of the maker's EDIT-mode chips. - * - * `packages/i18n/src/__tests__/makerEditChips-v1-scope-7709.test.ts` guards the - * ten packs. This guards the other copy of the same four strings: the - * `defaultValue` fallbacks in `editAppSuggestions()`, which are what a host - * with no I18nProvider (and any locale that ever loses the key) actually - * renders. cloud#1984 measured that shape on the sibling family — the packs - * were reworded and the fallbacks kept promising a status workflow, invisibly, - * on precisely the surface with the least i18n — so the two copies are pinned - * to each other here rather than trusted to stay in step. - * - * So: the edit-mode branch is reached at all, byte-equality with the `en` pack, - * and the same automation/approval-vocabulary ban. - */ -import { describe, it, expect } from 'vitest'; -import { builtInLocales } from '@object-ui/i18n/locales'; -import { buildAgentSuggestions } from '../AiChatPage.js'; - -/** A `t` that misses every key — i.e. what a provider-less host resolves. */ -const missEverything = (_key: string, options?: Record): string => - String(options?.defaultValue ?? _key); - -/** The `en` pack's edit-mode chip block. */ -const enChips = ( - builtInLocales.en as { - console: { ai: { suggestions: { editApp: Record } } }; - } -).console.ai.suggestions.editApp; - -const CHIP_KEYS = ['addField', 'addObject', 'addDashboard', 'addSampleData'] as const; - -/** The English half of the i18n suite's banned vocabulary. @see makerEditChips-v1-scope-7709 */ -const BANNED_EN = ['alert', 'remind', 'notif', 'automat', 'workflow', 'trigger', 'schedule', 'approv']; - -const editChips = () => buildAgentSuggestions('build', 'Build', missEverything, true); - -describe('editAppSuggestions — the build agent`s four edit-mode chips (objectui#7709)', () => { - it('renders the edit-mode starters when the surface is bound to an app', () => { - const chips = editChips(); - expect(chips).toHaveLength(4); - // The `editing` flag is what selects this family; without it the from- - // scratch five are rendered and this suite would be guarding nothing. - expect(buildAgentSuggestions('build', 'Build', missEverything)).toHaveLength(5); - }); - - it('every `defaultValue` is byte-equal to the en pack', () => { - expect(editChips()).toEqual(CHIP_KEYS.map((k) => enChips[k])); - }); - - it('no fallback promises autonomous behaviour', () => { - for (const chip of editChips()) { - const hits = BANNED_EN.filter((term) => chip.toLowerCase().includes(term)); - expect(hits, chip).toEqual([]); - } - }); - - it('the control: the retired wording WOULD have been flagged', () => { - // Non-vacuity, same reasoning as the pack-side suite: a banned list that - // has stopped matching anything passes the assertion above in silence. - const retired = 'Add an automation — an approval, a status flow, or a notification.'; - const hits = BANNED_EN.filter((term) => retired.toLowerCase().includes(term)); - expect(hits).toContain('automat'); - expect(hits).toContain('approv'); - expect(hits).toContain('notif'); - }); -}); diff --git a/ui/packages/app-shell/src/console/ai/__tests__/AiChatPage.firstMessageDrawnAtOnce-33420.test.tsx b/ui/packages/app-shell/src/console/ai/__tests__/AiChatPage.firstMessageDrawnAtOnce-33420.test.tsx index efa13cb1787..7771de0fe85 100644 --- a/ui/packages/app-shell/src/console/ai/__tests__/AiChatPage.firstMessageDrawnAtOnce-33420.test.tsx +++ b/ui/packages/app-shell/src/console/ai/__tests__/AiChatPage.firstMessageDrawnAtOnce-33420.test.tsx @@ -52,6 +52,9 @@ * once. CONTROLS: a load that answers sends once; a 404 creates a new one. */ +// AiChatPage reads a dropped spreadsheet through `import('@object-ui/plugin-grid')`; load it +// here so collection pays that transform, not a clocked case (check-test-source-alias). +import '@object-ui/plugin-grid'; import '@testing-library/jest-dom/vitest'; import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; import { act, cleanup, fireEvent, render, screen, waitFor, within } from '@testing-library/react'; @@ -92,7 +95,6 @@ vi.mock('../../../hooks/useCanAuthorMetadata', () => ({ useCanAuthorMetadata: () vi.mock('../../../layout/AiUsageIndicator', () => ({ AiUsageIndicator: () => null })); vi.mock('../ConversationsSidebar', () => ({ ConversationsSidebar: () => null })); -vi.mock('../PendingDraftsBar', () => ({ PendingDraftsBar: () => null })); import { I18nProvider } from '@object-ui/i18n'; import { AiChatPage, useComposerDraftHandoff } from '../AiChatPage'; diff --git a/ui/packages/app-shell/src/console/ai/__tests__/AiChatPage.handoffNeverFromUrl-12493.test.tsx b/ui/packages/app-shell/src/console/ai/__tests__/AiChatPage.handoffNeverFromUrl-12493.test.tsx deleted file mode 100644 index f9509eed7ac..00000000000 --- a/ui/packages/app-shell/src/console/ai/__tests__/AiChatPage.handoffNeverFromUrl-12493.test.tsx +++ /dev/null @@ -1,282 +0,0 @@ -// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. - -/** - * objectui#12493 — a URL parameter never sends a message on the user's behalf. - * - * The build surface sends its seeded first message with no further user - * action. The ADR-0057 P4 Builder handoff ("Open in Builder →" on the `ask` - * surface) used to carry that seed as `?handoffPrompt=`, so any link a - * signed-in user opened could put a first message in their mouth. The handoff - * now rides react-router navigation state, which only the app's own in-app - * `navigate()` can set, and the page no longer reads the parameter at all. - * - * Pins: - * - a page loaded with `?handoffPrompt=` sends nothing; - * - the in-app handoff (the real `openBuilder` producer, reached through the - * pane's `onOpenBuilder`) still lands its text on the build pane, once; - * - a reload of that history entry (state survives a reload) does not send it - * again; - * - CONTROL: a user-typed first message sends. - * - * The chat hook is faked to record every `sendMessage` call — that is the - * transport boundary this invariant is about. - */ - -import '@testing-library/jest-dom/vitest'; -import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; -import { act, cleanup, render, screen, waitFor } from '@testing-library/react'; -import { MemoryRouter, Route, Routes, useLocation, type Location } from 'react-router-dom'; -import React from 'react'; - -/** Every message that reached the (faked) chat transport. */ -const sent: string[] = []; -/** The `parentConversationId` the chat hook held when each message was sent. */ -const sentParent: Array = []; -let capturedProps: Record = {}; - -vi.mock('@object-ui/plugin-chatbot', async (importOriginal) => { - const actual = await importOriginal>(); - return { - ...actual, - useAiModels: () => ({ models: [], defaultModelId: undefined }), - useHitlInChat: () => ({ decide: vi.fn(), decisions: {} }), - useObjectChat: (opts: Record) => { - // The real hook ARMS the parent id when the prop arrives and sends it - // with the next turn, even if the prop has dropped by then (the - // URL-mirror drops it as the build conversation id lands); see - // `parentConvRef` in useObjectChat. Model that, not a read of the prop at - // send time: the first message is replayed on the task after the id - // lands (objectstack#32031). - const parentRef = React.useRef(opts.parentConversationId); - if (opts.parentConversationId) parentRef.current = opts.parentConversationId; - return { - messages: [], - isLoading: false, - error: undefined, - sendMessage: (text: string) => { - sent.push(text); - sentParent.push(parentRef.current); - parentRef.current = undefined; - }, - stop: vi.fn(), - reload: vi.fn(), - clear: vi.fn(), - setMessages: vi.fn(), - }; - }, - ChatbotEnhanced: (props: Record) => { - capturedProps = props; - return
; - }, - }; -}); -vi.mock('@object-ui/plugin-chatbot/core', async (importOriginal) => ({ - ...(await importOriginal()), - useAgents: () => ({ - agents: [{ name: 'metadata_assistant', label: 'Build', capabilities: ['build'] }], - loading: false, - error: undefined, - refetch: vi.fn(), - }), -})); - -vi.mock('@object-ui/auth', async (importOriginal) => { - const actual = await importOriginal>(); - return { ...actual, useAuth: () => ({ user: { id: 'u1' } }) }; -}); -vi.mock('../../../providers/MetadataProvider', async (importOriginal) => { - const actual = await importOriginal>(); - return { ...actual, useMetadata: () => ({ apps: [] }) }; -}); -vi.mock('../../../providers/AdapterProvider', async (importOriginal) => { - const actual = await importOriginal>(); - return { ...actual, useAdapter: () => null }; -}); -vi.mock('../ConversationsSidebar', () => ({ - ConversationsSidebar: () =>
, -})); - - -import { AiChatPage } from '../AiChatPage'; - -window.matchMedia = ((query: string) => ({ - matches: false, - media: query, - onchange: null, - addEventListener: () => {}, - removeEventListener: () => {}, - addListener: () => {}, - removeListener: () => {}, - dispatchEvent: () => false, -})) as unknown as typeof window.matchMedia; - -let minted = 0; - -function installFetch(): void { - vi.stubGlobal( - 'fetch', - vi.fn(async (input: RequestInfo | URL, init?: RequestInit) => { - const url = String(input); - const method = init?.method ?? 'GET'; - const json = (body: unknown) => - new Response(JSON.stringify(body), { - status: 200, - headers: { 'Content-Type': 'application/json' }, - }); - if (/\/conversations$/.test(url) && method === 'POST') { - minted += 1; - return json({ id: `conv-${minted}`, messages: [] }); - } - const one = /\/conversations\/([^/?]+)$/.exec(url); - if (one && method === 'GET') return json({ id: decodeURIComponent(one[1]), messages: [] }); - return json({ success: true, data: [] }); - }), - ); -} - -/** The router's live location, read from inside the tree. */ -const probe: { location?: Location } = {}; -function LocationProbe(): null { - const location = useLocation(); - React.useEffect(() => { - probe.location = location; - }, [location]); - return null; -} - -type Entry = string | { pathname: string; search?: string; state?: unknown }; - -function mount(entry: Entry) { - return render( - - - - } /> - } /> - - , - ); -} - -/** - * A build thread the user already has (cached for the product-only `build` - * scope). objectstack#32031 — a visit no longer mints a conversation, so the - * pins that need one on screen (the URL mirror, the handoff's parent thread) - * open on an existing thread instead of on a mount-time create. - */ -function seedThread(): void { - localStorage.setItem('objectstack:ai-chat-conversation-id:u1:build', 'conv-900'); -} - -/** Let the conversation resolve, the URL mirror land and any deferred replay fire. */ -async function settle(): Promise { - await waitFor(() => expect(screen.getByTestId('pane')).toBeInTheDocument()); - await waitFor(() => expect(probe.location?.pathname).toMatch(/^\/ai\/build\/conv-\d+$/)); - await act(async () => { - await new Promise((resolve) => setTimeout(resolve, 50)); - }); -} - -describe('AiChatPage — a URL parameter never sends a message (objectui#12493)', () => { - beforeEach(() => { - sent.length = 0; - sentParent.length = 0; - capturedProps = {}; - probe.location = undefined; - minted = 0; - localStorage.clear(); - installFetch(); - }); - - afterEach(() => { - cleanup(); - vi.unstubAllGlobals(); - }); - - it('a page loaded with ?handoffPrompt= sends nothing', async () => { - seedThread(); - mount('/ai/build?handoffPrompt=create%20an%20object%20named%20probe'); - await settle(); - - expect(sent).toEqual([]); - }); - - it('the in-app "Open in Builder" handoff lands its text once, by navigation state', async () => { - seedThread(); - mount('/ai/build'); - await settle(); - const askThread = probe.location?.pathname.split('/').pop(); - expect(sent).toEqual([]); - - // The real producer: the pane's handoff card calls `onOpenBuilder`. - await act(async () => { - (capturedProps.onOpenBuilder as (h: { prompt: string }) => void)({ - prompt: 'build a vendor tracker', - }); - }); - await waitFor(() => expect(sent).toEqual(['build a vendor tracker'])); - // The prompt never touched the URL. - expect(probe.location?.search ?? '').not.toContain('handoffPrompt'); - // The source thread rides the same state into the build agent's first turn. - expect(sentParent).toEqual([askThread]); - - await act(async () => { - await new Promise((resolve) => setTimeout(resolve, 50)); - }); - expect(sent).toEqual(['build a vendor tracker']); - }); - - it('a reload of the handoff history entry does not send the prompt again', async () => { - mount({ pathname: '/ai/build', state: { handoffPrompt: 'build a vendor tracker' } }); - await waitFor(() => expect(sent).toEqual(['build a vendor tracker'])); - await settle(); - expect(sent).toEqual(['build a vendor tracker']); - - // The entry's state no longer carries the prompt (it was consumed as seeded). - const entry = probe.location!; - expect((entry.state as { handoffPrompt?: string } | null)?.handoffPrompt).toBeUndefined(); - - // Reload: browser history keeps an entry's state, so remount on exactly it. - cleanup(); - sent.length = 0; - mount({ pathname: entry.pathname, search: entry.search, state: entry.state }); - await waitFor(() => expect(screen.getByTestId('pane')).toBeInTheDocument()); - await act(async () => { - await new Promise((resolve) => setTimeout(resolve, 50)); - }); - expect(sent).toEqual([]); - }); - - it('CONTROL: a user-typed first message sends', async () => { - seedThread(); - mount('/ai/build'); - await settle(); - - await act(async () => { - (capturedProps.onSendMessage as (text: string) => void)('hello builder'); - }); - await waitFor(() => expect(sent).toEqual(['hello builder'])); - }); - - // objectstack#32031 — the page-level half: a fresh visit (nothing cached, the - // state after every sign-in) creates NO conversation; the user's first send - // creates exactly one, lands in it, and the URL follows it so a reload - // resumes it. - it('CONTROL: with no thread yet, the first message creates one conversation and sends into it', async () => { - mount('/ai/build'); - await waitFor(() => expect(screen.getByTestId('pane')).toBeInTheDocument()); - await act(async () => { - await new Promise((resolve) => setTimeout(resolve, 50)); - }); - expect(minted).toBe(0); - expect(probe.location?.pathname).toBe('/ai/build'); - - await act(async () => { - (capturedProps.onSendMessage as (text: string) => void)('hello builder'); - }); - await waitFor(() => expect(sent).toEqual(['hello builder'])); - expect(minted).toBe(1); - await waitFor(() => expect(probe.location?.pathname).toBe('/ai/build/conv-1')); - expect(localStorage.getItem('objectstack:ai-chat-conversation-id:u1:build')).toBe('conv-1'); - }); -}); diff --git a/ui/packages/app-shell/src/console/ai/__tests__/AiChatPage.hydration.test.ts b/ui/packages/app-shell/src/console/ai/__tests__/AiChatPage.hydration.test.ts index 3b1de647cf4..3db432b2a67 100644 --- a/ui/packages/app-shell/src/console/ai/__tests__/AiChatPage.hydration.test.ts +++ b/ui/packages/app-shell/src/console/ai/__tests__/AiChatPage.hydration.test.ts @@ -1,5 +1,8 @@ // Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license. +// AiChatPage reads a dropped spreadsheet through `import('@object-ui/plugin-grid')`; load it +// here so collection pays that transform, not a clocked case (check-test-source-alias). +import '@object-ui/plugin-grid'; import { describe, it, expect } from 'vitest'; import { hydratedMessagesToChatMessages } from '../AiChatPage'; import { @@ -50,73 +53,16 @@ describe('AiChatPage hydration — tool invocation states', () => { ]); }); - it('lifts the pre-build proposed plan so the review card survives a reload on this surface', () => { - // propose_blueprint's `blueprint_proposed` result rides the merged tool - // output (here the persisted `{type:text,value}` envelope). Without lifting - // it on THIS converter the "Proposed plan" card only shows in the floating - // chat, never on /ai/build after a refresh. - const envelope = JSON.stringify({ - status: 'blueprint_proposed', - blueprint: { - summary: 'A reading list', - assumptions: ['One shelf for now'], - objects: [{ name: 'book', label: 'Book', fields: [{ name: 'title' }, { name: 'author' }] }], - }, - counts: { objects: 1, views: 0, dashboards: 0, seedData: 0 }, - questions: [], - }); - const [msg] = hydratedMessagesToChatMessages( - assistantWith([ - { - type: 'tool-call', - toolCallId: 't1', - toolName: 'propose_blueprint', - output: { type: 'text', value: envelope }, - }, - ]), - ); - expect(msg.toolInvocations?.[0]?.proposedPlan).toMatchObject({ - summary: 'A reading list', - objects: [{ name: 'book', label: 'Book', fieldCount: 2 }], - assumptions: ['One shelf for now'], - }); - }); - - it('lifts the ask-decline builder handoff so the "Open in Builder →" card survives a reload', () => { - // The `ask` agent's structured decline (suggest_builder → build_handoff) - // rides the merged tool output. Without lifting it on THIS converter the - // handoff card only shows in the live floating chat and is LOST when the - // conversation is reloaded or restored from the sessionStorage cache. - const envelope = JSON.stringify({ - status: 'build_handoff', - handoff: 'build', - prompt: 'Build a CRM to track leads', - packageId: 'app.crm', - }); - const [msg] = hydratedMessagesToChatMessages( - assistantWith([ - { - type: 'tool-call', - toolCallId: 't1', - toolName: 'suggest_builder', - output: { type: 'text', value: envelope }, - }, - ]), - ); - expect(msg.toolInvocations?.[0]?.builderHandoff).toEqual({ - prompt: 'Build a CRM to track leads', - packageId: 'app.crm', - }); - }); }); -describe('shared-conversation render — flat ai_messages rows → proposed-plan card', () => { +describe('shared-conversation render — flat ai_messages rows → one assistant turn', () => { // Reproduces the public `/s/:token` share bug: the endpoint returns FLAT // `ai_messages` rows, which the read-only page must put through the SAME // hydrate pipeline as the live chat. Before the fix it dumped the raw // `{"type":"tool-result",…}` envelope as text; this pins that the full - // raw-rows → ServerMessage → toUIMessages → map chain yields the card. - it('recovers the Proposed plan card from the raw shared rows', () => { + // raw-rows → ServerMessage → toUIMessages → map chain yields the tool call + // on its assistant turn. + it('recovers the tool call from the raw shared rows', () => { const envelope = JSON.stringify({ status: 'blueprint_proposed', blueprint: { @@ -154,10 +100,10 @@ describe('shared-conversation render — flat ai_messages rows → proposed-plan expect(chat.map((m) => m.role)).toEqual(['user', 'assistant']); const assistant = chat[1]; expect(assistant.content).toBe('我来帮您开发一个MES。'); - expect(assistant.toolInvocations?.[0]?.proposedPlan).toMatchObject({ - summary: 'A simple MES', - objects: [{ name: 'work_order', label: '工单', fieldCount: 2 }], - assumptions: ['Single production line'], + expect(assistant.toolInvocations?.[0]).toMatchObject({ + toolCallId: 'c1', + toolName: 'propose_blueprint', + state: 'output-available', }); }); }); diff --git a/ui/packages/app-shell/src/console/ai/__tests__/AiChatPage.iterateOrNewReload-27480.test.tsx b/ui/packages/app-shell/src/console/ai/__tests__/AiChatPage.iterateOrNewReload-27480.test.tsx deleted file mode 100644 index b4bc73b483a..00000000000 --- a/ui/packages/app-shell/src/console/ai/__tests__/AiChatPage.iterateOrNewReload-27480.test.tsx +++ /dev/null @@ -1,131 +0,0 @@ -// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. - -/** - * objectstack#27480 — the extend-or-new question an `iterate_or_new` plan asks - * survives a reload, on both reload paths this page has. Without that, a reload - * turns the question back into an ordinary plan card with a "Build it" button: - * the one-click duplicate the question exists to prevent, one refresh later. - * - * - server history: the stored tool result is merged back onto its call - * (`toUIMessages`) and re-parsed by the same detector the live chat uses; - * - cache fallback: the cache keeps a compact `output` rebuilt from the - * derived plan (`sanitizeChatMessagesForCache`), so the question's keys - * must be written back into it. - * - * Each path ends where the user does: the card rendered from the reloaded - * messages, asserted for the question and for the absence of "Build it". - */ -import '@testing-library/jest-dom/vitest'; -import { afterEach, describe, expect, it, vi } from 'vitest'; -import { cleanup, render, screen } from '@testing-library/react'; -import React from 'react'; -import { ChatbotEnhanced, uiMessageToChatMessage } from '@object-ui/plugin-chatbot'; -import { hydratedMessagesToChatMessages } from '../AiChatPage'; -import { sanitizeChatMessagesForCache, toUIMessages } from '../../../hooks/useChatConversation'; - -const ITERATE_OR_NEW = { - status: 'blueprint_proposed', - decision: 'iterate_or_new', - existingAppOverlap: { name: 'library', label: '图书馆' }, - summary: 'A reading-list app', - blueprint: { - objects: [{ name: 'book', label: 'Book', fields: [{ name: 'title' }, { name: 'author' }] }], - }, - counts: { objects: 1, views: 0, dashboards: 0, seedData: 0 }, - questions: [], -}; - -const LIVE = { - id: 'a1', - role: 'assistant' as const, - parts: [ - { - type: 'tool-propose_blueprint', - toolCallId: 'plan-1', - state: 'output-available' as const, - input: {}, - output: ITERATE_OR_NEW, - }, - ], -}; - -function renderCard(messages: React.ComponentProps['messages']) { - render(); -} - -function expectQuestionNotApproval() { - expect(screen.getByTestId('proposed-plan-iterate-or-new-question').textContent).toContain('图书馆'); - expect(screen.getByTestId('proposed-plan-extend-existing')).toBeInTheDocument(); - expect(screen.getByTestId('proposed-plan-build-new')).toBeInTheDocument(); - expect(screen.queryByTestId('proposed-plan-approve')).toBeNull(); - expect(screen.queryByTestId('proposed-plan-fallback')).toBeNull(); -} - -afterEach(cleanup); - -describe('the iterate_or_new question survives a reload (objectstack#27480)', () => { - it('server history: the stored result re-parses to the question', () => { - const ui = toUIMessages([ - { - id: 'a1', - role: 'assistant', - content: [{ type: 'tool-call', toolCallId: 'plan-1', toolName: 'propose_blueprint', input: {} }], - }, - { - role: 'tool', - content: [ - { - type: 'tool-result', - toolCallId: 'plan-1', - output: { type: 'text', value: JSON.stringify(ITERATE_OR_NEW) }, - }, - ], - }, - ]); - const messages = hydratedMessagesToChatMessages(ui); - expect(messages[0]?.toolInvocations?.[0]?.proposedPlan?.iterateOrNew).toEqual({ - app: { name: 'library', label: '图书馆' }, - }); - renderCard(messages); - expectQuestionNotApproval(); - }); - - it('cache fallback: the compact cached output keeps both keys the question is read from', () => { - const live = uiMessageToChatMessage(LIVE); - const persisted = JSON.parse(JSON.stringify(sanitizeChatMessagesForCache([live]))) as ReturnType< - typeof sanitizeChatMessagesForCache - >; - const planPart = persisted[0]?.parts.find((p) => p.type === 'tool-propose_blueprint'); - expect(planPart?.output).toMatchObject({ - status: 'blueprint_proposed', - decision: 'iterate_or_new', - existingAppOverlap: { name: 'library', label: '图书馆' }, - }); - - // Both reads a cache-fallback reload performs: this page's hydration - // mapper, and the live mapper `useObjectChat` re-runs over the same parts. - for (const messages of [hydratedMessagesToChatMessages(persisted), [uiMessageToChatMessage(persisted[0])]]) { - expect(messages[0]?.toolInvocations?.[0]?.proposedPlan?.iterateOrNew).toEqual({ - app: { name: 'library', label: '图书馆' }, - }); - cleanup(); - renderCard(messages); - expectQuestionNotApproval(); - } - }); - - it('cache fallback: a plain proposal is cached without the question keys (control)', () => { - const plain = { ...ITERATE_OR_NEW, decision: undefined, existingAppOverlap: undefined }; - const live = uiMessageToChatMessage({ ...LIVE, parts: [{ ...LIVE.parts[0], output: plain }] }); - const persisted = sanitizeChatMessagesForCache([live]); - const output = persisted[0]?.parts.find((p) => p.type === 'tool-propose_blueprint')?.output as Record< - string, - unknown - >; - expect(output.status).toBe('blueprint_proposed'); - expect('decision' in output).toBe(false); - expect('existingAppOverlap' in output).toBe(false); - renderCard(hydratedMessagesToChatMessages(persisted)); - expect(screen.getByTestId('proposed-plan-approve')).toBeInTheDocument(); - }); -}); diff --git a/ui/packages/app-shell/src/console/ai/__tests__/AiChatPage.loneAgentHeader-37146.test.tsx b/ui/packages/app-shell/src/console/ai/__tests__/AiChatPage.loneAgentHeader-37146.test.tsx index 2a6a090720c..5df1dcea589 100644 --- a/ui/packages/app-shell/src/console/ai/__tests__/AiChatPage.loneAgentHeader-37146.test.tsx +++ b/ui/packages/app-shell/src/console/ai/__tests__/AiChatPage.loneAgentHeader-37146.test.tsx @@ -6,20 +6,22 @@ * Since the in-app build entry closed, the agent catalog usually offers only * the ask agent. The header row then had nothing to switch, and drew the lone * agent's name (「提问」 / "Ask") as plain text. In the right-side drawer the - * host lifts Share and the Build Doctor into its own title bar + * host lifts Share into its own title bar * (`actionsInHost`, objectstack#35445), so that name was the row's only * content. * * - one agent: no switcher and no agent name; in the drawer (actions lifted) * no header row at all; on the full page the row stays for Share. * - two agents: the switcher renders, in the drawer and on the full page. - * - one agent on the build surface: the row stays for the package chip. * * Real subjects: `ChatPane` and the real `ChatbotEnhanced` that draws its * `headerSlot`. Stand-ins: the chat transport (idle and empty), the models * list, the metadata and adapter providers. */ +// AiChatPage reads a dropped spreadsheet through `import('@object-ui/plugin-grid')`; load it +// here so collection pays that transform, not a clocked case (check-test-source-alias). +import '@object-ui/plugin-grid'; import '@testing-library/jest-dom/vitest'; import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; import { cleanup, render, screen } from '@testing-library/react'; @@ -52,12 +54,6 @@ vi.mock('../../../providers/AdapterProvider', async (importOriginal) => ({ ...(await importOriginal>()), useAdapter: () => null, })); -// A user who may not author metadata: for a maker, a served build agent -// converges the catalog onto build alone (`makerVisibleAgents`), which would -// leave one launchable agent in the two-agent cases. -vi.mock('../../../hooks/useCanAuthorMetadata', () => ({ - useCanAuthorMetadata: () => false, -})); import { I18nProvider } from '@object-ui/i18n'; import type { AgentDescriptor } from '@object-ui/plugin-chatbot'; @@ -75,7 +71,7 @@ window.matchMedia = ((query: string) => ({ })) as unknown as typeof window.matchMedia; const ASK = { name: 'ask', label: 'Ask' } as unknown as AgentDescriptor; -const BUILD = { name: 'build', label: 'Build' } as unknown as AgentDescriptor; +const ANALYST = { name: 'analyst', label: 'Analyst' } as unknown as AgentDescriptor; function renderPane(opts: { agents: AgentDescriptor[]; activeAgent: string; actionsInHost: boolean }) { return render( @@ -129,21 +125,15 @@ describe('AI pane header with one launchable agent (objectstack#37146)', () => { }); it('drawer, two agents: the switcher renders', () => { - renderPane({ agents: [BUILD, ASK], activeAgent: 'ask', actionsInHost: true }); + renderPane({ agents: [ANALYST, ASK], activeAgent: 'ask', actionsInHost: true }); expect(headerRow()).not.toBeNull(); expect(screen.getByTestId('ai-chat-agent-picker')).toBeInTheDocument(); }); it('full page, two agents: the switcher renders beside Share', () => { - renderPane({ agents: [BUILD, ASK], activeAgent: 'ask', actionsInHost: false }); + renderPane({ agents: [ANALYST, ASK], activeAgent: 'ask', actionsInHost: false }); expect(screen.getByTestId('ai-chat-agent-picker')).toBeInTheDocument(); expect(screen.getByTestId('ai-chat-share-button')).toBeInTheDocument(); }); - it('drawer, one agent on the build surface: the row stays for the package chip', () => { - renderPane({ agents: [BUILD], activeAgent: 'build', actionsInHost: true }); - expect(screen.queryByTestId('ai-chat-agent-picker')).not.toBeInTheDocument(); - expect(headerRow()).not.toBeNull(); - expect(screen.getByTestId('ai-build-package-chip')).toBeInTheDocument(); - }); }); diff --git a/ui/packages/app-shell/src/console/ai/__tests__/AiChatPage.modelCostMultiplier-33660.test.tsx b/ui/packages/app-shell/src/console/ai/__tests__/AiChatPage.modelCostMultiplier-33660.test.tsx index ec0e26e608e..9e06a61da2d 100644 --- a/ui/packages/app-shell/src/console/ai/__tests__/AiChatPage.modelCostMultiplier-33660.test.tsx +++ b/ui/packages/app-shell/src/console/ai/__tests__/AiChatPage.modelCostMultiplier-33660.test.tsx @@ -7,11 +7,11 @@ * * ## Real subjects * - * The three hosts of the shared `ChatPane`: the full-page chat (`AiChatPage` at - * `/ai/build`), the console dock (`ChatDockConversation`) and the Studio - * copilot (`StudioCopilotConversation`), each with the REAL `ChatPane`, the - * REAL `useAiModels` and `useAiUsage` reading a `fetch` stub, and the REAL - * `ChatbotEnhanced` picker driven through its rendered `Select`. The stand-ins: + * The two hosts of the shared `ChatPane`: the full-page chat (`AiChatPage` at + * `/ai/build`) and the console dock (`ChatDockConversation`), each with the + * REAL `ChatPane`, the REAL `useAiModels` and `useAiUsage` reading a `fetch` + * stub, and the REAL `ChatbotEnhanced` picker driven through its rendered + * `Select`. The stand-ins: * the agent catalog, auth, metadata, the adapter and the side panels. * * Pins, on each host: @@ -22,6 +22,9 @@ * - the allowance note shows with usage served and is absent without it. */ +// AiChatPage reads a dropped spreadsheet through `import('@object-ui/plugin-grid')`; load it +// here so collection pays that transform, not a clocked case (check-test-source-alias). +import '@object-ui/plugin-grid'; import '@testing-library/jest-dom/vitest'; import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; import { act, cleanup, fireEvent, render, screen, waitFor, within } from '@testing-library/react'; @@ -58,12 +61,10 @@ vi.mock('../../../hooks/useCanAuthorMetadata', () => ({ useCanAuthorMetadata: () vi.mock('../../../layout/AiUsageIndicator', () => ({ AiUsageIndicator: () => null })); vi.mock('../ConversationsSidebar', () => ({ ConversationsSidebar: () => null })); -vi.mock('../PendingDraftsBar', () => ({ PendingDraftsBar: () => null })); import { I18nProvider } from '@object-ui/i18n'; import { AiChatPage } from '../AiChatPage'; import { ChatDockConversation } from '../../../layout/ChatDockConversation'; -import { StudioCopilotConversation } from '../../../views/studio-design/StudioAiCopilot'; window.matchMedia = ((query: string) => ({ matches: false, @@ -149,16 +150,6 @@ function mountDock(): void { ); } -function mountStudio(): void { - render( - - - - - , - ); -} - async function picker(): Promise { return screen.findByRole('combobox', { name: 'Model' }, { timeout: 4000 }); } @@ -174,7 +165,6 @@ const multiplierOf = (el: HTMLElement) => describe.each([ ['the full-page chat (/ai/build)', mountPage], ['the console dock', mountDock], - ['the Studio copilot', mountStudio], ])('%s — the model picker shows the cost multiplier (objectstack#33660)', (_host, mount) => { it('draws ×N per model the server gives one, and nothing for the model it gives none', async () => { mount(); diff --git a/ui/packages/app-shell/src/console/ai/__tests__/AiChatPage.modelPickSurvivesFirstSend-32994.test.tsx b/ui/packages/app-shell/src/console/ai/__tests__/AiChatPage.modelPickSurvivesFirstSend-32994.test.tsx index 3cbb95cc619..60fc42bde79 100644 --- a/ui/packages/app-shell/src/console/ai/__tests__/AiChatPage.modelPickSurvivesFirstSend-32994.test.tsx +++ b/ui/packages/app-shell/src/console/ai/__tests__/AiChatPage.modelPickSurvivesFirstSend-32994.test.tsx @@ -26,6 +26,9 @@ * - CONTROL: with no pick the default model is sent and shown, as before. */ +// AiChatPage reads a dropped spreadsheet through `import('@object-ui/plugin-grid')`; load it +// here so collection pays that transform, not a clocked case (check-test-source-alias). +import '@object-ui/plugin-grid'; import '@testing-library/jest-dom/vitest'; import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; import { act, cleanup, render, waitFor } from '@testing-library/react'; @@ -91,7 +94,6 @@ vi.mock('../../../providers/AdapterProvider', async (importOriginal) => ({ vi.mock('../../../hooks/useCanAuthorMetadata', () => ({ useCanAuthorMetadata: () => true })); vi.mock('../ConversationsSidebar', () => ({ ConversationsSidebar: () => null })); -vi.mock('../PendingDraftsBar', () => ({ PendingDraftsBar: () => null })); import { I18nProvider } from '@object-ui/i18n'; import { AiChatPage } from '../AiChatPage'; diff --git a/ui/packages/app-shell/src/console/ai/__tests__/AiChatPage.noNavigationAfterBuild-12724.test.tsx b/ui/packages/app-shell/src/console/ai/__tests__/AiChatPage.noNavigationAfterBuild-12724.test.tsx deleted file mode 100644 index 65af4069974..00000000000 --- a/ui/packages/app-shell/src/console/ai/__tests__/AiChatPage.noNavigationAfterBuild-12724.test.tsx +++ /dev/null @@ -1,344 +0,0 @@ -// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. - -/** - * objectui#12724 — a finished build STAYS on the conversation. - * - * The built-moment transition (objectui#5799) moved a conversation into the - * Studio workbench the moment a whole-app build existed, and objectui#11658 - * pointed it at the running app. The maintainer's AiBuild ruling retires both: - * the user stays on the conversation and picks a door on the result card. This - * file replaces the two that pinned the transition - * (`AiChatPage.builtTransition.test.tsx`, `AiChatPage.builtLandsRunning-11658.test.tsx`). - * - * The pins: - * 1. Neither a REOPENED built conversation (either posture) nor a LIVE build - * completion navigates: the page stays on `/ai/build/conv-1`, the only - * router call is the A1.b binding's in-place `?package=` replace on the - * same conversation, and `location.assign` is never called. - * 2. The binding still happens (the Studio dock resumes THIS thread through - * it), so pin 1 is not vacuous. - * 3. The two doors are SPA navigations the user chooses: 打开应用 to - * `/apps/APP` (the app's first navigation item), 在 Studio 中查看 to - * `/studio/PKG/data` with no landing state (the Interfaces pillar it - * opened before retired with objectstack#36502). - * - * Same faked-chat harness the retired files used: the hook instance owns the - * thread; hydration (the REAL AiChatPage path) derives the envelopes. - */ - -import '@testing-library/jest-dom/vitest'; -import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; -import { act, cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react'; -import React from 'react'; - -interface FakeMsg { - id: string; - role: string; - content: string; - toolInvocations?: unknown[]; -} - -const chat = { - isLoading: false, - append: undefined as ((m: FakeMsg) => void) | undefined, -}; - -/** Every call any `useNavigate()` result received, in order. */ -const navigateCalls: unknown[][] = []; - -vi.mock('react-router-dom', async (importOriginal) => { - const actual = await importOriginal(); - const React2 = await import('react'); - return { - ...actual, - useNavigate: () => { - const navigate = actual.useNavigate(); - return React2.useMemo( - () => - ((...args: unknown[]) => { - navigateCalls.push(args); - return (navigate as (...a: unknown[]) => unknown)(...args); - }) as typeof navigate, - [navigate], - ); - }, - }; -}); - -vi.mock('@object-ui/plugin-chatbot', async (importOriginal) => { - const actual = await importOriginal>(); - const React2 = await import('react'); - return { - ...actual, - useAiModels: () => ({ models: [], defaultModelId: undefined }), - useHitlInChat: () => ({ decide: vi.fn(), decisions: {} }), - useObjectChat: (opts: { initialMessages?: FakeMsg[] }) => { - const [messages, setMessages] = React2.useState( - () => (opts.initialMessages ?? []) as FakeMsg[], - ); - chat.append = (m: FakeMsg) => setMessages((prev) => [...prev, m]); - return { - messages, - isLoading: chat.isLoading, - error: undefined, - sendMessage: vi.fn(), - stop: vi.fn(), - reload: vi.fn(), - clear: vi.fn(), - setMessages: vi.fn(), - }; - }, - ChatbotEnhanced: (props: Record) => { - const msgs = (props.messages ?? []) as FakeMsg[]; - const open = props.onOpenBuiltApp as ((app: string, segment?: string) => void) | undefined; - const design = props.onDesignBuiltApp as ((app: string, segment?: string) => void) | undefined; - return ( -
- {msgs.map((m) => m.id).join(',')} -
- ); - }, - }; -}); -vi.mock('@object-ui/plugin-chatbot/core', async (importOriginal) => ({ - ...(await importOriginal()), - useAgents: () => ({ - agents: [{ name: 'metadata_assistant', label: 'Build', capabilities: ['build'] }], - loading: false, - error: undefined, - refetch: vi.fn(), - }), -})); - -vi.mock('@object-ui/auth', async (importOriginal) => { - const actual = await importOriginal>(); - return { ...actual, useAuth: () => ({ user: { id: 'u1' } }) }; -}); -vi.mock('../../../providers/MetadataProvider', async (importOriginal) => { - const actual = await importOriginal>(); - return { ...actual, useMetadata: () => ({ apps: [] }) }; -}); -vi.mock('../../../providers/AdapterProvider', async (importOriginal) => { - const actual = await importOriginal>(); - return { ...actual, useAdapter: () => null }; -}); -vi.mock('../ConversationsSidebar', () => ({ - ConversationsSidebar: () =>
, -})); - - -import { MemoryRouter, Route, Routes, useLocation } from 'react-router-dom'; -import { AiChatPage } from '../AiChatPage'; - -window.matchMedia = ((query: string) => ({ - matches: false, - media: query, - onchange: null, - addEventListener: () => {}, - removeEventListener: () => {}, - addListener: () => {}, - removeListener: () => {}, - dispatchEvent: () => false, -})) as unknown as typeof window.matchMedia; - -/** A persisted thread whose build ALREADY finished (whole-app draft envelope). */ -const builtTurns = (status: 'drafted' | 'published') => [ - { id: 'r1', role: 'user', content: [{ type: 'text', text: 'build me a CRM' }] }, - { - id: 'r2', - role: 'assistant', - content: [ - { type: 'text', text: 'Built it.' }, - { type: 'tool-call', toolCallId: 't1', toolName: 'apply_blueprint' }, - ], - }, - { - id: 'r3', - role: 'tool', - content: [ - { - type: 'tool-result', - toolCallId: 't1', - toolName: 'apply_blueprint', - output: { - type: 'text', - value: JSON.stringify({ - status, - packageId: 'app.k9', - drafted: [ - { type: 'app', name: 'k9_app' }, - { type: 'object', name: 'k9_task' }, - ], - }), - }, - }, - ], - }, -]; - -const UNBUILT_TURNS = [ - { id: 'r1', role: 'user', content: [{ type: 'text', text: 'hello' }] }, - { id: 'r2', role: 'assistant', content: [{ type: 'text', text: 'hi — what shall we build?' }] }, -]; - -let serverTurns: unknown[] = []; - -function installFetch(): void { - vi.stubGlobal( - 'fetch', - vi.fn(async (input: RequestInfo | URL, init?: RequestInit) => { - const url = String(input); - const method = init?.method ?? 'GET'; - if (/\/conversations\/conv-1$/.test(url) && method === 'GET') { - return new Response(JSON.stringify({ id: 'conv-1', messages: serverTurns }), { - status: 200, - headers: { 'Content-Type': 'application/json' }, - }); - } - return new Response(JSON.stringify({ success: true, data: [] }), { - status: 200, - headers: { 'Content-Type': 'application/json' }, - }); - }), - ); -} - -/** Where the router is, and with what state. */ -function Where() { - const location = useLocation(); - return ( -
- ); -} - -function renderPage() { - render( - - - } /> - } /> - } /> - } /> - - - , - ); -} - -let assignSpy: ReturnType; - -beforeEach(() => { - chat.isLoading = false; - serverTurns = []; - navigateCalls.length = 0; - window.localStorage.clear(); - window.sessionStorage.clear(); - installFetch(); - // `location.assign` is the full navigation a page reload into Studio would take. - assignSpy = vi.spyOn(window.location, 'assign').mockImplementation(() => {}); -}); - -afterEach(() => { - cleanup(); - vi.unstubAllGlobals(); - assignSpy.mockRestore(); -}); - -/** The ONLY router calls a finished build may make: the binding's in-place replace. */ -function expectOnlyTheBinding(): void { - for (const [to, opts] of navigateCalls) { - expect(to).toBe('/ai/build/conv-1?package=app.k9'); - expect(opts).toEqual({ replace: true }); - } - expect(screen.getByTestId('where')).toHaveAttribute('data-path', '/ai/build/conv-1'); - expect(screen.queryByTestId('studio-page')).not.toBeInTheDocument(); - expect(screen.queryByTestId('app-page')).not.toBeInTheDocument(); - expect(assignSpy).not.toHaveBeenCalled(); -} - -describe('AiChatPage — no automatic navigation after a build (objectui#12724)', () => { - it.each(['drafted', 'published'] as const)( - 'reopening a conversation that built an app (%s posture) stays on the conversation', - async (status) => { - serverTurns = builtTurns(status); - renderPage(); - await waitFor(() => expect(screen.getByTestId('pane')).toHaveTextContent('r'), { timeout: 4000 }); - // The binding lands (not vacuous: the build WAS seen) … - await waitFor( - () => expect(screen.getByTestId('where')).toHaveAttribute('data-search', '?package=app.k9'), - { timeout: 4000 }, - ); - await new Promise((r) => setTimeout(r, 300)); - // … and nothing else moved. - expectOnlyTheBinding(); - }, - ); - - it('a LIVE build completion stays on the conversation', async () => { - serverTurns = UNBUILT_TURNS; - chat.isLoading = true; - renderPage(); - await waitFor(() => expect(screen.getByTestId('pane')).toBeInTheDocument(), { timeout: 4000 }); - act(() => { - chat.append?.({ - id: 'live-1', - role: 'assistant', - content: 'built', - toolInvocations: [ - { - toolCallId: 't9', - toolName: 'apply_blueprint', - state: 'output-available', - draftReview: { - packageId: 'app.k9', - items: [ - { type: 'app', name: 'k9_app' }, - { type: 'object', name: 'k9_task' }, - ], - }, - }, - ], - }); - chat.isLoading = false; - }); - // one more render so the faked hook reports the settled isLoading - act(() => { - chat.append?.({ id: 'live-2', role: 'assistant', content: 'done' }); - }); - await waitFor( - () => expect(screen.getByTestId('where')).toHaveAttribute('data-search', '?package=app.k9'), - { timeout: 4000 }, - ); - await new Promise((r) => setTimeout(r, 300)); - expect(screen.getByTestId('pane')).toHaveTextContent('live-2'); - expectOnlyTheBinding(); - }); - - it('打开应用 is an SPA navigation to the built app (its first navigation item)', async () => { - serverTurns = UNBUILT_TURNS; - renderPage(); - await waitFor(() => expect(screen.getByTestId('pane')).toBeInTheDocument(), { timeout: 4000 }); - fireEvent.click(screen.getByTestId('open-door')); - expect(await screen.findByTestId('app-page', {}, { timeout: 4000 })).toBeInTheDocument(); - expect(screen.getByTestId('where')).toHaveAttribute('data-path', '/apps/k9_app'); - expect(assignSpy).not.toHaveBeenCalled(); - }); - - it('在 Studio 中查看 is an SPA navigation to the Studio home (the Data pillar) with no landing state', async () => { - serverTurns = UNBUILT_TURNS; - renderPage(); - await waitFor(() => expect(screen.getByTestId('pane')).toBeInTheDocument(), { timeout: 4000 }); - fireEvent.click(screen.getByTestId('studio-door')); - expect(await screen.findByTestId('studio-page', {}, { timeout: 4000 })).toBeInTheDocument(); - expect(screen.getByTestId('where')).toHaveAttribute('data-path', '/studio/app.k9/data'); - expect(screen.getByTestId('where')).toHaveAttribute('data-state', 'null'); - expect(assignSpy).not.toHaveBeenCalled(); - }); -}); diff --git a/ui/packages/app-shell/src/console/ai/__tests__/AiChatPage.onePlanPerTurnReload.test.tsx b/ui/packages/app-shell/src/console/ai/__tests__/AiChatPage.onePlanPerTurnReload.test.tsx deleted file mode 100644 index 2113e7748e6..00000000000 --- a/ui/packages/app-shell/src/console/ai/__tests__/AiChatPage.onePlanPerTurnReload.test.tsx +++ /dev/null @@ -1,151 +0,0 @@ -// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. - -/** - * One build turn renders ONE plan card after a reload too: the newest - * `propose_blueprint` result, the plan the runtime builds. - * - * The server stores a multi-step turn as one assistant row per step, so a - * reloaded turn is SEVERAL assistant messages; the live stream gives it as one. - * Both reload paths this page has are driven to the rendered card: - * - * - server history: `toUIMessages` → `hydratedMessagesToChatMessages`, drawn - * directly and through API mode's store (`useObjectChat` seeds the AI SDK - * store from these messages and maps it back on every render); - * - cache fallback: `sanitizeChatMessagesForCache` → the same hydration. - */ -import '@testing-library/jest-dom/vitest'; -import { afterEach, describe, expect, it, vi } from 'vitest'; -import { cleanup, render, renderHook, screen, within } from '@testing-library/react'; -import React from 'react'; -import { - ChatbotEnhanced, - toRuntimeMessages, - uiMessagesToChatMessages, - useObjectChat, -} from '@object-ui/plugin-chatbot'; -import { hydratedMessagesToChatMessages } from '../AiChatPage'; -import { sanitizeChatMessagesForCache, toUIMessages } from '../../../hooks/useChatConversation'; - -// Stands in for the AI SDK store, as in plugin-chatbot's -// `useObjectChat.persistedChart-25908.test.tsx`: it holds what it was seeded with. -vi.mock('@ai-sdk/react', () => ({ - useChat: (opts: { messages?: unknown[] }) => ({ - messages: opts.messages ?? [], - status: 'ready', - error: undefined, - sendMessage: vi.fn(), - regenerate: vi.fn(), - stop: vi.fn(), - setMessages: vi.fn(), - }), -})); - -const API = 'https://example.test/api/v1/ai/agents/build/chat'; - -const plan = (n: number) => ({ - status: 'blueprint_proposed', - summary: `Plan ${n}`, - blueprint: { - app: { label: `App ${n}` }, - objects: [{ name: 'book', label: 'Book', fields: [{ name: 'title' }] }], - }, - counts: { objects: 1, views: 0, dashboards: 0, seedData: 0 }, - questions: [], -}); - -/** One stored step: the assistant's tool call, then the `tool` row with its result. */ -const storedStep = (n: number) => [ - { - id: `a-${n}`, - role: 'assistant', - content: [{ type: 'tool-call', toolCallId: `plan-${n}`, toolName: 'propose_blueprint', input: {} }], - }, - { - role: 'tool', - content: [ - { - type: 'tool-result', - toolCallId: `plan-${n}`, - output: { type: 'text', value: JSON.stringify(plan(n)) }, - }, - ], - }, -]; -const storedUser = (id: string) => ({ id, role: 'user', content: 'build me a library app' }); - -function drawn(messages: React.ComponentProps['messages']) { - cleanup(); - render(); - return screen.queryAllByTestId('proposed-plan-title').map((el) => el.textContent); -} - -/** The replaced plans draw as completed steps: no fallback confirm card, nothing awaiting. */ -function expectReplacedPlansCompleted() { - expect(screen.queryByTestId('proposed-plan-fallback')).toBeNull(); - const steps = screen.getAllByTestId('tool-phase-line'); - expect(steps.length).toBeGreaterThan(0); - for (const step of steps) expect(step).toHaveTextContent(/^Completed/); -} - -/** API mode: the hydrated thread through the store and back, as `ChatPane` renders it. */ -function throughStore(hydrated: ReturnType) { - const { result } = renderHook(() => useObjectChat({ api: API, conversationId: 'c1', initialMessages: hydrated })); - return toRuntimeMessages(result.current.messages); -} - -afterEach(cleanup); - -describe('one plan card per build turn survives a reload', () => { - it('server history: a turn stored as four steps draws one card, the newest, on both renders', () => { - const hydrated = hydratedMessagesToChatMessages( - toUIMessages([storedUser('u1'), ...[1, 2, 3, 4].flatMap(storedStep)]), - ); - // The stored turn really is four assistant messages, one plan each. - expect(hydrated.filter((m) => m.role === 'assistant')).toHaveLength(4); - expect(drawn(hydrated)).toEqual(['Proposed plan · App 4']); - expectReplacedPlansCompleted(); - expect(drawn(throughStore(hydrated))).toEqual(['Proposed plan · App 4']); - expectReplacedPlansCompleted(); - }); - - it('PRESERVATION — server history: a plan from a previous turn keeps its card', () => { - const hydrated = hydratedMessagesToChatMessages( - toUIMessages([ - storedUser('u1'), - ...storedStep(0), - storedUser('u2'), - ...[1, 2, 3, 4].flatMap(storedStep), - ]), - ); - expect(drawn(hydrated)).toEqual(['Proposed plan · App 0', 'Proposed plan · App 4']); - expect(drawn(throughStore(hydrated))).toEqual(['Proposed plan · App 0', 'Proposed plan · App 4']); - }); - - it('cache fallback: the cached turn draws one card, the newest', () => { - const live = uiMessagesToChatMessages([ - { id: 'u1', role: 'user', parts: [{ type: 'text', text: 'build me a library app' }] }, - { - id: 'a1', - role: 'assistant', - parts: [1, 2, 3, 4].map((n) => ({ - type: 'tool-propose_blueprint', - toolCallId: `plan-${n}`, - state: 'output-available', - input: {}, - output: plan(n), - })), - }, - ]); - const persisted = JSON.parse(JSON.stringify(sanitizeChatMessagesForCache(live))) as ReturnType< - typeof sanitizeChatMessagesForCache - >; - const hydrated = hydratedMessagesToChatMessages(persisted); - // The compact cache copy keeps the plan's summary, not its app label, so - // the card is told apart by the summary it draws. - for (const messages of [hydrated, throughStore(hydrated)]) { - expect(drawn(messages)).toHaveLength(1); - expect(within(screen.getByTestId('proposed-plan')).getByText('Plan 4')).toBeInTheDocument(); - expectReplacedPlansCompleted(); - } - }); -}); diff --git a/ui/packages/app-shell/src/console/ai/__tests__/AiChatPage.planApprovalReachesLaunchers-11666.test.tsx b/ui/packages/app-shell/src/console/ai/__tests__/AiChatPage.planApprovalReachesLaunchers-11666.test.tsx deleted file mode 100644 index d6f74bc5a3f..00000000000 --- a/ui/packages/app-shell/src/console/ai/__tests__/AiChatPage.planApprovalReachesLaunchers-11666.test.tsx +++ /dev/null @@ -1,203 +0,0 @@ -// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. - -/** - * objectui#11666 — a proposed plan awaiting approval reaches the launcher the - * user returns to, and survives the chat closing. - * - * The launchers are on screen only while the chat is closed, so the reading - * must leave the chat: `ChatbotEnhanced` reports it (pinned in plugin-chatbot's - * `ChatbotEnhanced.planApprovalPending-11666.test.tsx`), `ChatPane` publishes it - * on the assistant bus, and the console launcher reads the bus. This file pins the middle - * hop end to end — the REAL `ChatPane` and the REAL top-bar robot (the FAB until objectstack#34608), with `ChatbotEnhanced` - * replaced by a prop recorder so the case can play the chat's reading. - */ - -import '@testing-library/jest-dom/vitest'; -import { afterEach, describe, expect, it, vi } from 'vitest'; -import { act, cleanup, render, renderHook, screen } from '@testing-library/react'; -import { MemoryRouter } from 'react-router-dom'; -import React from 'react'; - -/** Props of the last `ChatbotEnhanced` render. */ -let captured: Record = {}; - -vi.mock('@object-ui/plugin-chatbot', async (importOriginal) => { - const actual = await importOriginal>(); - return { - ...actual, - ChatbotEnhanced: (props: Record) => { - captured = props; - return null; - }, - useObjectChat: () => ({ - messages: [], - isLoading: false, - error: undefined, - sendMessage: vi.fn(), - stop: vi.fn(), - reload: vi.fn(), - clear: vi.fn(), - setMessages: vi.fn(), - }), - useAiModels: () => ({ models: [], defaultModelId: undefined }), - }; -}); - -vi.mock('../../../providers/MetadataProvider', async (importOriginal) => { - const actual = await importOriginal>(); - return { ...actual, useMetadata: () => ({ apps: [] }) }; -}); -vi.mock('../../../providers/AdapterProvider', async (importOriginal) => { - const actual = await importOriginal>(); - return { ...actual, useAdapter: () => null }; -}); - -import { I18nProvider } from '@object-ui/i18n'; -import type { AgentDescriptor } from '@object-ui/plugin-chatbot'; -import { ChatPane } from '../AiChatPage'; -import { AssistantTopBarButton } from '../../../layout/AssistantTopBarButton'; -import { useConversationList } from '../../../hooks/useConversationList'; -import { publishPlanApprovalPending, usePlanApprovalPendingCount } from '../../../assistant/assistantBus'; - -window.matchMedia = ((query: string) => ({ - matches: false, - media: query, - onchange: null, - addEventListener: () => {}, - removeEventListener: () => {}, - addListener: () => {}, - removeListener: () => {}, - dispatchEvent: () => false, -})) as unknown as typeof window.matchMedia; - -// objectstack#34608 — the top-bar robot replaced the floating button as the -// console's launcher and carries its marker. -const MARKER = 'topbar-ai-assistant-plan-pending'; - -function renderPane(conversationId: string) { - captured = {}; - return render( - - - - - , - ); -} - -function renderLauncher() { - return render( - - - - - , - ); -} - -/** Play the chat's own reading, as `ChatbotEnhanced` reports it. */ -function chatReports(pending: boolean, count = pending ? 1 : 0) { - const report = captured.onPlanApprovalPendingChange as (p: boolean, c: number) => void; - expect(typeof report).toBe('function'); - act(() => report(pending, count)); -} - -/** objectstack#25943 — what Studio's right slot reads off the bus. */ -function CountProbe() { - return {usePlanApprovalPendingCount()}; -} - -afterEach(() => { - for (const id of ['conv-1', 'conv-2']) { - act(() => publishPlanApprovalPending({ userId: undefined, conversationId: id, pending: false })); - } - cleanup(); - window.localStorage.clear(); - vi.unstubAllGlobals(); -}); - -describe('ChatPane → assistant bus → top-bar robot (objectui#11666)', () => { - it('the chat reading a waiting plan lights the robot, and the marker outlives the chat closing', () => { - renderLauncher(); - const pane = renderPane('conv-1'); - expect(screen.queryByTestId(MARKER)).not.toBeInTheDocument(); - - chatReports(true); - expect(screen.getByTestId(MARKER)).toBeInTheDocument(); - - // The chat closes (the dock collapses, the pane unmounts): nothing clears. - pane.unmount(); - expect(screen.getByTestId(MARKER)).toBeInTheDocument(); - }); - - it('reopening the chat clears nothing by itself; the plan leaving "awaiting" does', () => { - renderLauncher(); - const first = renderPane('conv-1'); - chatReports(true); - first.unmount(); - - // Reopen on the same thread: mounting announces nothing until the chat reads. - renderPane('conv-1'); - expect(screen.getByTestId(MARKER)).toBeInTheDocument(); - chatReports(true); - expect(screen.getByTestId(MARKER)).toBeInTheDocument(); - - // The user approves (or the build runs): the chat reads false. - chatReports(false); - expect(screen.queryByTestId(MARKER)).not.toBeInTheDocument(); - }); - - it('a chat on another thread reporting no plan does not clear the waiting one', () => { - renderLauncher(); - const first = renderPane('conv-1'); - chatReports(true); - first.unmount(); - - renderPane('conv-2'); - chatReports(false); - expect(screen.getByTestId(MARKER)).toBeInTheDocument(); - }); - - it('deleting the thread drops its reading (the /ai sidebar delete)', async () => { - vi.stubGlobal('fetch', vi.fn(async () => new Response(null, { status: 204 }))); - renderLauncher(); - const pane = renderPane('conv-1'); - chatReports(true); - pane.unmount(); - expect(screen.getByTestId(MARKER)).toBeInTheDocument(); - - const { result } = renderHook(() => useConversationList({ userId: undefined, apiBase: '/api/v1/ai' })); - await act(async () => { - await result.current.remove('conv-1'); - }); - expect(screen.queryByTestId(MARKER)).not.toBeInTheDocument(); - }); - - // objectstack#25943 — the chat's count reaches the bus with its reading. - it("the chat's count of items awaiting confirmation reaches the bus, and its end clears it", () => { - render(); - renderPane('conv-1'); - expect(screen.getByTestId('pending-count')).toHaveTextContent('0'); - - chatReports(true, 2); - expect(screen.getByTestId('pending-count')).toHaveTextContent('2'); - - chatReports(true, 3); - expect(screen.getByTestId('pending-count')).toHaveTextContent('3'); - - chatReports(false); - expect(screen.getByTestId('pending-count')).toHaveTextContent('0'); - }); -}); diff --git a/ui/packages/app-shell/src/console/ai/__tests__/AiChatPage.planCardLocale.test.tsx b/ui/packages/app-shell/src/console/ai/__tests__/AiChatPage.planCardLocale.test.tsx deleted file mode 100644 index 43deb73a967..00000000000 --- a/ui/packages/app-shell/src/console/ai/__tests__/AiChatPage.planCardLocale.test.tsx +++ /dev/null @@ -1,310 +0,0 @@ -// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. - -/** - * Which locale each string on the plan / confirm cards follows (objectui#3837). - * - * One gate, two rules (#772/#2884, stated in `AiChatPage`'s own comment above - * `convZh`): what a card SENDS to the agent follows the CONVERSATION's language - * — the cloud confirm gate's approval pattern only recognises Chinese and - * English — and what a card DISPLAYS follows the console UI locale, like every - * other label in the console. - * - * `planBuildingLabel` (#2632) was on the wrong side of that line: gated on - * `convZh`, it rendered a hard-coded `正在搭建…` for any Chinese thread, so an - * English console showed one Chinese badge among English labels, and the ten - * packs' `console.ai.planBuilding` was unreachable for the very readers it was - * translated for (#3546 slice four measured it; PR #3839 backfilled the key). - * - * The pane is rendered for real — real `I18nProvider`, real locale packs, real - * `isConversationZh` probe — with `ChatbotEnhanced` replaced by a prop recorder, - * because the props ChatPane hands down ARE where the two rules live. - * - * Note which cases can discriminate: only a UI locale that DIFFERS from the - * conversation's language can. `zh` UI + `zh` conversation reads the same string - * either way (the pack value is byte-identical to the deleted literal, and the - * containment pin in `packages/i18n/.../console-namespace-3546.test.tsx` is why), - * so it is kept as the invariance half, not as evidence of the fix. - */ - -import '@testing-library/jest-dom/vitest'; -import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; -import { cleanup, render } from '@testing-library/react'; -import { MemoryRouter } from 'react-router-dom'; -import React from 'react'; - -/** Props of the last `ChatbotEnhanced` render — the surface under assertion. */ -let captured: Record = {}; - -vi.mock('@object-ui/plugin-chatbot', async (importOriginal) => { - const actual = await importOriginal>(); - return { - ...actual, - ChatbotEnhanced: (props: Record) => { - captured = props; - return null; - }, - // No transport in a unit test: the conversation this pane reasons about - // arrives through `initialMessages` (the hydrated history), which is the - // half of `convZh` a fresh page load actually reads. - useObjectChat: () => ({ - messages: [], - isLoading: false, - error: undefined, - sendMessage: vi.fn(), - stop: vi.fn(), - reload: vi.fn(), - clear: vi.fn(), - setMessages: vi.fn(), - }), - useAiModels: () => ({ models: [], defaultModelId: undefined }), - }; -}); - -// The pane reads `apps` for the bound-package chip and the adapter for the -// Excel→App bar; neither is part of this invariant, and both otherwise want a -// live backend. -vi.mock('../../../providers/MetadataProvider', async (importOriginal) => { - const actual = await importOriginal>(); - return { ...actual, useMetadata: () => ({ apps: [] }) }; -}); -vi.mock('../../../providers/AdapterProvider', async (importOriginal) => { - const actual = await importOriginal>(); - return { ...actual, useAdapter: () => null }; -}); - -import { I18nProvider } from '@object-ui/i18n'; -import type { AgentDescriptor } from '@object-ui/plugin-chatbot'; -import { ChatPane } from '../AiChatPage'; -import type { HydratedUIMessage } from '../../../hooks/useChatConversation'; - -// jsdom has no matchMedia — `useIsMobile` (mobile canvas overlay) needs a stub. -window.matchMedia = ((query: string) => ({ - matches: false, - media: query, - onchange: null, - addEventListener: () => {}, - removeEventListener: () => {}, - addListener: () => {}, - removeListener: () => {}, - dispatchEvent: () => false, -})) as unknown as typeof window.matchMedia; - -const CJK = /[一-鿿]/; - -function userTurn(text: string): HydratedUIMessage[] { - return [{ id: 'm1', role: 'user', parts: [{ type: 'text', text }] }] as HydratedUIMessage[]; -} - -/** A Chinese thread and an English one — the two conversation languages the gate knows. */ -const ZH_THREAD = userTurn('帮我做一个客户管理应用'); -const EN_THREAD = userTurn('Build me a CRM app'); - -function renderPane(uiLocale: string, initialMessages: HydratedUIMessage[]) { - // Unmount any previous tree first: a still-mounted pane re-renders on its own - // effects and would overwrite `captured` with ITS props after this render. - cleanup(); - captured = {}; - render( - - - - - , - ); - return captured; -} - -beforeEach(() => { - // The provider persists the last language (objectstack#5406); without this a - // stale locale leaks into the next case. - window.localStorage.clear(); -}); -afterEach(() => cleanup()); - -describe('#3837 — plan-card labels follow the UI locale, sent messages follow the conversation', () => { - it('en UI + Chinese thread: the Building badge is English, like every other label on the card', () => { - const props = renderPane('en', ZH_THREAD); - // The discriminating assertion: before the fix this was '正在搭建…'. - expect(props.planBuildingLabel).toBe('Building…'); - // …and the card it sits on has no other Chinese in it, which is the actual - // user-visible complaint (#2458 item 4 is this in the other direction). - const chineseLabels = Object.entries(props) - .filter(([k, v]) => k.endsWith('Label') && typeof v === 'string' && CJK.test(v)) - .map(([k]) => k); - expect(chineseLabels).toEqual([]); - }); - - it('de UI + Chinese thread: the badge comes from the German pack, not from a two-way ternary', () => { - // The removed gate could only ever choose between Chinese and the UI locale, - // so a third locale is the cleanest proof that the PACK now answers. - expect(renderPane('de', ZH_THREAD).planBuildingLabel).toBe('Wird erstellt…'); - }); - - it('zh UI: the badge is the zh pack value — now the only source of that string', () => { - // Cannot discriminate before/after (the deleted literal was byte-identical - // by design) — it pins that the fix did not change what a zh reader sees. - expect(renderPane('zh', ZH_THREAD).planBuildingLabel).toBe('正在搭建…'); - expect(renderPane('zh', EN_THREAD).planBuildingLabel).toBe('正在搭建…'); - }); - - it('the three OUTBOUND messages still follow the conversation, not the UI (#772/#2884 intact)', () => { - // The other half of the gate must be untouched: these are sent INTO the - // thread and the cloud confirm gate matches them by language. - const zhUnderEn = renderPane('en', ZH_THREAD); - expect(zhUnderEn.planApproveMessage).toBe('确认,开始搭建。'); - expect(zhUnderEn.planApproveDefaultsMessage).toBe('确认搭建,未决问题按你的合理假设和默认处理。'); - expect(zhUnderEn.changesConfirmMessage).toBe('确认修改,应用你刚才提议的改动。'); - - // An English thread is read under a NON-Chinese, non-English console on - // purpose: `outbound-agent-messages.test.ts` guarantees no pack but `en` and - // `zh` defines these keys, so `de` proves the English wording the cloud gate - // matches is what a non-Chinese thread sends. (When this was written a `zh` - // console was the one combination that did NOT hold — the non-Chinese branch - // read the UI pack. That was filed as #3896 and fixed there; the full - // matrix, including that combination, is the describe block below.) - const enUnderDe = renderPane('de', EN_THREAD); - expect(enUnderDe.planApproveMessage).toBe('Looks good — build it as proposed.'); - expect(enUnderDe.planApproveDefaultsMessage).toBe( - 'Build it with your best assumptions; use sensible defaults for the open questions.', - ); - expect(enUnderDe.changesConfirmMessage).toBe('Confirm — apply the change you just proposed.'); - }); -}); - -/** - * The send half, all four sites, both directions (objectui#3896). - * - * Before this: the three gated messages fell back to `t()` — the UI PACK — for a - * non-Chinese conversation, and `planAnswerMessage` had no gate at all. So the - * two rows that discriminate are the two the UI locale and the conversation - * disagree on: - * - * - `zh` UI + English thread — sent `确认,开始搭建。` into an English thread - * (the zh pack defines all four keys, so `t()` HIT instead of falling - * through). The cloud gate matched it, the build ran, and the agent flipped - * the thread to Chinese: #2884's symptom, trigger reversed. - * - non-`zh` UI + Chinese thread — `planAnswerMessage` sent `For "…", go - * with: …` into a Chinese thread, which is #772's opening complaint verbatim. - * - * The matching-language rows are the invariance half: they read the same either - * way and are here so a future "simplification" that re-reads the UI pack cannot - * pass by getting the agreeing cases right. - */ -describe('#3896 — outbound text follows the CONVERSATION, in both directions', () => { - const ZH_OUTBOUND = { - planApproveMessage: '确认,开始搭建。', - planApproveDefaultsMessage: '确认搭建,未决问题按你的合理假设和默认处理。', - changesConfirmMessage: '确认修改,应用你刚才提议的改动。', - }; - const EN_OUTBOUND = { - planApproveMessage: 'Looks good — build it as proposed.', - planApproveDefaultsMessage: - 'Build it with your best assumptions; use sensible defaults for the open questions.', - changesConfirmMessage: 'Confirm — apply the change you just proposed.', - }; - - /** The three string-valued outbound props, as one comparable object. */ - function sent(props: Record) { - return { - planApproveMessage: props.planApproveMessage, - planApproveDefaultsMessage: props.planApproveDefaultsMessage, - changesConfirmMessage: props.changesConfirmMessage, - }; - } - - /** The fourth site is a function — the answer chip builds its text per option. */ - function answerChip(props: Record, question: string, option: string): string { - return (props.planAnswerMessage as (q: string, o: string) => string)(question, option); - } - - // `de` rides along as the third locale: it defines none of the four keys, so it - // proves the resolver is not quietly leaning on a UI-pack lookup that happens - // to agree. - it.each(['zh', 'en', 'de'])( - '%s UI + English thread: all four are English, so the gate reads English', - (uiLocale) => { - const props = renderPane(uiLocale, EN_THREAD); - expect(sent(props)).toEqual(EN_OUTBOUND); - expect(answerChip(props, 'One shelf or many?', 'many')).toBe( - 'For "One shelf or many?", go with: many.', - ); - // Nothing Chinese leaves the console for an English thread — the class of - // defect, not just the four strings. - for (const value of Object.values(sent(props))) { - expect(CJK.test(String(value)), `outbound Chinese under ${uiLocale} UI`).toBe(false); - } - }, - ); - - it.each(['en', 'zh', 'de'])( - '%s UI + Chinese thread: all four are Chinese, planAnswerMessage included', - (uiLocale) => { - const props = renderPane(uiLocale, ZH_THREAD); - expect(sent(props)).toEqual(ZH_OUTBOUND); - // This assertion is the whole of consequence B: the chip was ungated, so - // under an `en`/`de` console it sent English into a Chinese thread. - expect(answerChip(props, '一个货架还是多个?', '多个')).toBe( - '关于「一个货架还是多个?」,我选择「多个」。', - ); - }, - ); - - it('the answer chip does not read as blanket approval in either language', () => { - // `planAnswerMessage` answers a structure question; the cloud gate must NOT - // treat it as approval (the `APPROVAL_RE` mirror in - // `packages/i18n/src/__tests__/i18n.test.ts` owns that check on the pack - // values). Here: it stays distinct from the approval text it sits next to. - const zhProps = renderPane('en', ZH_THREAD); - expect(answerChip(zhProps, '一个货架还是多个?', '多个')).not.toBe( - ZH_OUTBOUND.planApproveMessage, - ); - const enProps = renderPane('zh', EN_THREAD); - expect(answerChip(enProps, 'One shelf or many?', 'many')).not.toBe( - EN_OUTBOUND.planApproveMessage, - ); - }); -}); - -/** - * objectstack#27480 — the extend-or-new question an `iterate_or_new` plan asks - * SENDS one of two answers, so they sit on the send side of the same line: the - * conversation's language picks them, never the console's. The rows that can - * discriminate are the ones where the two disagree. - */ -describe('objectstack#27480 — the extend-or-new answers follow the CONVERSATION', () => { - function answers(props: Record) { - return { - extend: (props.planExtendExistingMessage as (app: string) => string)('图书馆'), - buildNew: props.planBuildNewAppMessage, - }; - } - - it.each(['en', 'zh', 'de'])('%s UI + Chinese thread: both answers are Chinese', (uiLocale) => { - expect(answers(renderPane(uiLocale, ZH_THREAD))).toEqual({ - extend: '在「图书馆」上继续完善,不另建应用。', - buildNew: '另建一个独立应用。', - }); - }); - - it.each(['zh', 'en', 'de'])('%s UI + English thread: both answers are English', (uiLocale) => { - const props = renderPane(uiLocale, EN_THREAD); - expect(answers(props)).toEqual({ - extend: 'Keep improving "图书馆" instead of building a new app.', - buildNew: 'Build a separate, new app.', - }); - // Nothing Chinese leaves the console for an English thread but the app's own name. - expect(CJK.test(String(props.planBuildNewAppMessage)), `outbound Chinese under ${uiLocale} UI`).toBe(false); - }); -}); diff --git a/ui/packages/app-shell/src/console/ai/__tests__/AiChatPage.publishAdvisoryReachesAuthor.test.tsx b/ui/packages/app-shell/src/console/ai/__tests__/AiChatPage.publishAdvisoryReachesAuthor.test.tsx deleted file mode 100644 index 9f002765b31..00000000000 --- a/ui/packages/app-shell/src/console/ai/__tests__/AiChatPage.publishAdvisoryReachesAuthor.test.tsx +++ /dev/null @@ -1,283 +0,0 @@ -/** - * ObjectUI - * Copyright (c) 2024-present ObjectStack Inc. - * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. - */ - -/** - * objectui#10039 — a per-draft advisory the SERVER sent must reach the author - * on THIS surface, the chat transcript's draft-card Publish. - * - * ## What this asserts, and what would be worthless - * - * The defect is that the findings VANISH. So this fires the handler the chat - * cards fire (`onPublishDrafts`), answers it with the batch body the - * framework's runtime authoring gate actually sends (advisories riding each - * `published[]` element, objectstack#9343), and asserts the finding's own - * prose arrives at the console's advisory sink. - * - * ## Real vs stubbed - * - * Real: `ChatPane`'s publish handler, `useMetadataClient` — ⛔ deliberately NOT - * mocked (see `../../views/metadata-admin/useMetadataClient.advisorySink.test.tsx` - * for why mocking it is how this class of hole stays invisible) — the client, - * its `published[]` walk, `readSaveAdvisories`, `emitSaveAdvisories`, and the - * REAL `publishHealthFromResponse` the handler hands back to the chat card. - * - * Stubbed: `sonner` (the terminal sink, a module binding), `globalThis.fetch` - * (the server), and the chat tree itself — `ChatbotEnhanced` is the CONSUMER - * of the handler under test, not the handler, so it is reduced to the button - * that fires it. - */ - -import '@testing-library/jest-dom/vitest'; -import React from 'react'; -import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; -import { cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react'; -import { MemoryRouter, Route, Routes } from 'react-router-dom'; - -const PACKAGE_ID = 'app.k9qk'; - -vi.mock('sonner', () => ({ - toast: { - warning: vi.fn(), - error: vi.fn(), - success: vi.fn(), - info: vi.fn(), - message: vi.fn(), - dismiss: vi.fn(), - }, - Toaster: () => null, -})); - -/** What the chat card's Publish handed back — captured so the ADR-0038 L3 - * health hand-off is observed along with the advisory. */ -let publishResult: unknown; - -vi.mock('@object-ui/plugin-chatbot', async (importOriginal) => { - const actual = await importOriginal>(); - return { - ...actual, - useAiModels: () => ({ models: [], defaultModelId: undefined }), - useHitlInChat: () => ({ decide: vi.fn(), decisions: {} }), - useObjectChat: () => ({ - messages: [], - isLoading: false, - error: undefined, - sendMessage: vi.fn(), - stop: vi.fn(), - reload: vi.fn(), - clear: vi.fn(), - setMessages: vi.fn(), - }), - ChatbotEnhanced: (props: Record) => { - const onPublishDrafts = props.onPublishDrafts as - | ((packageId: string) => Promise) - | undefined; - return ( - - ); - }, - }; -}); -vi.mock('@object-ui/plugin-chatbot/core', async (importOriginal) => ({ - ...(await importOriginal()), - useAgents: () => ({ - agents: [{ name: 'metadata_assistant', label: 'Build', capabilities: ['build'] }], - loading: false, - error: undefined, - refetch: vi.fn(), - }), -})); - -vi.mock('@object-ui/auth', async (importOriginal) => { - const actual = await importOriginal>(); - return { ...actual, useAuth: () => ({ user: { id: 'u1' } }) }; -}); -vi.mock('../../../providers/MetadataProvider', async (importOriginal) => { - const actual = await importOriginal>(); - return { ...actual, useMetadata: () => ({ apps: [] }) }; -}); -vi.mock('../../../providers/AdapterProvider', async (importOriginal) => { - const actual = await importOriginal>(); - return { ...actual, useAdapter: () => null }; -}); -vi.mock('../ConversationsSidebar', () => ({ - ConversationsSidebar: () =>
, -})); - - -import { toast } from 'sonner'; -import { AiChatPage } from '../AiChatPage'; - -window.matchMedia = ((query: string) => ({ - matches: false, - media: query, - onchange: null, - addEventListener: () => {}, - removeEventListener: () => {}, - addListener: () => {}, - removeListener: () => {}, - dispatchEvent: () => false, -})) as unknown as typeof window.matchMedia; - -/** - * One finding in the gate's D3 shape. All six keys are required — - * `readSaveAdvisories` drops a half-shaped finding, so a fixture missing one - * would make this file pass (or fail) for the wrong reason. - */ -const PURGE_ADVISORY = { - severity: 'warning' as const, - rule: 'flow/delete-without-filter', - where: 'flow "nightly_purge" · node "purge old rows"', - path: 'flows[0].nodes[2].config.filters', - message: 'this delete_record node sets multi: true with no filter, so it deletes every row', - hint: 'add a filter, or set multi: false to delete a single record', -}; - -/** The batch body in the envelope `PublishPackageDraftsResponseSchema` declares. */ -const ADVISED_BATCH = { - success: true, - data: { - outcome: 'published', - publishedCount: 1, - failedCount: 0, - published: [{ type: 'flow', name: 'nightly_purge', advisories: [PURGE_ADVISORY] }], - failed: [], - }, -}; - -/** The same publish, clean: the server omits `advisories` entirely. */ -const CLEAN_BATCH = { - success: true, - data: { - outcome: 'published', - publishedCount: 1, - failedCount: 0, - published: [{ type: 'flow', name: 'nightly_purge' }], - failed: [], - }, -}; - -let batchBody: unknown = ADVISED_BATCH; -let publishPosts = 0; - -function json(body: unknown) { - return new Response(JSON.stringify(body), { - status: 200, - headers: { 'content-type': 'application/json' }, - }); -} - -beforeEach(() => { - vi.clearAllMocks(); - batchBody = ADVISED_BATCH; - publishPosts = 0; - publishResult = undefined; - window.localStorage.clear(); - window.sessionStorage.clear(); - vi.stubGlobal( - 'fetch', - vi.fn(async (input: unknown) => { - const url = String(input); - if (url.includes('/publish-drafts')) { - publishPosts += 1; - return json(batchBody); - } - return json({ success: true, data: [] }); - }) as unknown as typeof fetch, - ); -}); - -afterEach(() => { - cleanup(); - vi.unstubAllGlobals(); -}); - -/** Render the build surface and fire a draft card's Publish. */ -async function publishFromAChatCard(): Promise { - render( - - - } /> - - , - ); - fireEvent.click(await screen.findByTestId('card-publish')); - await waitFor(() => expect(publishPosts).toBe(1)); -} - -describe('AiChatPage — the server’s advisory reaches the author (objectui#10039)', () => { - it('renders the finding the batch publish answered with', async () => { - await publishFromAChatCard(); - - await waitFor(() => expect(toast.warning).toHaveBeenCalled()); - const [title, options] = vi.mocked(toast.warning).mock.calls[0] as [ - string, - { description?: string } | undefined, - ]; - expect(title).toMatch(/^Published\b/); - expect(options?.description).toContain(PURGE_ADVISORY.message); - expect(options?.description).toContain(PURGE_ADVISORY.rule); - expect(options?.description).toContain(PURGE_ADVISORY.hint); - }); - - it('CONTROL: a clean publish says nothing, and the card still gets its verdict', async () => { - batchBody = CLEAN_BATCH; - await publishFromAChatCard(); - - expect(publishPosts).toBe(1); - // The handler's own contract with the chat card is unchanged — this is - // what makes the silence above a reading about the advisory list rather - // than about a handler that stopped working. - await waitFor(() => expect(publishResult).toMatchObject({ ok: true })); - expect(toast.warning).not.toHaveBeenCalled(); - }); - - // objectstack#33277 — the registry refused the object of a batch that - // landed: the batch answers `published_unregistered` with `success: false`, - // and the object's element carries the `object-registry-refused` warning. - // The author reads that warning and the card its published verdict, as they - // did while the server answered `published` for this, never "Publish failed". - it('a published_unregistered batch still reaches the author as its warning, not as a failure', async () => { - const refused = { - severity: 'warning' as const, - rule: 'object-registry-refused', - where: 'object "ticket"', - path: '', - message: "object 'ticket' was published, but the runtime registry refused it, so it is NOT served", - hint: 'Resolve the registry\'s refusal, then publish the object again, or restart the server.', - }; - batchBody = { - success: true, - data: { - success: false, - outcome: 'published_unregistered', - publishedCount: 1, - failedCount: 0, - published: [{ type: 'object', name: 'ticket', advisories: [refused] }], - failed: [], - unregistered: [{ type: 'object', name: 'ticket', rule: 'object-registry-refused' }], - }, - }; - await publishFromAChatCard(); - - await waitFor(() => expect(publishResult).toMatchObject({ ok: true })); - await waitFor(() => expect(toast.warning).toHaveBeenCalled()); - const [, options] = vi.mocked(toast.warning).mock.calls[0] as [string, { description?: string } | undefined]; - expect(options?.description).toContain(refused.rule); - expect(toast.error).not.toHaveBeenCalled(); - }); -}); diff --git a/ui/packages/app-shell/src/console/ai/__tests__/AiChatPage.runtimeMessageSeam.test.tsx b/ui/packages/app-shell/src/console/ai/__tests__/AiChatPage.runtimeMessageSeam.test.tsx index a65e1a0ec57..c0482f04be4 100644 --- a/ui/packages/app-shell/src/console/ai/__tests__/AiChatPage.runtimeMessageSeam.test.tsx +++ b/ui/packages/app-shell/src/console/ai/__tests__/AiChatPage.runtimeMessageSeam.test.tsx @@ -26,6 +26,9 @@ * decision to route them through the one conversion stops being justified. */ +// AiChatPage reads a dropped spreadsheet through `import('@object-ui/plugin-grid')`; load it +// here so collection pays that transform, not a clocked case (check-test-source-alias). +import '@object-ui/plugin-grid'; import '@testing-library/jest-dom/vitest'; import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; import { cleanup, render, screen, waitFor } from '@testing-library/react'; @@ -75,7 +78,7 @@ vi.mock('@object-ui/plugin-chatbot', async (importOriginal) => { vi.mock('@object-ui/plugin-chatbot/core', async (importOriginal) => ({ ...(await importOriginal()), useAgents: () => ({ - agents: [{ name: 'metadata_assistant', label: 'Build', capabilities: ['build'] }], + agents: [{ name: 'ask', label: 'Ask' }], loading: false, error: undefined, refetch: vi.fn(), @@ -99,7 +102,7 @@ vi.mock('../ConversationsSidebar', () => ({ })); -import { AiChatPage, deriveBoundPackageId } from '../AiChatPage'; +import { AiChatPage } from '../AiChatPage'; window.matchMedia = ((query: string) => ({ matches: false, @@ -119,17 +122,16 @@ const CACHE_KEY = 'objectstack:ai-chat-messages:conv-seam'; * folds: a `'tool'`-role message, and a legacy `'result'` tool state on it. */ const TOOL_ROLE_THREAD: ObjectChatMessage[] = [ - { id: 'u1', role: 'user', content: 'build me a CRM' }, + { id: 'u1', role: 'user', content: 'how many opportunities?' }, { id: 'tool-turn', role: 'tool', - content: 'apply_blueprint finished', + content: 'aggregate_data finished', toolInvocations: [ { toolCallId: 't1', - toolName: 'apply_blueprint', + toolName: 'aggregate_data', state: 'result', - draftReview: { items: [{ type: 'object', name: 'lead' }], packageId: 'app.crm' }, pendingActionId: 'pa-1', }, ], @@ -160,7 +162,7 @@ function installFetch(): void { async function renderPage(): Promise { render( - + } /> } /> @@ -199,10 +201,6 @@ describe("AiChatPage routes the hook's messages through toRuntimeMessages (#4437 // The pass-through is what keeps the render-only keys alive across the // conversion — the affordances would silently vanish if it rebuilt. - expect(tools[0]?.draftReview).toEqual({ - items: [{ type: 'object', name: 'lead' }], - packageId: 'app.crm', - }); expect(tools[0]?.pendingActionId).toBe('pa-1'); }); @@ -234,15 +232,13 @@ describe("AiChatPage routes the hook's messages through toRuntimeMessages (#4437 // `sanitizeChatMessagesForCache` gates tool serialization on // `role === 'assistant'`, so pre-fold this turn cached its text and nothing - // else: the re-serialized draft envelope behind "Review N changes / - // Publish" never made it into the cache at all. - const toolPart = toolTurn?.parts.find((p) => p.type === 'tool-apply_blueprint'); + // else: the re-serialized approval envelope never made it into the cache. + const toolPart = toolTurn?.parts.find((p) => p.type === 'tool-aggregate_data'); expect(toolPart).toBeDefined(); expect(toolPart?.state).toBe('output-available'); expect(toolPart?.output).toMatchObject({ - status: 'drafted', - packageId: 'app.crm', - drafted: [{ type: 'object', name: 'lead' }], + status: 'pending_approval', + pendingActionId: 'pa-1', }); }); }); @@ -279,13 +275,6 @@ describe('#4437 fold-sensitivity: the two insensitive compute sites stay insensi expect(isConversationZh(toRuntimeMessages(zhOnlyOnToolTurn))).toBe(false); }); - it('deriveBoundPackageId: same package before and after the fold', () => { - // Newest-wins, and the packageId here rides the message whose role the fold - // rewrites — so a role-dependence would show up as it appearing or - // disappearing from the answer. - expect(deriveBoundPackageId(TOOL_ROLE_THREAD, undefined)).toBe('app.crm'); - expect(deriveBoundPackageId(toRuntimeMessages(TOOL_ROLE_THREAD), undefined)).toBe('app.crm'); - }); }); /** @@ -294,11 +283,11 @@ describe('#4437 fold-sensitivity: the two insensitive compute sites stay insensi * * Of the five cast sites, only two are observable: the `` prop * and the cache write both change what they produce when the fold is skipped, - * so restoring their cast reds a test above. The other three cannot red by - * construction — `isConversationZh` and `deriveBoundPackageId` are - * fold-INSENSITIVE (that is the measurement, pinned just above), and - * `useHitlInChat` reads a key the pass-through preserves either way. A cast - * coming back at any of those three is invisible to every runtime assertion in + * so restoring their cast reds a test above. The others cannot red by + * construction — `isConversationZh` is fold-INSENSITIVE (that is the + * measurement, pinned just above), and `useHitlInChat` reads a key the + * pass-through preserves either way. A cast coming back at either of those is + * invisible to every runtime assertion in * this file AND to `tsc`, because a cast is precisely the instruction to stop * checking. This net is what makes them non-silent. * diff --git a/ui/packages/app-shell/src/console/ai/__tests__/AiChatPage.seedWarnPackSentence-35303.test.tsx b/ui/packages/app-shell/src/console/ai/__tests__/AiChatPage.seedWarnPackSentence-35303.test.tsx deleted file mode 100644 index 16b6bc9c5c1..00000000000 --- a/ui/packages/app-shell/src/console/ai/__tests__/AiChatPage.seedWarnPackSentence-35303.test.tsx +++ /dev/null @@ -1,269 +0,0 @@ -/** - * ObjectUI - * Copyright (c) 2024-present ObjectStack Inc. - * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. - */ - -/** - * objectstack#35303 — the AI chat page's publish warns about a failed seed in - * the customer's words, never in the seed loader's. - * - * A failed seed answers `seedApplied.success === false`. Its `error` is the - * loader's own engine text, and an `errors[]` entry is a structured row - * (`{ row, reason }`), both written for whoever repairs the seed. The toast's - * description is the pack sentence `chatbot.build.health.seedFailed` (the - * sentence the chat's publish-health line says for the same failure, - * objectstack#32984); the engine text and the row reach `console.warn` - * whole, never the toast. - * - * Real: `AiChatPage`'s publish handler, `useMetadataClient` and its client, - * the publish-health reader, and `I18nProvider` with the shipped `en` and - * `zh-Hans` packs. Stubbed: `sonner` (the terminal sink), `globalThis.fetch` - * (the server), `console.warn` (observed), and the chat tree, reduced to the - * button that fires `onPublishDrafts`. - * - * Its own file: `I18nProvider` installs a module-level i18next global, which - * would leak into the default-value `t` the sibling publish pin reads. - */ - -import '@testing-library/jest-dom/vitest'; -import React from 'react'; -import { afterEach, beforeEach, describe, expect, it, vi, type MockInstance } from 'vitest'; -import { cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react'; -import { MemoryRouter, Route, Routes } from 'react-router-dom'; - -const PACKAGE_ID = 'app.k9qk'; - -vi.mock('sonner', () => ({ - toast: { - warning: vi.fn(), - error: vi.fn(), - success: vi.fn(), - info: vi.fn(), - message: vi.fn(), - dismiss: vi.fn(), - }, - Toaster: () => null, -})); - -/** What the chat card's Publish handed back. */ -let publishResult: unknown; - -vi.mock('@object-ui/plugin-chatbot', async (importOriginal) => { - const actual = await importOriginal>(); - return { - ...actual, - useAiModels: () => ({ models: [], defaultModelId: undefined }), - useHitlInChat: () => ({ decide: vi.fn(), decisions: {} }), - useObjectChat: () => ({ - messages: [], - isLoading: false, - error: undefined, - sendMessage: vi.fn(), - stop: vi.fn(), - reload: vi.fn(), - clear: vi.fn(), - setMessages: vi.fn(), - }), - ChatbotEnhanced: (props: Record) => { - const onPublishDrafts = props.onPublishDrafts as ((packageId: string) => Promise) | undefined; - return ( - - ); - }, - }; -}); -vi.mock('@object-ui/plugin-chatbot/core', async (importOriginal) => ({ - ...(await importOriginal()), - useAgents: () => ({ - agents: [{ name: 'metadata_assistant', label: 'Build', capabilities: ['build'] }], - loading: false, - error: undefined, - refetch: vi.fn(), - }), -})); - -vi.mock('@object-ui/auth', async (importOriginal) => { - const actual = await importOriginal>(); - return { ...actual, useAuth: () => ({ user: { id: 'u1' } }) }; -}); -vi.mock('../../../providers/MetadataProvider', async (importOriginal) => { - const actual = await importOriginal>(); - return { ...actual, useMetadata: () => ({ apps: [] }) }; -}); -vi.mock('../../../providers/AdapterProvider', async (importOriginal) => { - const actual = await importOriginal>(); - return { ...actual, useAdapter: () => null }; -}); -vi.mock('../ConversationsSidebar', () => ({ - ConversationsSidebar: () =>
, -})); - -import { toast } from 'sonner'; -import { I18nProvider, useObjectTranslation } from '@object-ui/i18n'; -import { en, zh } from '@object-ui/i18n/locales'; -import { AiChatPage } from '../AiChatPage'; - -window.matchMedia = ((query: string) => ({ - matches: false, - media: query, - onchange: null, - addEventListener: () => {}, - removeEventListener: () => {}, - addListener: () => {}, - removeListener: () => {}, - dispatchEvent: () => false, -})) as unknown as typeof window.matchMedia; - -const PACK = { en, 'zh-Hans': zh } as const; -type Locale = keyof typeof PACK; -const LOCALES: Locale[] = ['en', 'zh-Hans']; - -/** The seed loader's own text, as the runtime words a stopped seed apply. */ -const ENGINE_TEXT = "seed apply stopped at the seed for object 'crm_task': Reference not found: owner = \"ann\""; -/** One per-record failure as the loader reports it: a structured row, no `error`. */ -const ROW_ERROR = { row: 3, reason: 'Reference not found: owner = "ann"' }; -/** The prefix of the handler's console line, so other warnings never count. */ -const SEED_LOG_PREFIX = '[app-shell] Published, but the seed failed to load'; - -/** A published batch carrying the given `seedApplied`, inside the dispatcher's envelope. */ -function batchWithSeed(seedApplied: Record) { - return { - success: true, - data: { - success: true, - outcome: 'published', - publishedCount: 1, - failedCount: 0, - published: [{ type: 'seed', name: 'crm_sample_rows' }], - failed: [], - seedApplied, - }, - }; -} - -let batchBody: unknown; -let publishPosts = 0; -let warnSpy: MockInstance; - -function json(body: unknown) { - return new Response(JSON.stringify(body), { status: 200, headers: { 'content-type': 'application/json' } }); -} - -beforeEach(() => { - vi.clearAllMocks(); - batchBody = undefined; - publishPosts = 0; - publishResult = undefined; - window.localStorage.clear(); - window.sessionStorage.clear(); - warnSpy = vi.spyOn(console, 'warn').mockImplementation(() => {}); - vi.stubGlobal( - 'fetch', - vi.fn(async (input: unknown) => { - const url = String(input); - if (url.includes('/publish-drafts')) { - publishPosts += 1; - return json(batchBody); - } - return json({ success: true, data: [] }); - }) as unknown as typeof fetch, - ); -}); - -afterEach(() => { - cleanup(); - warnSpy.mockRestore(); - vi.unstubAllGlobals(); -}); - -function LanguageProbe() { - const { language } = useObjectTranslation(); - return
{language}
; -} - -/** Render the build surface in `locale` and fire a draft card's Publish. */ -async function publishFromAChatCardIn(locale: Locale): Promise { - render( - - - - - } /> - - - , - ); - await waitFor(() => expect(screen.getByTestId('language')).toHaveTextContent(locale)); - fireEvent.click(await screen.findByTestId('card-publish')); - await waitFor(() => expect(publishPosts).toBe(1)); - await waitFor(() => expect(publishResult).toMatchObject({ ok: true })); -} - -/** The one warning the publish raised: its title and its detail. */ -function seedWarning(): { title: string; description: unknown } { - const warnings = vi.mocked(toast.warning).mock.calls; - expect(warnings).toHaveLength(1); - const [title, opts] = warnings[0] as [string, { description?: unknown }]; - return { title, description: opts?.description }; -} - -/** The handler's console lines for a failed seed, with their payloads. */ -function seedLogs(): unknown[][] { - return warnSpy.mock.calls.filter((args) => typeof args[0] === 'string' && args[0].startsWith(SEED_LOG_PREFIX)); -} - -describe('AI chat publish warns about a failed seed in the pack’s sentence (objectstack#35303)', () => { - it.each(LOCALES)('%s: a seed that failed with engine text shows the pack sentence', async (locale) => { - batchBody = batchWithSeed({ success: false, inserted: 0, updated: 0, error: ENGINE_TEXT }); - await publishFromAChatCardIn(locale); - - const { title, description } = seedWarning(); - expect(title).toBe(PACK[locale].console.ai.seedWarn); - expect(description).toBe(PACK[locale].chatbot.build.health.seedFailed); - expect(String(description)).not.toContain(ENGINE_TEXT); - expect(toast.success).not.toHaveBeenCalled(); - - const logs = seedLogs(); - expect(logs).toHaveLength(1); - expect(logs[0][1]).toMatchObject({ packageId: PACKAGE_ID, error: ENGINE_TEXT }); - }); - - it.each(LOCALES)('%s: a seed that failed with a structured row and no error shows the pack sentence', async (locale) => { - batchBody = batchWithSeed({ success: false, inserted: 0, updated: 0, errors: [ROW_ERROR] }); - await publishFromAChatCardIn(locale); - - const { title, description } = seedWarning(); - expect(title).toBe(PACK[locale].console.ai.seedWarn); - expect(description).toBe(PACK[locale].chatbot.build.health.seedFailed); - expect(String(description)).not.toContain('[object Object]'); - - const logs = seedLogs(); - expect(logs).toHaveLength(1); - expect(logs[0][1]).toMatchObject({ packageId: PACKAGE_ID, errors: [ROW_ERROR] }); - }); -}); - -describe('control: a seed that loaded reads as before (objectstack#35303)', () => { - it.each(LOCALES)('%s: a seed that loaded raises no warning and logs nothing', async (locale) => { - batchBody = batchWithSeed({ success: true, inserted: 2, updated: 0 }); - await publishFromAChatCardIn(locale); - - expect(toast.warning).not.toHaveBeenCalled(); - expect(seedLogs()).toEqual([]); - expect(vi.mocked(toast.success).mock.calls).toHaveLength(1); - expect(vi.mocked(toast.success).mock.calls[0][0]).toBe(PACK[locale].console.ai.publishOk); - }); -}); diff --git a/ui/packages/app-shell/src/console/ai/__tests__/AiChatPage.sendOrderWhileUploading-34462.test.tsx b/ui/packages/app-shell/src/console/ai/__tests__/AiChatPage.sendOrderWhileUploading-34462.test.tsx index e79e273789e..954a8205e21 100644 --- a/ui/packages/app-shell/src/console/ai/__tests__/AiChatPage.sendOrderWhileUploading-34462.test.tsx +++ b/ui/packages/app-shell/src/console/ai/__tests__/AiChatPage.sendOrderWhileUploading-34462.test.tsx @@ -97,7 +97,6 @@ vi.mock('../../../providers/AdapterProvider', async (importOriginal) => ({ vi.mock('../../../hooks/useCanAuthorMetadata', () => ({ useCanAuthorMetadata: () => true })); vi.mock('../ConversationsSidebar', () => ({ ConversationsSidebar: () => null })); -vi.mock('../PendingDraftsBar', () => ({ PendingDraftsBar: () => null })); import { I18nProvider } from '@object-ui/i18n'; import { UploadProvider } from '@object-ui/fields'; diff --git a/ui/packages/app-shell/src/console/ai/__tests__/AiChatPage.startChips-1984.test.ts b/ui/packages/app-shell/src/console/ai/__tests__/AiChatPage.startChips-1984.test.ts deleted file mode 100644 index 701229d4ce7..00000000000 --- a/ui/packages/app-shell/src/console/ai/__tests__/AiChatPage.startChips-1984.test.ts +++ /dev/null @@ -1,67 +0,0 @@ -/** - * ObjectUI - * Copyright (c) 2024-present ObjectStack Inc. - * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. - */ - -/** - * cloud#1984 — the CALL-SITE half of the maker start chips. - * - * `packages/i18n/src/__tests__/makerStartChips-v1-scope-1984.test.ts` guards - * the ten packs. This guards the other copy of the same five strings: the - * `defaultValue` fallbacks in `metadataAssistantSuggestions()`, which are what - * a host with no I18nProvider (and any locale that ever loses the key) - * actually renders. Two copies of one string is exactly where a scope fix gets - * applied to one of them — the packs were reworded for ADR-0112 v1 and the - * fallbacks would have kept promising a status workflow and low-stock - * visibility, invisibly, on precisely the surface with the least i18n. - * - * So: byte-equality with the `en` pack, and the same automation-vocabulary ban. - */ -import { describe, it, expect } from 'vitest'; -import { builtInLocales } from '@object-ui/i18n/locales'; -import { buildAgentSuggestions } from '../AiChatPage.js'; - -/** A `t` that misses every key — i.e. what a provider-less host resolves. */ -const missEverything = (_key: string, options?: Record): string => - String(options?.defaultValue ?? _key); - -/** The `en` pack's chip block. */ -const enChips = ( - builtInLocales.en as { - console: { ai: { suggestions: { metadataAssistant: Record } } }; - } -).console.ai.suggestions.metadataAssistant; - -const CHIP_KEYS = ['buildCrm', 'buildApp', 'buildFlow', 'buildInventory', 'buildRecruiting'] as const; - -/** The English half of the i18n suite's banned vocabulary. @see makerStartChips-v1-scope-1984 */ -const BANNED_EN = ['alert', 'remind', 'notif', 'automat', 'workflow', 'trigger', 'schedule']; - -describe('metadataAssistantSuggestions — the build agent`s five start chips (cloud#1984)', () => { - it('renders the five authoring starters for the build agent', () => { - const chips = buildAgentSuggestions('build', 'Build', missEverything); - expect(chips).toHaveLength(5); - }); - - it('every `defaultValue` is byte-equal to the en pack', () => { - const chips = buildAgentSuggestions('build', 'Build', missEverything); - expect(chips).toEqual(CHIP_KEYS.map((k) => enChips[k])); - }); - - it('no fallback promises autonomous behaviour', () => { - for (const chip of buildAgentSuggestions('build', 'Build', missEverything)) { - const hits = BANNED_EN.filter((term) => chip.toLowerCase().includes(term)); - expect(hits, chip).toEqual([]); - } - }); - - it('the control: the retired wording WOULD have been flagged', () => { - // Non-vacuity, same reasoning as the pack-side suite: a banned list that - // has stopped matching anything passes the assertion above in silence. - const retired = 'Design a support desk — tickets with priority, a status workflow, and customer links.'; - expect(BANNED_EN.filter((term) => retired.toLowerCase().includes(term))).toContain('workflow'); - }); -}); diff --git a/ui/packages/app-shell/src/console/ai/__tests__/AiChatPage.studioDraftsBar-12965.test.tsx b/ui/packages/app-shell/src/console/ai/__tests__/AiChatPage.studioDraftsBar-12965.test.tsx deleted file mode 100644 index 7e7fa32becb..00000000000 --- a/ui/packages/app-shell/src/console/ai/__tests__/AiChatPage.studioDraftsBar-12965.test.tsx +++ /dev/null @@ -1,153 +0,0 @@ -// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. - -/** - * objectui#12965 (part of objectui#12725) — `ChatPane` does not draw the - * floating pending-drafts bar in the package's own Studio. - * - * In the Studio copilot's right slot the bar (`PendingDraftsBar`, objectui#5694) - * floated over the composer's input line and hid its placeholder. There the - * Studio top bar's 变更 and 发布 and the applied card's 查看变更并发布 are the - * ways to review and publish, and objectui#12725's ruled artboard draws no - * bar. Outside Studio — the full-page chat and the console dock — the bar - * stays (since objectui#12978 as a row of the composer's area, not a float). - * - * Every case has a draft pending for the bound package, so the bar has - * something to draw. In Studio, the sibling probe reads the same ledger - * through the same hook the Studio top bar's 变更 badge uses; it answers 1 - * before the bar's absence is read, so the absence is not a read taken before - * the ledger answered. No layout runs here: the composer's unobstructed input - * line was measured in a real browser at 1010 and 1280 px, on this card's - * evidence branch. - * - * Same harness as `AiChatPage.appliedCardDoors-12894.test.tsx`: the real pane, - * with `ChatbotEnhanced` replaced by a stub, and the real `PendingDraftsBar`. - */ - -import '@testing-library/jest-dom/vitest'; -import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; -import { cleanup, render, screen, waitFor } from '@testing-library/react'; -import { MemoryRouter } from 'react-router-dom'; -import React from 'react'; - -vi.mock('@object-ui/plugin-chatbot', async (importOriginal) => { - const actual = await importOriginal>(); - return { - ...actual, - // objectui#12978 — the bar is a row of the composer's own area now, handed - // in through `promptHeaderSlot`; the stub draws that slot so the bar can be - // read. Where it sits against the input is pinned with the real component - // in `AiChatPage.draftsBarInFlow-12978.test.tsx`. - ChatbotEnhanced: ({ promptHeaderSlot }: { promptHeaderSlot?: React.ReactNode }) => ( -
{promptHeaderSlot}
- ), - useObjectChat: () => ({ - messages: [], - isLoading: false, - error: undefined, - sendMessage: vi.fn(), - stop: vi.fn(), - reload: vi.fn(), - clear: vi.fn(), - setMessages: vi.fn(), - }), - useAiModels: () => ({ models: [], defaultModelId: undefined }), - }; -}); - -vi.mock('../../../providers/MetadataProvider', async (importOriginal) => { - const actual = await importOriginal>(); - return { ...actual, useMetadata: () => ({ apps: [] }) }; -}); -vi.mock('../../../providers/AdapterProvider', async (importOriginal) => { - const actual = await importOriginal>(); - return { ...actual, useAdapter: () => null }; -}); - -import { I18nProvider } from '@object-ui/i18n'; -import type { AgentDescriptor } from '@object-ui/plugin-chatbot'; -import { ChatPane } from '../AiChatPage'; -import { usePendingDrafts } from '../../../preview/usePendingDrafts'; - -window.matchMedia = ((query: string) => ({ - matches: false, - media: query, - onchange: null, - addEventListener: () => {}, - removeEventListener: () => {}, - addListener: () => {}, - removeListener: () => {}, - dispatchEvent: () => false, -})) as unknown as typeof window.matchMedia; - -const PKG = 'app.hcpl'; -const AGENTS = [{ name: 'build', label: 'Build' }] as unknown as AgentDescriptor[]; -const DRAFT = { type: 'object', name: 'hcpl_borrowing', label: 'Borrowing', packageId: PKG }; - -/** Reads the package's pending drafts the way the Studio top bar's 变更 badge does. */ -function DraftsBadgeProbe({ packageId }: { packageId: string }): React.ReactElement { - const { count } = usePendingDrafts({ packageId }); - return
{count === null ? '' : String(count)}
; -} - -function renderPane(entry: string) { - return render( - - - - - - , - ); -} - -beforeEach(() => { - window.localStorage.clear(); - // One draft pending for the bound package; every other request answers empty. - vi.stubGlobal( - 'fetch', - vi.fn(async (url: unknown) => { - const body = String(url).includes('/meta/_drafts') ? { drafts: [DRAFT] } : { success: true, data: [] }; - return new Response(JSON.stringify(body), { - status: 200, - headers: { 'Content-Type': 'application/json' }, - }); - }), - ); -}); -afterEach(() => { - cleanup(); - vi.unstubAllGlobals(); -}); - -describe('objectui#12965 — the pending-drafts bar in the Studio copilot', () => { - it('on one of the package\'s Studio pillars, with a draft pending, no pending-drafts bar is drawn', async () => { - renderPane('/studio/app.hcpl/interfaces?surface=object%3Ahcpl_borrowing'); - // The ledger has answered with the pending draft (the 变更 badge's reading)... - await waitFor(() => expect(screen.getByTestId('drafts-badge-probe').textContent).toBe('1')); - // ...and the chat draws no bar over its composer. - expect(screen.getByTestId('ai-chat-panel')).toBeInTheDocument(); - expect(screen.queryByTestId('pending-drafts-bar')).toBeNull(); - }); - - it.each([ - ['the full-page chat', '/ai/build/conv-1?package=app.hcpl'], - ['the console dock, inside the running app', '/apps/hcpl/hcpl_borrowing'], - ])('CONTROL: %s, with a draft pending, still draws the bar', async (_host, entry) => { - renderPane(entry); - expect(await screen.findByTestId('pending-drafts-bar')).toBeInTheDocument(); - expect(screen.getByTestId('drafts-badge-probe').textContent).toBe('1'); - }); -}); diff --git a/ui/packages/app-shell/src/console/ai/__tests__/AiChatPage.toolLabelsLocale-11667.test.tsx b/ui/packages/app-shell/src/console/ai/__tests__/AiChatPage.toolLabelsLocale-11667.test.tsx index 7c5311f7888..29b2470ed2f 100644 --- a/ui/packages/app-shell/src/console/ai/__tests__/AiChatPage.toolLabelsLocale-11667.test.tsx +++ b/ui/packages/app-shell/src/console/ai/__tests__/AiChatPage.toolLabelsLocale-11667.test.tsx @@ -1,44 +1,34 @@ // Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. /** - * objectui#11667 — the AI chat's tool-approval card and Builder handoff card - * speak the session's language. + * objectui#11667 — the AI chat's tool-approval card speaks the session's + * language. * * `ChatPane` handed `ChatbotEnhanced` three literals for the inline HITL card * ("Approve & run", "Reject", and the deny reason "Operator rejected from - * chat") and left the ADR-0057 P4 handoff card on the component's English - * defaults ("Build this in the Builder", "Open in Builder →", and the - * superseded card's tooltip "A newer request is available"). Every other label - * on the same screen was already a `console.ai.*` key, so a zh-CN reader met - * these six in English. + * chat"). Every other label on the same screen was already a `console.ai.*` + * key, so a zh-CN reader met these three in English. * * Rendered as shipped: the REAL `ChatbotEnhanced` under a real `I18nProvider`, * with only the transport (`useObjectChat`) stubbed so the conversation is a - * fixture — one tool call awaiting approval, and two handoff cards, so one of - * them is the superseded card whose tooltip is the sixth string. The deny - * reason is read where it is RECORDED: the body of the reject request the real - * `useHitlInChat` sends. + * fixture — one tool call awaiting approval. The deny reason is read where it + * is RECORDED: the body of the reject request the real `useHitlInChat` sends. */ +// AiChatPage reads a dropped spreadsheet through `import('@object-ui/plugin-grid')`; load it +// here so collection pays that transform, not a clocked case (check-test-source-alias). +import '@object-ui/plugin-grid'; import '@testing-library/jest-dom/vitest'; import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; import { act, cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react'; import { MemoryRouter } from 'react-router-dom'; import React from 'react'; -/** The six strings the card names, as they used to reach every locale. */ -const ENGLISH = [ - 'Approve & run', - 'Reject', - 'Operator rejected from chat', - 'Build this in the Builder', - 'Open in Builder →', - 'A newer request is available', -] as const; +/** The three strings the card names, as they used to reach every locale. */ +const ENGLISH = ['Approve & run', 'Reject', 'Operator rejected from chat'] as const; /** * The conversation: one destructive tool call held for approval (the shape - * `mapMessages` lifts from a `pending_approval` result), then two - * `suggest_builder` handoffs — the older one is superseded by the newer one. + * `mapMessages` lifts from a `pending_approval` result). * Module-scoped so the stubbed hook hands back one stable array. */ const MESSAGES = [ @@ -57,34 +47,6 @@ const MESSAGES = [ }, ], }, - { - id: 'a2', - role: 'assistant', - content: '', - toolInvocations: [ - { - toolCallId: 'call-handoff-old', - toolName: 'suggest_builder', - state: 'output-available', - result: { handoff: 'build', prompt: 'Build a CRM' }, - builderHandoff: { prompt: 'Build a CRM' }, - }, - ], - }, - { - id: 'a3', - role: 'assistant', - content: '', - toolInvocations: [ - { - toolCallId: 'call-handoff-new', - toolName: 'suggest_builder', - state: 'output-available', - result: { handoff: 'build', prompt: 'Build a CRM with deals' }, - builderHandoff: { prompt: 'Build a CRM with deals' }, - }, - ], - }, ]; const sendMessage = vi.fn(); @@ -207,17 +169,14 @@ afterEach(() => { vi.unstubAllGlobals(); }); -describe('AI chat tool-approval and Builder handoff labels follow the UI locale (objectui#11667)', () => { - it('zh-CN: none of the six English strings reaches the reader, and each surface renders in Chinese', async () => { +describe('AI chat tool-approval labels follow the UI locale (objectui#11667)', () => { + it('zh-CN: none of the three English strings reaches the reader, and the card renders in Chinese', async () => { const { container } = renderPane('zh-CN'); - // Each surface is on the page — so the absence below is a reading, not an + // The card is on the page — so the absence below is a reading, not an // empty render. expect(await screen.findByRole('button', { name: '通过并执行' })).toBeInTheDocument(); expect(screen.getByRole('button', { name: '拒绝' })).toBeInTheDocument(); - expect(screen.getAllByText('在构建器中搭建')).toHaveLength(2); - expect(screen.getByTestId('builder-handoff-open')).toHaveTextContent('在构建器中打开 →'); - expect(screen.getByTestId('builder-handoff-superseded')).toHaveAttribute('title', '已有更新的请求'); expect(englishFound(container)).toEqual([]); diff --git a/ui/packages/app-shell/src/console/ai/__tests__/AiChatPage.uiLocale-34639.test.tsx b/ui/packages/app-shell/src/console/ai/__tests__/AiChatPage.uiLocale-34639.test.tsx index 33c7410596b..62c669000f2 100644 --- a/ui/packages/app-shell/src/console/ai/__tests__/AiChatPage.uiLocale-34639.test.tsx +++ b/ui/packages/app-shell/src/console/ai/__tests__/AiChatPage.uiLocale-34639.test.tsx @@ -20,6 +20,9 @@ * `ChatPane`, so it is covered by the same seam. */ +// AiChatPage reads a dropped spreadsheet through `import('@object-ui/plugin-grid')`; load it +// here so collection pays that transform, not a clocked case (check-test-source-alias). +import '@object-ui/plugin-grid'; import '@testing-library/jest-dom/vitest'; import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; import { cleanup, render } from '@testing-library/react'; @@ -145,6 +148,6 @@ describe('AI chat request carries the console UI language as context.uiLocale (o it('the rest of the context is unchanged beside it', () => { const { context } = renderPane('en'); expect(context.agentName).toBe('build'); - expect(Object.keys(context).sort()).toEqual(['agentName', 'autoPublishAiBuilds', 'uiLocale']); + expect(Object.keys(context).sort()).toEqual(['agentName', 'uiLocale']); }); }); diff --git a/ui/packages/app-shell/src/console/ai/__tests__/BuildDebugDrawer.test.tsx b/ui/packages/app-shell/src/console/ai/__tests__/BuildDebugDrawer.test.tsx deleted file mode 100644 index ee6c48e31e0..00000000000 --- a/ui/packages/app-shell/src/console/ai/__tests__/BuildDebugDrawer.test.tsx +++ /dev/null @@ -1,73 +0,0 @@ -// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. - -import '@testing-library/jest-dom/vitest'; -import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'; -import { render, screen } from '@testing-library/react'; -import { I18nProvider } from '@object-ui/i18n'; -import { BuildDebugDrawer } from '../BuildDebugDrawer'; -import type { BuildDebugReport } from '../buildDebugApi'; - -const REPORT: BuildDebugReport = { - conversationId: 'conv_x', - title: '开发报销流程', - summary: { models: ['openai/gpt-5.4-mini'], userTurns: 3, messages: 36, totalTokens: 242495, llmMs: 82900 }, - reconciliation: { - orphaned: [ - { t: '04:29:43', tool: 'create_metadata', status: 'changes_proposed', artifact: { type: 'flow', name: 'reimbursement_approval_flow' } }, - ], - missing: [], - errors: [], - liveCount: 9, - ok: false, - }, - verify: { status: 'failed', errors: 2, warnings: 16, userIssues: [], platformNoise: 18 }, - timeline: [{ t: '04:23:45', kind: 'user', text: '开发报销流程' }], - pendingActions: [], -}; - -// The drawer's chrome reads `console.ai.buildDoctorDrawer.*` (objectui#10969), -// so it renders under the en pack the console always mounts; its zh reading is -// pinned in `buildDoctor.drawerBody-10969`. -function renderDrawer() { - return render( - - {}} /> - , - ); -} - -describe('BuildDebugDrawer', () => { - beforeEach(() => { - vi.stubGlobal( - 'fetch', - vi.fn(async () => ({ headers: new Headers(), ok: true, status: 200, json: async () => REPORT })), - ); - }); - afterEach(() => { - vi.unstubAllGlobals(); - }); - - it('renders the orphaned proposal (审批流 evaporated) + de-noised verify when opened', async () => { - renderDrawer(); - - // The headline failure: a proposed change that never landed. - expect(await screen.findByText(/Proposed but never applied/)).toBeInTheDocument(); - expect(screen.getByText(/reimbursement_approval_flow/)).toBeInTheDocument(); - // Verdict reflects a discrepancy. - expect(screen.getByText(/doesn't match what's live/)).toBeInTheDocument(); - // verify_build de-noised: platform noise hidden, not failing the user's app. - expect(screen.getByText(/18 platform sys_\* finding/)).toBeInTheDocument(); - }); - - it('hits the debug endpoint for the conversation', async () => { - const spy = vi.fn(async () => ({ headers: new Headers(), ok: true, status: 200, json: async () => REPORT })); - vi.stubGlobal('fetch', spy); - renderDrawer(); - await screen.findByText(/Proposed but never applied/); - // The authenticated fetch hands the wire a `Headers` (the bearer, when one is stored). - expect(spy).toHaveBeenCalledWith('/api/v1/ai/conversations/conv_x/debug', { - credentials: 'include', - headers: expect.any(Headers), - }); - }); -}); diff --git a/ui/packages/app-shell/src/console/ai/__tests__/ExcelImportBar.importGrant-12082.test.tsx b/ui/packages/app-shell/src/console/ai/__tests__/ExcelImportBar.importGrant-12082.test.tsx deleted file mode 100644 index f93a0aa578d..00000000000 --- a/ui/packages/app-shell/src/console/ai/__tests__/ExcelImportBar.importGrant-12082.test.tsx +++ /dev/null @@ -1,164 +0,0 @@ -// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. - -/** - * objectui#12082 — the AI build panel's spreadsheet import reads the - * `listImport` row of the affordance-to-grant map, asked of the object it - * imports into. - * - * `ExcelImportBar` is the second mount of `ImportWizard`: the console list's - * Import is the first, and it has read the `listImport` row since the map - * landed. The bar read no grant at all, so a caller who may not create records - * of the picked object could press Import, map the sheet and run it, and every - * row was refused by the server. The bar now offers Import for the picked - * object only when its row allows it — the caller's create grant and the - * effective operation set — and picking another object asks again. - * - * Measured through the REAL `MePermissionsProvider`; the wizard is a probe that - * records the object it was opened for. - */ - -import '@testing-library/jest-dom/vitest'; -import * as React from 'react'; -import { describe, it, expect, vi, beforeEach } from 'vitest'; -import { render, cleanup, fireEvent, waitFor, screen, within, act } from '@testing-library/react'; -import { MePermissionsProvider, type MePermissionsResponse, type MePermissionsAuthenticatedResponse } from '@object-ui/permissions'; - -const h = vi.hoisted(() => ({ - /** The objects the bar lists as import targets. */ - objects: [ - { name: 'crm_account', label: 'Account' }, - { name: 'crm_deal', label: 'Deal' }, - ], - /** The props each mounted ImportWizard received. */ - wizard: [] as Array>, -})); - -vi.mock('@object-ui/auth', async (importOriginal) => ({ - ...(await importOriginal>()), - createAuthenticatedFetch: () => async () => - new Response(JSON.stringify({ data: { items: h.objects } }), { - status: 200, - headers: { 'content-type': 'application/json' }, - }), -})); -vi.mock('@object-ui/plugin-grid', async (importOriginal) => ({ - ...(await importOriginal>()), - ImportWizard: (props: { objectName: string; fields?: Array<{ name: string }> }) => { - h.wizard.push({ objectName: props.objectName, fields: props.fields }); - return
; - }, -})); -vi.mock('sonner', () => ({ toast: Object.assign(vi.fn(), { success: vi.fn(), error: vi.fn() }) })); - -import { ExcelImportBar } from '../ExcelImportBar'; - -const FILE = new File(['a,b\n1,2'], 'deals.xlsx'); -/** What `t()` answers with no i18n provider: the key itself. */ -const IMPORT = 'excelImport.importAction'; - -const SHAPES: Array<{ shape: string; bits: Record; create: boolean }> = [ - { shape: 'create-only', bits: { allowCreate: true, allowRead: true, allowEdit: false, allowDelete: false }, create: true }, - { shape: 'edit-only', bits: { allowCreate: false, allowRead: true, allowEdit: true, allowDelete: false }, create: false }, - { shape: 'read-only', bits: { allowCreate: false, allowRead: true, allowEdit: false, allowDelete: false }, create: false }, - { shape: 'full', bits: { allowCreate: true, allowRead: true, allowEdit: true, allowDelete: true }, create: true }, -]; -const FULL = SHAPES[3].bits; - -const envelope = (objects: Record>): MePermissionsAuthenticatedResponse => ({ - authenticated: true, - userId: 'u-pin', - tenantId: null, - positions: ['member'], - hasAnyQueue: false, - objectsUsingQueues: [], - permissionSets: ['member'], - objects: objects as never, - fields: {}, -}); - -const settle = () => act(() => new Promise((resolve) => setTimeout(resolve, 50))); - -function mount(perms: MePermissionsResponse | null) { - const dataSource = { - getObjectSchema: vi.fn(async (_name: string) => ({ fields: { title: { type: 'text', label: 'Title' } } })), - }; - const bar = ; - render(perms ? {bar} : bar); - return { dataSource }; -} - -const importButton = () => screen.getByRole('button', { name: IMPORT }); - -/** Press Import; report whether the wizard opened, and for which object. */ -async function pressImport(dataSource: { getObjectSchema: ReturnType }): Promise { - fireEvent.click(importButton()); - await settle(); - if (!screen.queryByTestId('import-wizard')) { - expect(dataSource.getObjectSchema).not.toHaveBeenCalled(); - return null; - } - return String(h.wizard[h.wizard.length - 1].objectName); -} - -beforeEach(() => { - cleanup(); - h.wizard.length = 0; -}); - -describe.each(SHAPES)('the spreadsheet import bar under a $shape grant on its target (objectui#12082)', ({ bits, create }) => { - it('Import is offered exactly when the create grant allows it', async () => { - const { dataSource } = mount(envelope({ crm_account: bits, crm_deal: bits })); - await settle(); - expect(importButton()).toHaveTextContent(IMPORT); - expect(importButton().hasAttribute('disabled'), 'disabled').toBe(!create); - expect(await pressImport(dataSource)).toBe(create ? 'crm_account' : null); - }); -}); - -describe("the spreadsheet import bar: the map's other layers and fail-open (objectui#12082)", () => { - it('fail-open: with no permission provider Import is offered, as before', async () => { - const { dataSource } = mount(null); - await settle(); - expect(importButton()).not.toBeDisabled(); - expect(await pressImport(dataSource)).toBe('crm_account'); - }); - - it('an effective operation set without import withholds Import under the full grant', async () => { - const { dataSource } = mount(envelope({ crm_account: { ...FULL, apiOperations: ['get', 'list', 'create', 'update'] } })); - await settle(); - expect(importButton()).toBeDisabled(); - expect(await pressImport(dataSource)).toBeNull(); - }); - - it('the verdict is asked of the PICKED object: a closed target, then an open one', async () => { - const { dataSource } = mount(envelope({ crm_account: SHAPES[2].bits, crm_deal: FULL })); - await settle(); - expect(importButton()).toBeDisabled(); - fireEvent.keyDown(screen.getByRole('combobox'), { key: 'ArrowDown' }); - const listbox = await screen.findByRole('listbox'); - fireEvent.click(within(listbox).getAllByRole('option').find((o) => o.textContent === 'Deal')!); - await waitFor(() => expect(importButton()).not.toBeDisabled()); - expect(await pressImport(dataSource)).toBe('crm_deal'); - }); -}); - -describe('the spreadsheet import bar: a field carrying an expression (objectstack#31759)', () => { - it('is not offered to the wizard: the engine computes it on every write, so an imported value never stands', async () => { - const dataSource = { - getObjectSchema: vi.fn(async (_name: string) => ({ - fields: { - title: { type: 'text', label: 'Title' }, - price: { type: 'currency', label: 'Price' }, - amount: { type: 'currency', label: 'Amount', expression: 'record.quantity * record.unit_price' }, - total: { type: 'formula', label: 'Total' }, - }, - })), - }; - render(); - await settle(); - expect(await pressImport(dataSource)).toBe('crm_account'); - const offered = (h.wizard[h.wizard.length - 1].fields as Array<{ name: string }>).map((f) => f.name); - // CONTROL: the plain currency field of the same shape is still offered; a formula still is not. - expect(offered).toEqual(['title', 'price']); - }); -}); diff --git a/ui/packages/app-shell/src/console/ai/__tests__/ExcelImportBar.sharedSelect-11865.test.tsx b/ui/packages/app-shell/src/console/ai/__tests__/ExcelImportBar.sharedSelect-11865.test.tsx deleted file mode 100644 index 1de2887e579..00000000000 --- a/ui/packages/app-shell/src/console/ai/__tests__/ExcelImportBar.sharedSelect-11865.test.tsx +++ /dev/null @@ -1,234 +0,0 @@ -// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. - -/** - * The Excel import bar's target-object picker is the shared `Select` - * (objectui#11865). - * - * The bar in the AI build panel ("Import deals.xlsx into …") picked its target - * object with a browser-native select, beside the shared Radix `Select` the - * rest of the console picks with. The card asks for one control for one kind - * of choice, surface by surface. - * - * What is pinned: - * - the picker IS the primitive (a Radix combobox trigger); no native select - * is left in the bar; - * - it had no accessible name and still has none (kept for parity; see the - * pull request's acceptance notes); - * - it lists the objects the native control listed, in its order, and - * starts on the same one; - * - every option leads to the import the native control led to (the schema - * read and the wizard's object), compared as JSON text; - * - a held object name the list does not carry is what the trigger shows; - * - with no object to list it is the primitive's disabled trigger - * (objectui#11781); - * - the keyboard alone opens the picker and selects. - * - * DIRECTION, observed against the native control: every pin here but the name - * pin is red there, because each one reads the picker as the primitive's - * trigger. What makes the write rows guards of "the conversion changed nothing - * the bar imports into" is the literal each compares against: a `change` event - * on the pre-conversion bar's native control, then Import, led to that same - * JSON, read once on that bar with these fixtures. The held-name readings were - * taken there the same way. - */ - -import '@testing-library/jest-dom/vitest'; -import * as React from 'react'; -import { describe, it, expect, vi, beforeEach } from 'vitest'; -import { render, cleanup, fireEvent, waitFor, screen, within, act } from '@testing-library/react'; - -const h = vi.hoisted(() => ({ - /** What the object list answers; `null` makes it fail. */ - objects: [] as unknown[] | null, - /** The props each mounted ImportWizard received. */ - wizard: [] as Array>, -})); - -vi.mock('@object-ui/auth', async (importOriginal) => ({ - ...(await importOriginal>()), - createAuthenticatedFetch: () => async () => - h.objects === null - ? new Response('unavailable', { status: 500 }) - : new Response(JSON.stringify({ data: { items: h.objects } }), { - status: 200, - headers: { 'content-type': 'application/json' }, - }), -})); -vi.mock('@object-ui/plugin-grid', async (importOriginal) => ({ - ...(await importOriginal>()), - ImportWizard: (props: { objectName: string; objectLabel: string; fields: unknown; initialFile?: File }) => { - h.wizard.push({ - objectName: props.objectName, - objectLabel: props.objectLabel, - fields: props.fields, - file: props.initialFile?.name, - }); - return
; - }, -})); -vi.mock('sonner', () => ({ toast: Object.assign(vi.fn(), { success: vi.fn(), error: vi.fn() }) })); - -import { ExcelImportBar } from '../ExcelImportBar'; - -/** The served object list: a platform object the bar filters out, and one with no label. */ -const OBJECTS = [ - { name: 'crm_account', label: 'Account' }, - { name: 'sys_user', label: 'User' }, - { name: 'crm_deal', label: 'Deal' }, - { name: 'crm_lead' }, -]; -const FILE = new File(['a,b\n1,2'], 'deals.xlsx'); -/** What `t()` answers with no i18n provider: the key itself. */ -const IMPORT = 'excelImport.importAction'; - -const settle = () => act(() => new Promise((resolve) => setTimeout(resolve, 50))); - -function mount(defaultObjectName?: string) { - const dataSource = { - getObjectSchema: vi.fn(async (_name: string) => ({ - fields: { title: { type: 'text', label: 'Title' }, total: { type: 'formula' } }, - })), - }; - const utils = render( - , - ); - return { ...utils, dataSource }; -} - -/** The bar's picker: its one combobox. */ -const trigger = () => screen.getByRole('combobox'); -const importButton = () => screen.getByRole('button', { name: IMPORT }); - -async function openPicker(): Promise { - fireEvent.keyDown(trigger(), { key: 'ArrowDown' }); - const listbox = await screen.findByRole('listbox'); - return within(listbox).getAllByRole('option'); -} - -async function pick(label: string): Promise { - const options = await openPicker(); - const option = options.find((o) => o.textContent === label); - if (!option) throw new Error(`no "${label}" listed: ${options.map((o) => o.textContent).join(' | ')}`); - fireEvent.click(option); - await waitFor(() => expect(screen.queryByRole('listbox')).not.toBeInTheDocument()); -} - -/** Press Import and return what it led to as JSON text: the schema read and the wizard's object. */ -async function doImport(dataSource: { getObjectSchema: ReturnType }): Promise { - fireEvent.click(importButton()); - await screen.findByTestId('import-wizard'); - return JSON.stringify({ getObjectSchema: dataSource.getObjectSchema.mock.calls, wizard: h.wizard[h.wizard.length - 1] }); -} - -beforeEach(() => { - cleanup(); - h.objects = OBJECTS; - h.wizard.length = 0; -}); - -describe('the target-object picker is the shared Select (objectui#11865)', () => { - it('renders the picker as the Radix combobox trigger, on the first listed object', async () => { - const { container } = mount(); - await settle(); - expect(trigger().tagName).toBe('BUTTON'); - expect(trigger()).toHaveTextContent('Account'); - expect(container.querySelectorAll('select')).toHaveLength(0); - }); - - // Green against the native control too, by design: it pins what the conversion kept. - it('has no accessible name, as the native control had none', async () => { - mount(); - await settle(); - expect(screen.getAllByRole('combobox')).toHaveLength(1); - expect(screen.getByRole('combobox', { name: '' })).toBe(trigger()); - }); - - it('lists the objects the native control listed, in its order', async () => { - mount(); - await settle(); - expect((await openPicker()).map((o) => o.textContent)).toEqual(['Account', 'Deal', 'crm_lead']); - }); -}); - -/** [the option picked, the JSON text of what Import led to]. */ -const WRITES: ReadonlyArray = [ - ['Account', '{"getObjectSchema":[["crm_account"]],"wizard":{"objectName":"crm_account","objectLabel":"Account","fields":[{"name":"title","label":"Title","type":"text","required":false}],"file":"deals.xlsx"}}'], - ['Deal', '{"getObjectSchema":[["crm_deal"]],"wizard":{"objectName":"crm_deal","objectLabel":"Deal","fields":[{"name":"title","label":"Title","type":"text","required":false}],"file":"deals.xlsx"}}'], - ['crm_lead', '{"getObjectSchema":[["crm_lead"]],"wizard":{"objectName":"crm_lead","objectLabel":"crm_lead","fields":[{"name":"title","label":"Title","type":"text","required":false}],"file":"deals.xlsx"}}'], -]; - -describe('every option imports into what the native control imported into', () => { - it.each(WRITES)('%s', async (label, json) => { - const { dataSource } = mount(); - await settle(); - await pick(label); - expect(trigger()).toHaveTextContent(label); - expect(await doImport(dataSource)).toBe(json); - }); - - it('starts on `defaultObjectName` when the list carries it', async () => { - const { dataSource } = mount('crm_deal'); - await settle(); - expect(trigger().textContent).toBe('Deal'); - expect(await doImport(dataSource)).toBe( - '{"getObjectSchema":[["crm_deal"]],"wizard":{"objectName":"crm_deal","objectLabel":"Deal","fields":[{"name":"title","label":"Title","type":"text","required":false}],"file":"deals.xlsx"}}', - ); - }); -}); - -describe('a held object name the list does not carry is what the trigger shows', () => { - it('a `defaultObjectName` the list does not return: shown, and imported into as held', async () => { - const { dataSource } = mount('ghost'); - await settle(); - // The native control showed "Account" here while Import loaded into `ghost`. - expect(trigger()).toHaveTextContent('ghost'); - expect((await openPicker()).map((o) => o.textContent)).toEqual(['ghost', 'Account', 'Deal', 'crm_lead']); - fireEvent.keyDown(screen.getByRole('listbox'), { key: 'Escape' }); - await waitFor(() => expect(screen.queryByRole('listbox')).not.toBeInTheDocument()); - expect(await doImport(dataSource)).toBe( - '{"getObjectSchema":[["ghost"]],"wizard":{"objectName":"ghost","objectLabel":"ghost","fields":[{"name":"title","label":"Title","type":"text","required":false}],"file":"deals.xlsx"}}', - ); - }); - - it('a failed object list with a `defaultObjectName`: disabled, showing the object Import still loads into', async () => { - h.objects = null; - const { dataSource } = mount('crm_deal'); - await settle(); - // The native control was disabled and blank here while Import loaded into `crm_deal`. - expect(trigger()).toBeDisabled(); - expect(trigger().textContent).toBe('crm_deal'); - expect(importButton()).toBeEnabled(); - expect(await doImport(dataSource)).toBe( - '{"getObjectSchema":[["crm_deal"]],"wizard":{"objectName":"crm_deal","objectLabel":"crm_deal","fields":[{"name":"title","label":"Title","type":"text","required":false}],"file":"deals.xlsx"}}', - ); - }); -}); - -describe('with no object to list, the picker is disabled through the primitive (objectui#11781)', () => { - it('an empty list: disabled, the keyboard does not open it, and Import stays disabled', async () => { - h.objects = []; - mount(); - await settle(); - // The primitive's disabled trigger: Radix marks it `data-disabled`. - expect(trigger()).toBeDisabled(); - expect(trigger()).toHaveAttribute('data-disabled'); - fireEvent.keyDown(trigger(), { key: 'ArrowDown' }); - fireEvent.keyDown(trigger(), { key: 'Enter' }); - await settle(); - expect(screen.queryByRole('listbox')).not.toBeInTheDocument(); - expect(importButton()).toBeDisabled(); - }); -}); - -describe('the keyboard alone picks', () => { - it('Enter opens the picker and Enter on an option selects it', async () => { - const { dataSource } = mount(); - await settle(); - fireEvent.keyDown(trigger(), { key: 'Enter' }); - const listbox = await screen.findByRole('listbox'); - fireEvent.keyDown(within(listbox).getByRole('option', { name: 'Deal' }), { key: 'Enter' }); - await waitFor(() => expect(screen.queryByRole('listbox')).not.toBeInTheDocument()); - expect(trigger()).toHaveTextContent('Deal'); - expect(await doImport(dataSource)).toBe(WRITES[1][1]); - }); -}); diff --git a/ui/packages/app-shell/src/console/ai/__tests__/PendingDraftsBar.sentenceWraps-13088.test.tsx b/ui/packages/app-shell/src/console/ai/__tests__/PendingDraftsBar.sentenceWraps-13088.test.tsx deleted file mode 100644 index 97d0d778b76..00000000000 --- a/ui/packages/app-shell/src/console/ai/__tests__/PendingDraftsBar.sentenceWraps-13088.test.tsx +++ /dev/null @@ -1,111 +0,0 @@ -// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. - -/** - * objectui#13088 — the pending-drafts bar's sentence is never cut to one line. - * - * On a phone the bar's row is narrower than its sentence. The sentence used to - * be drawn in a `truncate` span (one line, `overflow: hidden`, an ellipsis), - * so at 390 px the zh sentence ended 「用户还看不…」 and the half that says - * users cannot see the change yet was cut. It now wraps onto more lines, - * taking the row's free width, while the publish button keeps its place on - * the bar. - * - * ## What is read here, and what is not - * - * This environment runs no layout and loads no stylesheet, so a reading of - * the sentence's widths or its computed `white-space` would pass whatever the - * markup said. What is read instead is the structure that decides whether the - * sentence can wrap, each reading one the old span fails: - * - * - the sentence element, found by its own `data-testid` (never by a class - * this file asserts about), carries no one-line clamp: no `truncate`, - * `whitespace-nowrap`, `text-nowrap`, `text-ellipsis`, `overflow-hidden`, - * `overflow-x-hidden`, `overflow-clip` or `line-clamp-*`; - * - nothing from the sentence up to the bar carries a class that would hand - * it `white-space: nowrap` by inheritance (`truncate`, `whitespace-nowrap`, - * `text-nowrap`); - * - the publish button sits on the same bar. - * - * The boxes themselves (the sentence's `scrollWidth` against `clientWidth`, - * its line count, the bar, the button and the input) were measured in - * Chromium at 320, 390, 1010 and 1280 px, zh and en, before and after, and are - * recorded on this change's pull request. - */ - -import '@testing-library/jest-dom/vitest'; -import React from 'react'; -import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; -import { cleanup, render, screen, within } from '@testing-library/react'; -import { PendingDraftsBar } from '../PendingDraftsBar.js'; - -vi.mock('../../../providers/MetadataProvider.js', async (importOriginal) => ({ - ...(await importOriginal>()), - useMetadata: () => ({ refresh: vi.fn() }), -})); - -const PKG = 'app.hcpl'; -const DRAFT = { type: 'object', name: 'hcpl_borrowing', label: 'Borrowing', packageId: PKG }; - -beforeEach(() => { - vi.stubGlobal( - 'fetch', - vi.fn(async (input: RequestInfo | URL) => { - const body = String(input).includes('/meta/_drafts') ? { drafts: [DRAFT] } : { success: true }; - return new Response(JSON.stringify(body), { - status: 200, - headers: { 'Content-Type': 'application/json' }, - }); - }), - ); -}); -afterEach(() => { - cleanup(); - vi.unstubAllGlobals(); -}); - -/** Classes that clamp the element they sit on to one line, or clip it. */ -const CLAMPS_ITSELF = new Set([ - 'truncate', - 'whitespace-nowrap', - 'text-nowrap', - 'text-ellipsis', - 'overflow-hidden', - 'overflow-x-hidden', - 'overflow-clip', -]); -/** Classes whose `white-space: nowrap` every descendant inherits. */ -const NOWRAP_INHERITED = new Set(['truncate', 'whitespace-nowrap', 'text-nowrap']); - -function classesOf(el: Element): string[] { - return Array.from(el.classList); -} - -describe('objectui#13088 — the pending-drafts bar shows its whole sentence', () => { - // objectstack#34610 — the bar's action is now Show draft (the screen's one - // Publish is the shell's bar), and it keeps its place the same way. - it('the sentence wraps instead of being clamped to one line, and the action button stays on the bar', async () => { - render( {}} />); - const bar = await screen.findByTestId('pending-drafts-bar', undefined, { timeout: 4000 }); - const sentence = within(bar).getByTestId('pending-drafts-bar-sentence'); - - // The whole sentence is in the element, including its second half. (No - // i18n instance is mounted here, so the inline default is drawn and the - // plural form is not chosen; the packs' `_one` form is not what this pins.) - expect(sentence).toHaveTextContent(/^1 unpublished changes?\. Show the draft to review and publish (it|them)\.$/); - - // No one-line clamp on the sentence itself. - const clamps = classesOf(sentence).filter((c) => CLAMPS_ITSELF.has(c) || /^line-clamp-/.test(c)); - expect(clamps).toEqual([]); - - // Nothing between the sentence and the bar (both included) hands it - // `white-space: nowrap` by inheritance. - const inherited: string[] = []; - for (let el: Element | null = sentence; el; el = el === bar ? null : el.parentElement) { - for (const c of classesOf(el)) if (NOWRAP_INHERITED.has(c)) inherited.push(`${el.tagName.toLowerCase()} ${c}`); - } - expect(inherited).toEqual([]); - - // The action stays on the bar. - expect(within(bar).getByRole('button', { name: 'Show draft' })).toBeInTheDocument(); - }); -}); diff --git a/ui/packages/app-shell/src/console/ai/__tests__/PendingDraftsBar.test.tsx b/ui/packages/app-shell/src/console/ai/__tests__/PendingDraftsBar.test.tsx deleted file mode 100644 index 0bbbd1f74a5..00000000000 --- a/ui/packages/app-shell/src/console/ai/__tests__/PendingDraftsBar.test.tsx +++ /dev/null @@ -1,153 +0,0 @@ -/** - * ObjectUI - * Copyright (c) 2024-present ObjectStack Inc. - * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. - */ - -/** - * objectui#5694 — the standing unpublished-changes line, above the composer - * while the bound package has pending drafts, gone when the count is zero. - * - * objectstack#34610 — the line publishes nothing: the screen's one Publish is - * the shell's bar. The line points to it while the main area shows the draft, - * offers to show the draft otherwise, and shows a receipt when a publish from - * the bar lands. Its count is the app's drafts, the draft bar's scope: its - * package and its ADR-0146 customization pair, off the env-wide `_drafts`. - */ - -import React from 'react'; -import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'; -import { render, waitFor, fireEvent, cleanup, act } from '@testing-library/react'; -import { PendingDraftsBar } from '../PendingDraftsBar.js'; -import { emitMetadataRefresh, emitPublishReceipt } from '../../../assistant/assistantBus.js'; - -let draftRows: Array> = []; - -function json(body: unknown): Response { - return new Response(JSON.stringify(body), { - status: 200, - headers: { 'content-type': 'application/json' }, - }); -} - -beforeEach(() => { - draftRows = []; - vi.stubGlobal( - 'fetch', - vi.fn(async () => json(draftRows)), - ); -}); -afterEach(() => { - cleanup(); - vi.unstubAllGlobals(); -}); - -const q = (c: HTMLElement, id: string) => c.querySelector(`[data-testid="${id}"]`); - -describe('PendingDraftsBar (objectui#5694, objectstack#34610)', () => { - it('renders nothing when the package has no pending drafts, and nothing when unbound', async () => { - const { container, rerender } = render(); - await waitFor(() => - expect(fetch).toHaveBeenCalledWith( - '/api/v1/meta/_drafts', - expect.objectContaining({ credentials: 'include' }), - ), - ); - expect(q(container, 'pending-drafts-bar')).toBeNull(); - rerender(); - expect(q(container, 'pending-drafts-bar')).toBeNull(); - }); - - it("counts the app's drafts: its package and its customization pair, never another app's", async () => { - draftRows = [ - { type: 'object', name: 'task', packageId: 'app.k9qk' }, - { type: 'view', name: 'task.all', packageId: 'app.k9qk.custom' }, - { type: 'object', name: 'note', packageId: 'app.other' }, - { type: 'flow', name: 'loose_flow', packageId: null }, - ]; - const { container } = render(); - await waitFor(() => expect(q(container, 'pending-drafts-bar')).toBeTruthy()); - expect(q(container, 'pending-drafts-bar-sentence')?.textContent).toMatch(/^2 unpublished changes/); - }); - - it('bound to the pair, it counts the same app', async () => { - draftRows = [ - { type: 'object', name: 'task', packageId: 'app.k9qk' }, - { type: 'view', name: 'task.all', packageId: 'app.k9qk.custom' }, - { type: 'object', name: 'note', packageId: 'app.other' }, - ]; - const { container } = render(); - await waitFor(() => expect(q(container, 'pending-drafts-bar')).toBeTruthy()); - expect(q(container, 'pending-drafts-bar-sentence')?.textContent).toMatch(/^2 unpublished changes/); - }); - - it('draws no Publish: while the main area shows the draft it points to the draft bar', async () => { - draftRows = [ - { type: 'dashboard', name: 'task_dashboard', packageId: 'app.k9qk' }, - { type: 'object', name: 'task', packageId: 'app.k9qk' }, - ]; - const onShowDraft = vi.fn(); - const { container } = render( - , - ); - await waitFor(() => expect(q(container, 'pending-drafts-bar')).toBeTruthy()); - const bar = q(container, 'pending-drafts-bar') as HTMLElement; - expect(bar.textContent).toContain('2 unpublished changes. Publish them from the draft bar at the top.'); - expect(bar.querySelector('button')).toBeNull(); - }); - - it('with the main area elsewhere it offers to show the draft, which is not a publish', async () => { - draftRows = [{ type: 'object', name: 'task', packageId: 'app.k9qk' }]; - const onShowDraft = vi.fn(); - const { container } = render(); - await waitFor(() => expect(q(container, 'pending-drafts-show-draft')).toBeTruthy()); - expect(q(container, 'pending-drafts-bar')?.textContent).toContain('Show the draft to review and publish'); - fireEvent.click(q(container, 'pending-drafts-show-draft') as HTMLElement); - expect(onShowDraft).toHaveBeenCalledTimes(1); - expect(fetch).not.toHaveBeenCalledWith(expect.stringContaining('publish-drafts'), expect.anything()); - }); - - it("a publish from the shell's bar becomes the chat's receipt, until drafts are pending again", async () => { - draftRows = [{ type: 'object', name: 'task', packageId: 'app.k9qk' }]; - const { container } = render(); - await waitFor(() => expect(q(container, 'pending-drafts-bar')).toBeTruthy()); - - // The draft bar publishes the package: the drafts go, the receipt lands. - draftRows = []; - act(() => { - emitPublishReceipt({ packageId: 'app.k9qk' }); - emitMetadataRefresh(); - }); - await waitFor(() => expect(q(container, 'publish-receipt')).toBeTruthy()); - expect(q(container, 'pending-drafts-bar')).toBeNull(); - expect(q(container, 'publish-receipt')?.textContent).toContain('Published. Your changes are live.'); - - // The next build drafts again: the line replaces the receipt for good. - draftRows = [{ type: 'field', name: 'task.due', packageId: 'app.k9qk' }]; - act(() => emitMetadataRefresh()); - await waitFor(() => expect(q(container, 'pending-drafts-bar')).toBeTruthy()); - expect(q(container, 'publish-receipt')).toBeNull(); - draftRows = []; - act(() => emitMetadataRefresh()); - await waitFor(() => expect(q(container, 'pending-drafts-bar')).toBeNull()); - expect(q(container, 'publish-receipt')).toBeNull(); - }); - - it("another package's publish is not this conversation's receipt; dismissing hides it", async () => { - const { container } = render(); - await waitFor(() => expect(fetch).toHaveBeenCalled()); - act(() => emitPublishReceipt({ packageId: 'app.other' })); - expect(q(container, 'publish-receipt')).toBeNull(); - // The app's own publish, named by its pair, is this conversation's. - act(() => emitPublishReceipt({ packageId: 'app.k9qk.custom' })); - expect(q(container, 'publish-receipt')).toBeTruthy(); - fireEvent.click(q(container, 'publish-receipt-dismiss') as HTMLElement); - expect(q(container, 'publish-receipt')).toBeNull(); - act(() => emitPublishReceipt({ packageId: null })); - expect(q(container, 'publish-receipt')).toBeTruthy(); - fireEvent.click(q(container, 'publish-receipt-dismiss') as HTMLElement); - expect(q(container, 'publish-receipt')).toBeNull(); - }); -}); diff --git a/ui/packages/app-shell/src/console/ai/__tests__/agentEmptyState.test.ts b/ui/packages/app-shell/src/console/ai/__tests__/agentEmptyState.test.ts new file mode 100644 index 00000000000..4d183b1a8b2 --- /dev/null +++ b/ui/packages/app-shell/src/console/ai/__tests__/agentEmptyState.test.ts @@ -0,0 +1,46 @@ +/** + * ObjectUI + * Copyright (c) 2024-present ObjectStack Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ + +// AiChatPage reads a dropped spreadsheet through `import('@object-ui/plugin-grid')`; load it +// here so collection pays that transform, not a clocked case (check-test-source-alias). +import '@object-ui/plugin-grid'; +import { describe, it, expect } from 'vitest'; + +import { agentEmptyState, buildAgentSuggestions } from '../AiChatPage'; + +// Identity translator: returns the defaultValue. Lets us test the branching +// without the i18n runtime. +const t = (_key: string, opts?: Record): string => (opts?.defaultValue as string) ?? _key; + +describe('agentEmptyState', () => { + it('the ask agent reads as data Q&A', () => { + expect(agentEmptyState(t, 'ask').title).toBe('Ask your data'); + }); + + it('any other agent gets the generic empty state', () => { + expect(agentEmptyState(t, 'build').title).toBe('Start a conversation'); + expect(agentEmptyState(t, 'support_bot').title).toBe('Start a conversation'); + expect(agentEmptyState(t, undefined).title).toBe('Start a conversation'); + }); +}); + +describe('buildAgentSuggestions', () => { + it('the ask agent offers data starters', () => { + expect(buildAgentSuggestions('ask', 'Ask', t).join(' ')).toMatch(/How many users/); + }); + + it('a custom agent named for data offers data starters', () => { + expect(buildAgentSuggestions('sales_data', 'Sales data', t).join(' ')).toMatch(/How many users/); + }); + + it('any other agent gets the generic starters, never app-authoring ones', () => { + const s = buildAgentSuggestions('build', 'Build', t).join(' '); + expect(s).toMatch(/What can you help me with/); + expect(s).not.toMatch(/Build a sales CRM/); + }); +}); diff --git a/ui/packages/app-shell/src/console/ai/__tests__/aiFaces.displayLocale-9909.test.tsx b/ui/packages/app-shell/src/console/ai/__tests__/aiFaces.displayLocale-9909.test.tsx index 0fbefe932f4..e27f04763bd 100644 --- a/ui/packages/app-shell/src/console/ai/__tests__/aiFaces.displayLocale-9909.test.tsx +++ b/ui/packages/app-shell/src/console/ai/__tests__/aiFaces.displayLocale-9909.test.tsx @@ -9,8 +9,7 @@ /** * The AI console's date, time and number faces read the DECLARED session * locale, never the machine's (objectui#9909): a conversation row's - * older-than-a-week date and its absolute-time tooltip, and the build-debug - * drawer's token count. + * older-than-a-week date and its absolute-time tooltip. * * The row's date tail is objectui#3441's shape one directory over: the recent * buckets go through `t('console.ai.daysAgo')`, and the 7-days-and-older bucket @@ -46,7 +45,6 @@ vi.mock('../../../hooks/useConversationList', () => { }); import { ConversationsSidebar } from '../ConversationsSidebar'; -import { BuildDebugDrawer } from '../BuildDebugDrawer'; afterEach(() => { cleanup(); @@ -61,16 +59,6 @@ function session(locale: string, node: React.ReactNode): React.ReactElement { ); } -const REPORT = { - conversationId: 'conv_x', - title: 'Build', - summary: { models: ['m'], userTurns: 3, messages: 36, totalTokens: 242495, llmMs: 82900 }, - reconciliation: { orphaned: [], missing: [], errors: [], liveCount: 0, ok: true }, - verify: { status: 'passed', errors: 0, warnings: 0, userIssues: [], platformNoise: 0 }, - timeline: [], - pendingActions: [], -}; - interface Surface { name: string; read: (locale: string) => Promise; @@ -119,20 +107,6 @@ const SURFACES: Surface[] = [ de: /4\.3\.2020, 15:30:00/, en: /3\/4\/2020, 3:30:00\sPM/, }, - { - name: 'BuildDebugDrawer — token count', - read: async (locale) => { - vi.stubGlobal('fetch', vi.fn(async () => ({ headers: new Headers(), ok: true, status: 200, json: async () => REPORT }))); - render(session(locale, {}} />)); - const line = await screen.findByText(/tok/); - const text = line.textContent ?? ''; - cleanup(); - vi.unstubAllGlobals(); - return text; - }, - de: /242\.495 tok/, - en: /242,495 tok/, - }, ]; describe('AI console faces follow the declared session locale (objectui#9909)', () => { diff --git a/ui/packages/app-shell/src/console/ai/__tests__/artifactStudioPath.test.ts b/ui/packages/app-shell/src/console/ai/__tests__/artifactStudioPath.test.ts deleted file mode 100644 index 40eb45bef25..00000000000 --- a/ui/packages/app-shell/src/console/ai/__tests__/artifactStudioPath.test.ts +++ /dev/null @@ -1,55 +0,0 @@ -// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license. - -import { describe, it, expect } from 'vitest'; -import { artifactStudioPath } from '../artifactStudioPath'; - -/** - * objectui#2623 — every AI-built artifact deep-links to its direct-edit home - * (the Studio pillar where it can be changed by hand, no AI needed). - */ -describe('artifactStudioPath', () => { - const pkg = 'app.rmpe'; - - it("object → the object designer's address (objectstack#36904)", () => { - expect(artifactStudioPath(pkg, { type: 'object', name: 'rmpe_customer' })).toBe( - '/studio/app.rmpe/metadata/object/rmpe_customer', - ); - }); - - it('flow → the flow designer on its metadata address (objectstack#36903)', () => { - expect(artifactStudioPath(pkg, { type: 'flow', name: 'customer_lost_follow_up' })).toBe( - '/studio/app.rmpe/metadata/flow/customer_lost_follow_up', - ); - }); - - // objectstack#36502 — the Interfaces pillar is retired: these open their All-metadata item page. - it('dashboard / page → their All-metadata item page', () => { - expect(artifactStudioPath(pkg, { type: 'dashboard', name: 'home_dashboard' })).toBe( - '/studio/app.rmpe/metadata/dashboard/home_dashboard', - ); - expect(artifactStudioPath(pkg, { type: 'page', name: 'welcome' })).toBe('/studio/app.rmpe/metadata/page/welcome'); - }); - - it('view → its own All-metadata item page, by its qualified name', () => { - expect(artifactStudioPath(pkg, { type: 'view', name: 'rmpe_customer.customer_list' })).toBe( - '/studio/app.rmpe/metadata/view/rmpe_customer.customer_list', - ); - }); - - it('app → its All-metadata item page', () => { - expect(artifactStudioPath(pkg, { type: 'app', name: 'customer_management' })).toBe( - '/studio/app.rmpe/metadata/app/customer_management', - ); - }); - - it('artifacts with no direct-edit home return null (seed / dataset / unknown)', () => { - expect(artifactStudioPath(pkg, { type: 'seed', name: 'rmpe_customer_sample' })).toBeNull(); - expect(artifactStudioPath(pkg, { type: 'dataset', name: 'rmpe_customer_ds' })).toBeNull(); - expect(artifactStudioPath(pkg, { type: 'mystery', name: 'x' })).toBeNull(); - }); - - it('no package id or blank name → null (never a half-built link)', () => { - expect(artifactStudioPath(undefined, { type: 'object', name: 'x' })).toBeNull(); - expect(artifactStudioPath(pkg, { type: 'object', name: ' ' })).toBeNull(); - }); -}); diff --git a/ui/packages/app-shell/src/console/ai/__tests__/buildDoctor.drawerBody-10969.test.tsx b/ui/packages/app-shell/src/console/ai/__tests__/buildDoctor.drawerBody-10969.test.tsx deleted file mode 100644 index 21d376d993e..00000000000 --- a/ui/packages/app-shell/src/console/ai/__tests__/buildDoctor.drawerBody-10969.test.tsx +++ /dev/null @@ -1,147 +0,0 @@ -// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. - -/** - * objectui#10969 — the Build Doctor drawer's body speaks the session's - * language, as objectui#10900 made its title do. - * - * objectui#10900 localized the Build Doctor button, its tooltips and the - * drawer's title (`buildDoctor.locale-10900`); the body under that title — - * the description, the loading and not-found states, the summary line, the - * verdict, and each section's title and hint — stayed English literals under - * zh-CN. They now read `console.ai.buildDoctorDrawer.*`. What the report - * itself carries (tool, artifact and status names, timeline text) is data and - * is asserted verbatim. - * - * Harness: `BuildDebugDrawer.test.tsx`'s report, answered by the drawer's one - * request, rendered under a real `I18nProvider` in zh and en. - */ -import '@testing-library/jest-dom/vitest'; -import { afterEach, describe, expect, it, vi } from 'vitest'; -import { cleanup, render, screen } from '@testing-library/react'; -import { I18nProvider } from '@object-ui/i18n'; -import { BuildDebugDrawer } from '../BuildDebugDrawer'; -import type { BuildDebugReport } from '../buildDebugApi'; - -const REPORT: BuildDebugReport = { - conversationId: 'conv_x', - title: null, - summary: { models: ['openai/gpt-5.4-mini'], userTurns: 3, messages: 36, totalTokens: 242495, llmMs: 82900 }, - reconciliation: { - orphaned: [ - { t: '04:29:43', tool: 'create_metadata', status: 'changes_proposed', artifact: { type: 'flow', name: 'reimbursement_approval_flow' } }, - ], - missing: [ - { tool: 'update_metadata', status: 'applied', artifact: { type: 'object', name: 'expense' } }, - ], - errors: [], - liveCount: 9, - ok: false, - }, - verify: { status: 'failed', errors: 2, warnings: 16, userIssues: [], platformNoise: 18 }, - timeline: [{ t: '04:23:45', kind: 'user', text: 'build an expense flow' }], - pendingActions: [{ tool: 'create_metadata', object: 'flow', status: 'pending', error: null, createdAt: null }], -}; - -const ZH = { defaultLanguage: 'zh', detectBrowserLanguage: false } as const; -const EN = { defaultLanguage: 'en', detectBrowserLanguage: false } as const; - -function answer(report: BuildDebugReport | null) { - vi.stubGlobal( - 'fetch', - vi.fn(async () => - report - ? { headers: new Headers(), ok: true, status: 200, json: async () => report } - : { headers: new Headers(), ok: false, status: 404, json: async () => ({}) }, - ), - ); -} - -function renderDrawer(config: typeof ZH | typeof EN) { - return render( - - {}} /> - , - ); -} - -afterEach(() => { - cleanup(); - vi.unstubAllGlobals(); -}); - -describe('Build Doctor drawer body (objectui#10969)', () => { - it('zh: description, verdict, section titles and hints, and the summary line are Chinese', async () => { - answer(REPORT); - renderDrawer(ZH); - - expect(await screen.findByText(/已提议但从未应用/)).toBeInTheDocument(); - expect(screen.getByText('智能体声称的变更与实际已生效的内容对照。只读诊断。')).toBeInTheDocument(); - expect(screen.getByText('2 处不一致——对话中所说的与实际生效的内容不符。')).toBeInTheDocument(); - expect( - screen.getByText('智能体提议了确认卡片,但之后没有任何一轮应用它——该变更被静默丢弃。'), - ).toBeInTheDocument(); - expect(screen.getByText(/声称已应用但缺失/)).toBeInTheDocument(); - expect(screen.getByText('构建检查(verify_build)')).toBeInTheDocument(); - expect(screen.getByText(/已隐藏 18 条平台 sys_\* 发现/)).toBeInTheDocument(); - expect(screen.getByText('待处理操作')).toBeInTheDocument(); - expect(screen.getByText('时间线(1)')).toBeInTheDocument(); - expect(screen.getByText('(无标题)')).toBeInTheDocument(); - expect(screen.getByText(/3 轮 · 36 条消息/)).toBeInTheDocument(); - - // The report's own data stays verbatim. - expect(screen.getByText(/reimbursement_approval_flow/)).toBeInTheDocument(); - - // None of the English chrome is left. - for (const english of [ - /What the agent claimed/, - /discrepancy/, - /Proposed but never applied/, - /Claimed but missing/, - /Build check/, - /Pending actions/, - /Timeline/, - /untitled/, - /platform sys_\* finding/, - ]) { - expect(screen.queryByText(english)).toBeNull(); - } - }); - - it('zh: the all-live verdict is Chinese', async () => { - answer({ - ...REPORT, - reconciliation: { orphaned: [], missing: [], errors: [], liveCount: 9, ok: true }, - }); - renderDrawer(ZH); - expect(await screen.findByText('全部 9 项尝试的变更均已生效——没有丢失。')).toBeInTheDocument(); - }); - - it('zh: the not-found state is Chinese', async () => { - answer(null); - renderDrawer(ZH); - expect(await screen.findByText('不可用——未找到该对话,或你没有访问权限。')).toBeInTheDocument(); - }); - - it('en: the body is unchanged English', async () => { - answer(REPORT); - renderDrawer(EN); - - expect(await screen.findByText(/Proposed but never applied/)).toBeInTheDocument(); - expect( - screen.getByText('What the agent claimed vs what is actually live. Read-only diagnostic.'), - ).toBeInTheDocument(); - expect(screen.getByText("2 discrepancy(ies) — what the chat said doesn't match what's live.")).toBeInTheDocument(); - expect(screen.getByText('Build check (verify_build)')).toBeInTheDocument(); - expect(screen.getByText(/18 platform sys_\* finding\(s\) hidden/)).toBeInTheDocument(); - expect(screen.getByText('Timeline (1)')).toBeInTheDocument(); - expect(screen.getByText(/3 turn\(s\) · 36 msgs · 242,495 tok · 82\.9s LLM/)).toBeInTheDocument(); - }); - - it('en: the not-found state is unchanged English', async () => { - answer(null); - renderDrawer(EN); - expect( - await screen.findByText('Not available — the conversation was not found or you are not authorized.'), - ).toBeInTheDocument(); - }); -}); diff --git a/ui/packages/app-shell/src/console/ai/__tests__/buildDoctor.locale-10900.test.tsx b/ui/packages/app-shell/src/console/ai/__tests__/buildDoctor.locale-10900.test.tsx deleted file mode 100644 index 1d4f6a1631e..00000000000 --- a/ui/packages/app-shell/src/console/ai/__tests__/buildDoctor.locale-10900.test.tsx +++ /dev/null @@ -1,150 +0,0 @@ -// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. - -/** - * objectui#10900 — the build conversation's Build Doctor button and the drawer - * it opens speak the session's language. - * - * The 2026-09-28 cloud E2E, browser in zh-CN, read `Build Doctor` in the - * build conversation header: the button's accessible name and both of its - * tooltips were English literals beside a Share button that already read - * `console.ai.*` keys, and the drawer's title was a literal too. Rendered here - * as shipped under a real `I18nProvider` — `ChatPane` with `useObjectChat` - * stubbed and `ChatbotEnhanced` reduced to the `headerSlot` ChatPane hands it - * (the way the sibling ChatPane suites stub them), and the drawer with its one - * request answered. - */ -import '@testing-library/jest-dom/vitest'; -import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; -import { cleanup, render, screen } from '@testing-library/react'; -import { MemoryRouter } from 'react-router-dom'; -import React from 'react'; - -vi.mock('@object-ui/plugin-chatbot', async (importOriginal) => { - const actual = await importOriginal>(); - return { - ...actual, - // The header the pane builds reaches the chat surface as `headerSlot`; - // render just that, so the button is in the DOM as ChatPane made it. - ChatbotEnhanced: (props: { headerSlot?: React.ReactNode }) =>
{props.headerSlot}
, - useObjectChat: () => ({ - messages: [], - isLoading: false, - error: undefined, - sendMessage: vi.fn(), - stop: vi.fn(), - reload: vi.fn(), - clear: vi.fn(), - setMessages: vi.fn(), - }), - useAiModels: () => ({ models: [], defaultModelId: undefined }), - }; -}); - -vi.mock('../../../providers/MetadataProvider', async (importOriginal) => { - const actual = await importOriginal>(); - return { ...actual, useMetadata: () => ({ apps: [] }) }; -}); -vi.mock('../../../providers/AdapterProvider', async (importOriginal) => { - const actual = await importOriginal>(); - return { ...actual, useAdapter: () => null }; -}); - -import { I18nProvider } from '@object-ui/i18n'; -import type { AgentDescriptor } from '@object-ui/plugin-chatbot'; -import { ChatPane } from '../AiChatPage'; -import { BuildDebugDrawer } from '../BuildDebugDrawer'; - -window.matchMedia = ((query: string) => ({ - matches: false, - media: query, - onchange: null, - addEventListener: () => {}, - removeEventListener: () => {}, - addListener: () => {}, - removeListener: () => {}, - dispatchEvent: () => false, -})) as unknown as typeof window.matchMedia; - -const ZH = { defaultLanguage: 'zh', detectBrowserLanguage: false } as const; -const EN = { defaultLanguage: 'en', detectBrowserLanguage: false } as const; - -function renderPane(config: typeof ZH | typeof EN, conversationId: string | undefined) { - return render( - - - - - , - ); -} - -function renderDrawer(config: typeof ZH | typeof EN) { - return render( - - {}} /> - , - ); -} - -beforeEach(() => { - window.localStorage.clear(); - // The drawer's one request; an unreadable answer is enough — the title is - // drawn before and regardless of the report. - vi.stubGlobal('fetch', vi.fn(async () => ({ ok: false, status: 404, json: async () => ({}) }))); -}); -afterEach(() => { - cleanup(); - vi.unstubAllGlobals(); -}); - -describe('Build Doctor button (objectui#10900)', () => { - it('zh: accessible name and tooltip are Chinese', () => { - renderPane(ZH, 'conv-1'); - const button = screen.getByTestId('ai-chat-debug-button'); - expect(button).toHaveAttribute('aria-label', '构建诊断'); - expect(button).toHaveAttribute('title', '构建诊断 — 实际生效了哪些变更?'); - }); - - it('zh: the tooltip before the first message is Chinese', () => { - renderPane(ZH, undefined); - expect(screen.getByTestId('ai-chat-debug-button')).toHaveAttribute('title', '请先发送一条消息'); - }); - - it('en: unchanged English', () => { - renderPane(EN, 'conv-1'); - const button = screen.getByTestId('ai-chat-debug-button'); - expect(button).toHaveAttribute('aria-label', 'Build Doctor'); - expect(button).toHaveAttribute('title', 'Build Doctor — what actually landed?'); - }); - - it('en: the tooltip before the first message is unchanged English', () => { - renderPane(EN, undefined); - expect(screen.getByTestId('ai-chat-debug-button')).toHaveAttribute('title', 'Send a message first'); - }); -}); - -describe('Build Doctor drawer title (objectui#10900)', () => { - it('zh: the title is Chinese', () => { - renderDrawer(ZH); - expect(screen.getByRole('dialog', { name: '构建诊断' })).toBeInTheDocument(); - }); - - it('en: the title is unchanged English', () => { - renderDrawer(EN); - expect(screen.getByRole('dialog', { name: 'Build Doctor' })).toBeInTheDocument(); - }); -}); diff --git a/ui/packages/app-shell/src/console/ai/__tests__/changeCardLabels.drafted-32984.test.tsx b/ui/packages/app-shell/src/console/ai/__tests__/changeCardLabels.drafted-32984.test.tsx deleted file mode 100644 index 2f61210468a..00000000000 --- a/ui/packages/app-shell/src/console/ai/__tests__/changeCardLabels.drafted-32984.test.tsx +++ /dev/null @@ -1,316 +0,0 @@ -// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license. - -/** - * objectstack#32984 — the AI chat's change card names objects and fields by - * label even while they are only DRAFTED. Before the first publish the - * published registry does not hold them, so the card read 「b6bl_quote_item · - * line_total」; the names are now read by name from the draft overlay - * (`?preview=draft`) when the published registry does not know them. - */ -import { describe, it, expect, vi } from 'vitest'; -import type { ReactNode } from 'react'; -import { renderHook, waitFor } from '@testing-library/react'; -import { createI18n, I18nProvider } from '@object-ui/i18n'; -import { useChangeCardLabels } from '../changeCardLabels'; - -type Obj = { name: string; label?: string; fields?: Record }; - -/** A published registry already loaded with `objects` (no names-only scope). */ -function published(objects: Obj[]) { - return { objects, getTypeStatus: () => 'ready' as const } as never; -} - -/** A metadata client whose draft-overlay read answers `drafts` by name (the list may grow later). */ -function client(drafts: Obj[]) { - const overlayGet = vi.fn(async (type: string, name: string) => - type === 'object' ? (structuredClone(drafts.find((d) => d.name === name)) ?? null) : null, - ); - const plainGet = vi.fn(async () => null); - const withPreviewDrafts = vi.fn((on: boolean) => (on ? { get: overlayGet } : { get: plainGet })); - return { api: { withPreviewDrafts, get: plainGet } as never, overlayGet, plainGet, withPreviewDrafts }; -} - -const QUOTE_ITEM: Obj = { - name: 'b6bl_quote_item', - label: 'Quote line', - fields: { line_total: { label: 'Subtotal' } }, -}; - -describe('objectstack#32984 — change card labels for drafted objects and fields', () => { - it('names an object and field that exist only as drafts by their draft labels', async () => { - const c = client([QUOTE_ITEM]); - const { result } = renderHook(() => useChangeCardLabels(published([]), c.api, 0)); - - // First ask: the published registry does not know it; the overlay is asked. - result.current.resolveObjectLabel('b6bl_quote_item'); - await waitFor(() => expect(result.current.resolveObjectLabel('b6bl_quote_item')).toBe('Quote line')); - expect(result.current.resolveFieldLabel('b6bl_quote_item', 'line_total')).toBe('Subtotal'); - // Read through the draft overlay, by name, once. - expect(c.withPreviewDrafts).toHaveBeenCalledWith(true); - expect(c.overlayGet).toHaveBeenCalledTimes(1); - expect(c.overlayGet).toHaveBeenCalledWith('object', 'b6bl_quote_item'); - }); - - it('names a field drafted onto a published object by its draft label', async () => { - const c = client([{ ...QUOTE_ITEM, fields: { ...QUOTE_ITEM.fields, discount: { label: 'Discount' } } }]); - const { result } = renderHook(() => useChangeCardLabels(published([QUOTE_ITEM]), c.api, 0)); - - result.current.resolveFieldLabel('b6bl_quote_item', 'discount'); - await waitFor(() => expect(result.current.resolveFieldLabel('b6bl_quote_item', 'discount')).toBe('Discount')); - }); - - it('control: a published object and field answer from the registry while the overlay has not answered', () => { - const c = client([]); - const { result } = renderHook(() => useChangeCardLabels(published([QUOTE_ITEM]), c.api, 0)); - - // objectstack#34629: a published name also asks the overlay (once), but its - // published label answers at once, before that read settles. - expect(result.current.resolveObjectLabel('b6bl_quote_item')).toBe('Quote line'); - expect(result.current.resolveFieldLabel('b6bl_quote_item', 'line_total')).toBe('Subtotal'); - expect(c.overlayGet).toHaveBeenCalledTimes(1); - }); - - it('control: a name neither world knows keeps answering undefined, and is asked once', async () => { - const c = client([]); - const { result } = renderHook(() => useChangeCardLabels(published([]), c.api, 0)); - - expect(result.current.resolveObjectLabel('b6bl_new_thing')).toBeUndefined(); - await waitFor(() => expect(c.overlayGet).toHaveBeenCalledTimes(1)); - await new Promise((r) => setTimeout(r, 0)); - expect(result.current.resolveObjectLabel('b6bl_new_thing')).toBeUndefined(); - expect(result.current.resolveFieldLabel('b6bl_new_thing', 'x')).toBeUndefined(); - expect(c.overlayGet).toHaveBeenCalledTimes(1); - }); -}); - -describe('objectstack#32984 — a change applied later in the same conversation is named by label', () => { - /** Settle the overlay reads in flight. */ - const settle = () => new Promise((r) => setTimeout(r, 0)); - - it('a field added after the first read is named on a later card', async () => { - const drafts: Obj[] = [{ name: 'b6bl_quote_item', label: 'Quote line', fields: { line_total: { label: 'Subtotal' } } }]; - const c = client(drafts); - const { result, rerender } = renderHook(({ rev }) => useChangeCardLabels(published([]), c.api, rev), { - initialProps: { rev: 0 }, - }); - - // The card that proposes the field: the overlay does not hold it yet. - result.current.resolveFieldLabel('b6bl_quote_item', 'discount'); - await waitFor(() => expect(result.current.resolveObjectLabel('b6bl_quote_item')).toBe('Quote line')); - expect(result.current.resolveFieldLabel('b6bl_quote_item', 'discount')).toBeUndefined(); - - // The change applies (the field is drafted), the conversation moves on, and - // a later card names the field. - drafts[0]!.fields!.discount = { label: 'Discount' }; - rerender({ rev: 1 }); - result.current.resolveFieldLabel('b6bl_quote_item', 'discount'); - await waitFor(() => expect(result.current.resolveFieldLabel('b6bl_quote_item', 'discount')).toBe('Discount')); - }); - - it('an object created after the first read is named on a later card', async () => { - const drafts: Obj[] = []; - const c = client(drafts); - const { result, rerender } = renderHook(({ rev }) => useChangeCardLabels(published([]), c.api, rev), { - initialProps: { rev: 0 }, - }); - - result.current.resolveObjectLabel('b6bl_supplier'); - await waitFor(() => expect(c.overlayGet).toHaveBeenCalledTimes(1)); - await settle(); - expect(result.current.resolveObjectLabel('b6bl_supplier')).toBeUndefined(); - - drafts.push({ name: 'b6bl_supplier', label: 'Supplier', fields: { rating: { label: 'Rating' } } }); - rerender({ rev: 1 }); - result.current.resolveObjectLabel('b6bl_supplier'); - await waitFor(() => expect(result.current.resolveObjectLabel('b6bl_supplier')).toBe('Supplier')); - expect(result.current.resolveFieldLabel('b6bl_supplier', 'rating')).toBe('Rating'); - }); - - it('control: a miss is re-asked at most once per conversation revision, never per render', async () => { - const c = client([]); - const { result, rerender } = renderHook(({ rev }) => useChangeCardLabels(published([]), c.api, rev), { - initialProps: { rev: 0 }, - }); - - for (let i = 0; i < 5; i += 1) { - result.current.resolveObjectLabel('b6bl_never'); - result.current.resolveFieldLabel('b6bl_never', 'x'); - await settle(); - rerender({ rev: 0 }); - } - expect(c.overlayGet).toHaveBeenCalledTimes(1); - - rerender({ rev: 1 }); - for (let i = 0; i < 5; i += 1) { - result.current.resolveObjectLabel('b6bl_never'); - await settle(); - rerender({ rev: 1 }); - } - expect(c.overlayGet).toHaveBeenCalledTimes(2); - }); - - it('control: a kept answer that holds the asked field is not re-asked when the revision moves', async () => { - const c = client([QUOTE_ITEM]); - const { result, rerender } = renderHook(({ rev }) => useChangeCardLabels(published([]), c.api, rev), { - initialProps: { rev: 0 }, - }); - result.current.resolveFieldLabel('b6bl_quote_item', 'line_total'); - await waitFor(() => expect(result.current.resolveFieldLabel('b6bl_quote_item', 'line_total')).toBe('Subtotal')); - rerender({ rev: 1 }); - expect(result.current.resolveFieldLabel('b6bl_quote_item', 'line_total')).toBe('Subtotal'); - expect(result.current.resolveObjectLabel('b6bl_quote_item')).toBe('Quote line'); - await settle(); - expect(c.overlayGet).toHaveBeenCalledTimes(1); - }); -}); - -describe('objectstack#34629 — a published object or field the draft relabelled is named by its draft label', () => { - /** Settle the overlay reads in flight. */ - const settle = () => new Promise((r) => setTimeout(r, 0)); - /** The overlay answers the published definition with the draft's changes merged in. */ - const RELABELLED: Obj = { name: 'b6bl_quote_item', label: 'Order line', fields: { line_total: { label: 'Line amount' } } }; - - it('a published object renamed in the draft shows the draft label', async () => { - const c = client([RELABELLED]); - const { result } = renderHook(() => useChangeCardLabels(published([QUOTE_ITEM]), c.api, 0)); - - result.current.resolveObjectLabel('b6bl_quote_item'); - await waitFor(() => expect(result.current.resolveObjectLabel('b6bl_quote_item')).toBe('Order line')); - expect(c.withPreviewDrafts).toHaveBeenCalledWith(true); - expect(c.overlayGet).toHaveBeenCalledWith('object', 'b6bl_quote_item'); - }); - - it('a published field relabelled in the draft shows the draft label', async () => { - const c = client([{ ...QUOTE_ITEM, fields: { line_total: { label: 'Line amount' } } }]); - const { result } = renderHook(() => useChangeCardLabels(published([QUOTE_ITEM]), c.api, 0)); - - result.current.resolveFieldLabel('b6bl_quote_item', 'line_total'); - await waitFor(() => expect(result.current.resolveFieldLabel('b6bl_quote_item', 'line_total')).toBe('Line amount')); - // The object the draft did not rename keeps its published label. - expect(result.current.resolveObjectLabel('b6bl_quote_item')).toBe('Quote line'); - }); - - it('control: a published name with no draft change shows its published label after the overlay answers', async () => { - const c = client([QUOTE_ITEM]); - const { result } = renderHook(() => useChangeCardLabels(published([QUOTE_ITEM]), c.api, 0)); - - result.current.resolveObjectLabel('b6bl_quote_item'); - await waitFor(() => expect(c.overlayGet).toHaveBeenCalledTimes(1)); - await settle(); - expect(result.current.resolveObjectLabel('b6bl_quote_item')).toBe('Quote line'); - expect(result.current.resolveFieldLabel('b6bl_quote_item', 'line_total')).toBe('Subtotal'); - }); - - it('control: a failed overlay read keeps the published label', async () => { - const c = client([]); - c.overlayGet.mockRejectedValueOnce(new Error('offline')); - const { result } = renderHook(() => useChangeCardLabels(published([QUOTE_ITEM]), c.api, 0)); - - result.current.resolveObjectLabel('b6bl_quote_item'); - await waitFor(() => expect(c.overlayGet).toHaveBeenCalledTimes(1)); - await settle(); - expect(result.current.resolveObjectLabel('b6bl_quote_item')).toBe('Quote line'); - }); - - it('a relabel drafted later in the same conversation is named on a later card', async () => { - const drafts: Obj[] = [structuredClone(QUOTE_ITEM)]; - const c = client(drafts); - const { result, rerender } = renderHook(({ rev }) => useChangeCardLabels(published([QUOTE_ITEM]), c.api, rev), { - initialProps: { rev: 0 }, - }); - - // An earlier card names the object before the draft renames it. - result.current.resolveObjectLabel('b6bl_quote_item'); - await waitFor(() => expect(c.overlayGet).toHaveBeenCalledTimes(1)); - await settle(); - expect(result.current.resolveObjectLabel('b6bl_quote_item')).toBe('Quote line'); - - // A later change renames it; the conversation moves on and a later card names it. - drafts[0] = structuredClone(RELABELLED); - rerender({ rev: 1 }); - result.current.resolveObjectLabel('b6bl_quote_item'); - await waitFor(() => expect(result.current.resolveObjectLabel('b6bl_quote_item')).toBe('Order line')); - expect(c.overlayGet).toHaveBeenCalledTimes(2); - }); - - it('the bound: one overlay read per published object per revision, none while one is in flight', async () => { - let release: () => void = () => {}; - const c = client([RELABELLED]); - const gate = new Promise((r) => { - release = r; - }); - c.overlayGet.mockImplementation(async (_type: string, name: string) => { - await gate; - return name === RELABELLED.name ? structuredClone(RELABELLED) : null; - }); - const { result, rerender } = renderHook(({ rev }) => useChangeCardLabels(published([QUOTE_ITEM]), c.api, rev), { - initialProps: { rev: 0 }, - }); - - // In flight: object and field asks across renders and a revision move add no read. - for (let i = 0; i < 5; i += 1) { - result.current.resolveObjectLabel('b6bl_quote_item'); - result.current.resolveFieldLabel('b6bl_quote_item', 'line_total'); - rerender({ rev: i < 3 ? 0 : 1 }); - } - expect(c.overlayGet).toHaveBeenCalledTimes(1); - - release(); - await waitFor(() => expect(result.current.resolveObjectLabel('b6bl_quote_item')).toBe('Order line')); - // Settled at revision 0 was asked; revision 1 is now current and was never asked: one more read, then none. - for (let i = 0; i < 5; i += 1) { - result.current.resolveObjectLabel('b6bl_quote_item'); - result.current.resolveFieldLabel('b6bl_quote_item', 'line_total'); - await settle(); - rerender({ rev: 1 }); - } - expect(c.overlayGet).toHaveBeenCalledTimes(2); - }); - - describe('with a convention translation for the object and field', () => { - function withTranslation({ children }: { children: ReactNode }) { - const instance = createI18n({ defaultLanguage: 'en', detectBrowserLanguage: false }); - instance.addResourceBundle( - 'en', - 'translation', - { - b6bl: { - objects: { b6bl_quote_item: { label: 'Quote line (translated)' } }, - fields: { b6bl_quote_item: { line_total: 'Subtotal (translated)' } }, - }, - }, - true, - true, - ); - return ( - - {children} - - ); - } - - it('a draft relabel wins over the translation written for the published label', async () => { - const c = client([RELABELLED]); - const { result } = renderHook(() => useChangeCardLabels(published([QUOTE_ITEM]), c.api, 0), { - wrapper: withTranslation, - }); - - result.current.resolveObjectLabel('b6bl_quote_item'); - await waitFor(() => expect(result.current.resolveObjectLabel('b6bl_quote_item')).toBe('Order line')); - expect(result.current.resolveFieldLabel('b6bl_quote_item', 'line_total')).toBe('Line amount'); - }); - - it('control: a label the draft did not change still goes through the translation', async () => { - const c = client([QUOTE_ITEM]); - const { result } = renderHook(() => useChangeCardLabels(published([QUOTE_ITEM]), c.api, 0), { - wrapper: withTranslation, - }); - - result.current.resolveObjectLabel('b6bl_quote_item'); - await waitFor(() => expect(c.overlayGet).toHaveBeenCalledTimes(1)); - await settle(); - expect(result.current.resolveObjectLabel('b6bl_quote_item')).toBe('Quote line (translated)'); - expect(result.current.resolveFieldLabel('b6bl_quote_item', 'line_total')).toBe('Subtotal (translated)'); - }); - }); -}); diff --git a/ui/packages/app-shell/src/console/ai/__tests__/deriveBoundPackageId.test.ts b/ui/packages/app-shell/src/console/ai/__tests__/deriveBoundPackageId.test.ts deleted file mode 100644 index 912a0a82170..00000000000 --- a/ui/packages/app-shell/src/console/ai/__tests__/deriveBoundPackageId.test.ts +++ /dev/null @@ -1,83 +0,0 @@ -/** - * ObjectUI - * Copyright (c) 2024-present ObjectStack Inc. - * - * #2458 / ADR-0057 Amendment A1.a — the package a build conversation is bound to, - * shown as the header chip. Explicit `?package=` (Edit-with-AI) wins; otherwise - * the most recent package a build/draft in the thread produced; undefined = the - * not-yet-bound "New app" draft (the magic flow's start state). - */ -import { describe, it, expect } from 'vitest'; -import { deriveBoundPackageId, isPlatformBuiltinApp } from '../AiChatPage'; - -/** - * DERIVED from the function under test, not restated: `deriveBoundPackageId` - * declares a structural minimum (messages whose `toolInvocations` may carry - * `draftReview` / `builderHandoff`), never `ChatMessage`. This file used to - * author a `ChatMessage` and cast to it — and the legacy `ChatMessage` the - * chatbot barrel exports has NO properties in common with that minimum, so the - * cast was asserting between unrelated shapes and the fixtures could have - * drifted arbitrarily far from what the function reads (objectui#4040). - */ -type PackageBearingMessage = Parameters[0][number]; -type PackageBearingTool = NonNullable[number]; - -const msg = (toolInvocations: readonly PackageBearingTool[]): PackageBearingMessage => ({ toolInvocations }); - -describe('deriveBoundPackageId', () => { - it('prefers the explicit editPackageId (Edit-with-AI) over anything in messages', () => { - const messages = [msg([{ draftReview: { packageId: 'app.drafted' } }])]; - expect(deriveBoundPackageId(messages, 'app.edit')).toBe('app.edit'); - }); - - it('unbound while nothing has been built → undefined ("New app")', () => { - expect(deriveBoundPackageId([], undefined)).toBeUndefined(); - // A tool invocation carrying NEITHER binding key — the case this covers. - // (It used to spell that as `{ someOther: true }`; the derivation reads only - // `draftReview` / `builderHandoff`, so the two are the same path.) - expect(deriveBoundPackageId([msg([{}])], undefined)).toBeUndefined(); - }); - - it('binds to the package a build/draft produced (draftReview or builderHandoff)', () => { - expect(deriveBoundPackageId([msg([{ draftReview: { packageId: 'app.inventory' } }])], undefined)).toBe( - 'app.inventory', - ); - expect(deriveBoundPackageId([msg([{ builderHandoff: { packageId: 'app.crm' } }])], undefined)).toBe( - 'app.crm', - ); - }); - - it('takes the MOST RECENT package when several appear (newest wins)', () => { - const messages = [ - msg([{ draftReview: { packageId: 'app.first' } }]), - msg([{ draftReview: { packageId: 'app.second' } }]), - ]; - expect(deriveBoundPackageId(messages, undefined)).toBe('app.second'); - }); -}); - -// #2466 / ADR-0057 A1.b — the switcher lists authorable packages only. Platform -// built-ins reserve the `com.objectstack.*` package namespace; user- and -// AI-built packages use other ids. `_packageId` is the reliable signal on the -// LIST response (managedBy/source aren't grafted onto list items). -describe('isPlatformBuiltinApp', () => { - it('is true for a platform built-in (com.objectstack.setup / account)', () => { - expect(isPlatformBuiltinApp({ _packageId: 'com.objectstack.setup' })).toBe(true); - expect(isPlatformBuiltinApp({ _packageId: 'com.objectstack.account' })).toBe(true); - }); - - it('is false for an AI-built / user package (e.g. app.xadv)', () => { - expect(isPlatformBuiltinApp({ _packageId: 'app.xadv' })).toBe(false); - expect(isPlatformBuiltinApp({ _packageId: 'my.company.crm' })).toBe(false); - }); - - it('is false when there is no package id, or it is not a string', () => { - expect(isPlatformBuiltinApp({})).toBe(false); - expect(isPlatformBuiltinApp({ _packageId: undefined })).toBe(false); - expect(isPlatformBuiltinApp({ _packageId: 123 as unknown as string })).toBe(false); - }); - - it('does not match a package that merely contains the prefix mid-string', () => { - expect(isPlatformBuiltinApp({ _packageId: 'acme.com.objectstack.fake' })).toBe(false); - }); -}); diff --git a/ui/packages/app-shell/src/console/ai/__tests__/editModeEmptyState.test.ts b/ui/packages/app-shell/src/console/ai/__tests__/editModeEmptyState.test.ts deleted file mode 100644 index 3c65543280c..00000000000 --- a/ui/packages/app-shell/src/console/ai/__tests__/editModeEmptyState.test.ts +++ /dev/null @@ -1,93 +0,0 @@ -/** - * ObjectUI - * Copyright (c) 2024-present ObjectStack Inc. - * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. - */ - -import { describe, it, expect } from 'vitest'; - -import { agentEmptyState, buildAgentSuggestions, editAppDataSuggestions } from '../AiChatPage'; - -// Identity translator: returns the defaultValue, interpolating `{{app}}` so the -// edit-mode named title can be asserted. Lets us test the branching without the -// i18n runtime. -const t = (_key: string, opts?: Record): string => { - let s = (opts?.defaultValue as string) ?? _key; - if (opts && 'app' in opts) s = s.replace('{{app}}', String(opts.app)); - return s; -}; - -// ADR-0057 A1.b — the build surface's empty-state guidance and starters switch -// between the magic flow (from-scratch) and edit mode (change an existing app). -describe('agentEmptyState — build magic vs edit mode', () => { - it('magic flow (no editContext): "Build with AI" / describe-an-app', () => { - const s = agentEmptyState(t, 'build', undefined); - expect(s.title).toBe('Build with AI'); - expect(s.description).toMatch(/describe/i); - }); - - it('edit mode with a known app name: title names the app', () => { - const s = agentEmptyState(t, 'build', { appLabel: 'Tiny Todo' }); - expect(s.title).toBe('Editing “Tiny Todo”'); - expect(s.description).toMatch(/change/i); - expect(s.description).toMatch(/in place/i); - }); - - it('edit mode before the app name resolves: generic edit title (never a raw id)', () => { - const s = agentEmptyState(t, 'build', { appLabel: undefined }); - expect(s.title).toBe('Edit this app'); - expect(s.title).not.toMatch(/app\./); // no raw package id like app.xadv - }); - - it('ask agent is unaffected by edit context', () => { - const s = agentEmptyState(t, 'ask', { appLabel: 'Tiny Todo' }); - expect(s.title).toBe('Ask your data'); - }); -}); - -describe('buildAgentSuggestions — magic vs edit starters', () => { - it('build + not editing: from-scratch authoring starters', () => { - const s = buildAgentSuggestions('build', 'Build', t, false); - expect(s.join(' ')).toMatch(/Build a sales CRM/); - expect(s.join(' ')).not.toMatch(/Add a field/); - }); - - it('build + editing: change-oriented starters', () => { - const s = buildAgentSuggestions('build', 'Build', t, true); - expect(s.join(' ')).toMatch(/Add a field/); - expect(s.join(' ')).toMatch(/Add a new object/); - expect(s.join(' ')).not.toMatch(/Build a sales CRM/); - }); - - it('editing defaults to false (magic starters) when omitted', () => { - expect(buildAgentSuggestions('build', 'Build', t)).toEqual( - buildAgentSuggestions('build', 'Build', t, false), - ); - }); - - it('ask agent ignores editing (always data starters)', () => { - const s = buildAgentSuggestions('ask', 'Ask', t, true); - expect(s.join(' ')).toMatch(/How many users/); - expect(s.join(' ')).not.toMatch(/Add a field/); - }); -}); - -// objectstack#34608 — a builder editing an app is offered both halves, as the -// ruling put it:「问数据,或者让我改这个应用」. The empty state names data -// questions as well as changes, and the starters lead with data questions. -describe('edit mode offers data questions as well as changes (objectstack#34608)', () => { - it('the edit-mode description names asking about the data and changing the app', () => { - const s = agentEmptyState(t, 'build', { appLabel: 'Tiny Todo' }); - expect(s.description).toMatch(/ask about this app’s data/i); - expect(s.description).toMatch(/counts, lists and summaries/i); - expect(s.description).toMatch(/change/i); - }); - - it('editAppDataSuggestions are data questions, drawn from the ask agent’s starters', () => { - const s = editAppDataSuggestions(t); - expect(s.length).toBeGreaterThanOrEqual(2); - for (const line of s) expect(line).not.toMatch(/^Add /); - }); -}); diff --git a/ui/packages/app-shell/src/console/ai/__tests__/mainAreaDraft-34610.test.ts b/ui/packages/app-shell/src/console/ai/__tests__/mainAreaDraft-34610.test.ts deleted file mode 100644 index 80853b59226..00000000000 --- a/ui/packages/app-shell/src/console/ai/__tests__/mainAreaDraft-34610.test.ts +++ /dev/null @@ -1,62 +0,0 @@ -/** - * objectstack#34610 — where the console's main area goes for a draft the - * drawer's build produced (`mainAreaDraftMove`). The app shows in the main - * area, in the regime the build is in (ADR-0045): draft mode for changes to a - * published app, the real app for a materialized build. - */ -import { describe, expect, it } from 'vitest'; -import { mainAreaDraftMove } from '../mainAreaDraft'; - -const at = (pathname: string, search = '', hash = '') => ({ pathname, search, hash }); - -describe('mainAreaDraftMove (objectstack#34610)', () => { - it('editing the app the drawer sits beside stays on the page and enters draft mode in place', () => { - expect(mainAreaDraftMove({ segment: 'app.crm' }, at('/apps/crm/account', '?view=all', '#top'), true)).toEqual({ - to: '/apps/crm/account?view=all&preview=draft#top', - replace: true, - leavesPreview: false, - }); - }); - - it('a page already under the target app counts as in place', () => { - expect(mainAreaDraftMove({ segment: 'app.crm' }, at('/apps/app.crm/lead'), false)?.to).toBe( - '/apps/app.crm/lead?preview=draft', - ); - }); - - it('already in draft mode on the page: nothing to navigate (the bus refresh brings the change in)', () => { - expect(mainAreaDraftMove({ segment: 'app.crm' }, at('/apps/crm/account', '?preview=draft'), true)).toBeNull(); - }); - - it('another app (a new build after it binds) opens its landing as a new history entry', () => { - expect(mainAreaDraftMove({ segment: 'app.library' }, at('/home'), false)).toEqual({ - to: '/apps/app.library?preview=draft', - replace: false, - leavesPreview: false, - }); - }); - - it('a materialized build shows the real app, no draft overlay (ADR-0045)', () => { - expect(mainAreaDraftMove({ segment: 'app.library', materialized: true }, at('/home'), false)).toEqual({ - to: '/apps/app.library', - replace: false, - leavesPreview: false, - }); - }); - - it('a materialized build on a previewed page leaves preview, so the sticky keeper must be told', () => { - expect( - mainAreaDraftMove({ segment: 'app.crm', materialized: true }, at('/apps/crm', '?preview=draft'), true), - ).toEqual({ to: '/apps/crm', replace: true, leavesPreview: true }); - }); - - it("a draft card's Preview opens the surface it drafted, even from inside the app", () => { - expect( - mainAreaDraftMove( - { segment: 'app.crm', path: '/apps/app.crm/page/welcome?preview=draft' }, - at('/apps/crm/account'), - true, - ), - ).toEqual({ to: '/apps/app.crm/page/welcome?preview=draft', replace: false, leavesPreview: false }); - }); -}); diff --git a/ui/packages/app-shell/src/console/ai/__tests__/outboundAgentText.test.ts b/ui/packages/app-shell/src/console/ai/__tests__/outboundAgentText.test.ts deleted file mode 100644 index c11ee3f2482..00000000000 --- a/ui/packages/app-shell/src/console/ai/__tests__/outboundAgentText.test.ts +++ /dev/null @@ -1,114 +0,0 @@ -// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. - -/** - * `resolveOutboundAgentText` — the outbound half of the plan/confirm-card - * language gate (objectui#3896). - * - * The invariant: what a card SENDS is a function of the CONVERSATION's language - * and nothing else. There is deliberately no `I18nProvider` in this file — a UI - * locale cannot even be expressed here, which is the strongest statement of the - * rule the unit level can make. `AiChatPage.planCardLocale.test.tsx` then pins - * the same strings through a real provider, where a UI locale exists and - * could still leak in. - * - * Gate conformance is NOT re-asserted here: the cloud `APPROVAL_RE` mirror lives - * in `packages/i18n/src/__tests__/i18n.test.ts` and pins the `zh`/`en` PACK - * values against it. This file pins that the resolver hands back exactly those - * pack values, which is the other link of that chain. - */ - -import { describe, it, expect } from 'vitest'; -import { en, zh } from '@object-ui/i18n/locales'; -import { - OUTBOUND_GATE_TEXT, - resolveOutboundAgentText, - type OutboundAgentTextKey, -} from '../outboundAgentText'; - -const KEYS = [ - 'planApproveMessage', - 'planApproveDefaultsMessage', - 'planAnswerMessage', - 'planExtendExistingMessage', - 'planBuildNewAppMessage', - 'changesConfirmMessage', -] as const; - -function packValue(pack: unknown, key: OutboundAgentTextKey): unknown { - return (pack as { console: { ai: Record } }).console.ai[key]; -} - -describe('outbound agent text follows the conversation, never the UI locale (#3896)', () => { - it('covers every outbound key the i18n guard owns — no silent shrink', () => { - // Mirrors OUTBOUND_KEYS in packages/i18n/src/__tests__/outbound-agent-messages.test.ts. - expect(Object.keys(OUTBOUND_GATE_TEXT).sort()).toEqual([...KEYS].sort()); - }); - - it.each(KEYS)('a Chinese conversation gets the zh pack value for %s', (key) => { - expect(resolveOutboundAgentText(true, key)).toBe(packValue(zh, key)); - }); - - it.each(KEYS)('a non-Chinese conversation gets the en pack value for %s', (key) => { - // The defect: this branch used to be `t(key)`, i.e. the UI pack — so a zh - // console answered a non-Chinese conversation in Chinese. - expect(resolveOutboundAgentText(false, key)).toBe(packValue(en, key)); - }); - - it.each(KEYS)('the two answers for %s really differ, so the pin can discriminate', (key) => { - expect(resolveOutboundAgentText(true, key)).not.toBe(resolveOutboundAgentText(false, key)); - }); - - it.each(KEYS)('the last-resort wording for %s mirrors both packs byte for byte', (key) => { - // If a pack ever stops defining the key the resolver falls back to this - // table, and a Chinese conversation must fall back to CHINESE. Pinning the - // mirror is what keeps that fallback gate-correct instead of stale. - expect(OUTBOUND_GATE_TEXT[key].zh).toBe(packValue(zh, key)); - expect(OUTBOUND_GATE_TEXT[key].en).toBe(packValue(en, key)); - }); - - describe('planAnswerMessage placeholders', () => { - it('fills question and option in a Chinese conversation', () => { - expect( - resolveOutboundAgentText(true, 'planAnswerMessage', { - question: '一个货架还是多个?', - option: '多个', - }), - ).toBe('关于「一个货架还是多个?」,我选择「多个」。'); - }); - - it('fills question and option in an English conversation', () => { - expect( - resolveOutboundAgentText(false, 'planAnswerMessage', { - question: 'One shelf or many?', - option: 'many', - }), - ).toBe('For "One shelf or many?", go with: many.'); - }); - - it('leaves an unsupplied placeholder visible instead of blanking it', () => { - // A silently-dropped placeholder would send a truncated question to the - // agent; leaving the token makes the bug legible in the thread itself. - expect(resolveOutboundAgentText(false, 'planAnswerMessage', { question: 'Q' })).toBe( - 'For "Q", go with: {{option}}.', - ); - }); - - it('does not interpolate when no variables are supplied', () => { - expect(resolveOutboundAgentText(false, 'planAnswerMessage')).toBe(packValue(en, 'planAnswerMessage')); - }); - }); - - describe('planExtendExistingMessage names the app (objectstack#27480)', () => { - it('fills the app in a Chinese conversation', () => { - expect(resolveOutboundAgentText(true, 'planExtendExistingMessage', { app: '图书馆' })).toBe( - '在「图书馆」上继续完善,不另建应用。', - ); - }); - - it('fills the app in an English conversation', () => { - expect(resolveOutboundAgentText(false, 'planExtendExistingMessage', { app: 'Library' })).toBe( - 'Keep improving "Library" instead of building a new app.', - ); - }); - }); -}); diff --git a/ui/packages/app-shell/src/console/ai/artifactStudioPath.ts b/ui/packages/app-shell/src/console/ai/artifactStudioPath.ts deleted file mode 100644 index 6c5c6a834ab..00000000000 --- a/ui/packages/app-shell/src/console/ai/artifactStudioPath.ts +++ /dev/null @@ -1,49 +0,0 @@ -// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license. - -/** - * Map an AI-built artifact to its direct-edit home in Studio — the route where - * that artifact can be changed by hand. Every AI-built artifact gets an edit - * path that needs no AI: the finished build card links each artifact there - * (objectui#2623). - * - * object → Data pillar, the object's schema/records surface - * flow → the flow designer, full-screen on the flow's metadata address - * (objectstack#36903: the Automations pillar retired) - * dashboard, page, view, app - * → the item's page in the "All metadata" area. objectstack#36502: - * the Interfaces pillar that designed them is retired; they are - * designed in the running app, and the item page is where they - * are read and edited as metadata. - * - * Returns null for artifacts with no direct-edit home (seed / dataset / …) — - * callers render those as plain text, not dead links. - */ - -import { studioItemPath } from '../../views/studio-design/studioAddress.js'; - -export interface BuiltArtifact { - type: string; - name: string; -} - -export function artifactStudioPath( - packageId: string | undefined, - artifact: BuiltArtifact, -): string | null { - if (!packageId) return null; - const name = artifact.name?.trim(); - if (!name) return null; - switch (artifact.type) { - // objectstack#36895 — the item's Studio address (`studioItemPath`): its - // pillar today for an object or a flow, its "All metadata" page for the rest. - case 'object': - case 'flow': - case 'dashboard': - case 'page': - case 'view': - case 'app': - return studioItemPath(packageId, artifact.type, name); - default: - return null; - } -} diff --git a/ui/packages/app-shell/src/console/ai/buildDebugApi.ts b/ui/packages/app-shell/src/console/ai/buildDebugApi.ts deleted file mode 100644 index 2e104ba1d50..00000000000 --- a/ui/packages/app-shell/src/console/ai/buildDebugApi.ts +++ /dev/null @@ -1,93 +0,0 @@ -// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. - -/** - * Client for the admin build-debug endpoint - * (`GET /api/v1/ai/conversations/:id/debug`, service-ai). - * - * The chat renders the build agent's self-report, never what actually landed. - * This fetches the server-side reconciliation — agent-CLAIMED vs LIVE - * `sys_metadata` — so a signed-in admin can diagnose a build that "went wrong" - * from the browser, with no DB credentials. Mirrors `fetchConversation`'s - * same-origin cookie auth, and sends the stored bearer token beside it. - */ - -import { createAuthenticatedFetch } from '@object-ui/auth'; - -/** The console's authenticated fetch: the stored bearer token beside the session cookie. */ -function authFetch(input: RequestInfo | URL, init?: RequestInit): Promise { - return createAuthenticatedFetch()(input, init); -} - -export interface ArtifactRef { - type: string; - name: string; -} - -export interface MutationFinding { - t?: string; - tool: string; - status: string; - artifact: ArtifactRef; -} - -export interface VerifyIssue { - severity: string; - code: string; - artifact?: ArtifactRef; -} - -export interface VerifySummary { - status: string; - errors: number; - warnings: number; - userIssues: VerifyIssue[]; - platformNoise: number; -} - -export type TimelineEntry = - | { t: string; kind: 'user'; text: string } - | { t: string; kind: 'assistant-text'; text: string; model?: string; tokens?: number; ms?: number } - | { t: string; kind: 'assistant-calls'; calls: Array<{ name: string; args: unknown }>; model?: string; tokens?: number; ms?: number } - | { t: string; kind: 'tool-result'; name: string; isError: boolean; status?: string; preview: string }; - -export interface BuildDebugReport { - conversationId: string; - title: string | null; - summary: { - models: string[]; - userTurns: number; - messages: number; - totalTokens: number; - llmMs: number; - }; - reconciliation: { - orphaned: MutationFinding[]; - missing: MutationFinding[]; - errors: MutationFinding[]; - liveCount: number; - ok: boolean; - }; - verify: VerifySummary | null; - timeline: TimelineEntry[]; - pendingActions: Array<{ - tool: string | null; - object: string | null; - status: string | null; - error: string | null; - createdAt: string | null; - }>; -} - -/** - * Fetch the reconciliation report for a build conversation. Returns null on - * 403/404 (not authorized / unknown conversation) so the caller can show an - * empty state instead of throwing. - */ -export async function fetchBuildDebug(apiBase: string, conversationId: string): Promise { - const res = await authFetch(`${apiBase}/conversations/${encodeURIComponent(conversationId)}/debug`, { - credentials: 'include', - }); - if (res.status === 404 || res.status === 403 || res.status === 401) return null; - if (!res.ok) throw new Error(`GET build debug failed: ${res.status}`); - return (await res.json()) as BuildDebugReport; -} diff --git a/ui/packages/app-shell/src/console/ai/changeCardLabels.ts b/ui/packages/app-shell/src/console/ai/changeCardLabels.ts deleted file mode 100644 index 1dde472682d..00000000000 --- a/ui/packages/app-shell/src/console/ai/changeCardLabels.ts +++ /dev/null @@ -1,136 +0,0 @@ -// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license. - -/** - * How the AI chat's change card names the objects and fields a change touches - * (objectstack#32984). The producer sends machine names only (「字段 - * b6bl_quote_item · line_total · currency」); these resolvers answer the - * labels. - * - * Two worlds answer: - * - * 1. the published registry the console already reads, by name; - * 2. the draft overlay (`GET /meta/object/:name?preview=draft`), by object - * name. A build conversation edits drafts, so before the first publish - * every object it made lives only there, and a published object or field - * it relabelled carries its new label only there (objectstack#34629). - * - * A name the published registry does not know (an object drafted but never - * published, or a field drafted onto a published object) answers from the - * overlay alone. A name it does know answers its published label until the - * overlay has answered, then the overlay's label: the label the change will - * publish, which is the published one when the draft did not change it. - * - * The overlay's answer is kept per object and asked again once the - * conversation's `revision` has moved since it was asked, when the kept answer - * cannot be trusted: it does not name what a card asks for (no object, or not - * that field), or the name is published, where a later change in the same - * conversation may have relabelled it and the kept answer would show the old - * label without looking stale. At most one read per object per revision, and - * none while one is in flight, so a render never refetches. - * - * A label the draft changed is shown as written, without the convention - * translation lookup: a translation keyed to the object or field was written - * for the published label the draft replaces, and would hide the new one. A - * label the draft did not change goes through that lookup as before. - * - * A name neither world knows (one the change is about to create) answers - * `undefined`, and the card shows the name as given. Only this card reads the - * overlay: what the rest of the console reads stays the published world. - */ -import { useCallback, useRef, useState } from 'react'; -import { useObjectLabel } from '@object-ui/i18n'; -import type { MetadataContextValue } from '@object-ui/react'; -import { readObjectsByName } from '../../hooks/useObjectPresence.js'; - -/** The part of an object definition the change card reads. */ -interface LabelledObject { - name?: string; - label?: string; - fields?: Record; -} - -/** The by-name read of the draft overlay: a client that can turn `?preview=draft` on. */ -export interface DraftOverlayReader { - withPreviewDrafts(previewDrafts: boolean): { get(type: string, name: string): Promise }; -} - -export interface ChangeCardLabels { - resolveObjectLabel: (objectName: string) => string | undefined; - resolveFieldLabel: (objectName: string, fieldName: string) => string | undefined; -} - -const NO_DRAFTS: ReadonlyMap = new Map(); - -export function useChangeCardLabels( - metadata: Pick, - client: DraftOverlayReader, - /** - * Moves when the conversation may have drafted something new (a message - * lands, a turn ends). Compared by identity; any primitive works. - */ - revision: string | number, -): ChangeCardLabels { - const { objectLabel: i18nObjectLabel, fieldLabel: i18nFieldLabel } = useObjectLabel(); - // By name, when a change card asks (objectui#12811): the chat dock mounts - // the pane on an app's object-list open, where reading the whole `objects` - // registry at render would bring it back onto that open. - const findPublished = useCallback( - (objectName: string) => - (readObjectsByName(metadata, [objectName]) as LabelledObject[]).find((o) => o?.name === objectName), - [metadata], - ); - - // The draft overlay's answer per object name: the definition, or `null` when - // the overlay holds none (or the read failed); the revision each name was - // last asked at; and the names whose read is in flight. - const [drafts, setDrafts] = useState(NO_DRAFTS); - const askedAt = useRef(new Map()); - const inFlight = useRef(new Set()); - const findDraft = useCallback( - (objectName: string, fieldName?: string, published = false): LabelledObject | undefined => { - const kept = drafts.get(objectName) ?? undefined; - const answers = - !published && kept !== undefined && (fieldName === undefined || kept.fields?.[fieldName] !== undefined); - const askable = !askedAt.current.has(objectName) || askedAt.current.get(objectName) !== revision; - if (!answers && askable && !inFlight.current.has(objectName)) { - askedAt.current.set(objectName, revision); - inFlight.current.add(objectName); - const settle = (item: LabelledObject | null) => { - inFlight.current.delete(objectName); - setDrafts((prev) => new Map(prev).set(objectName, item)); - }; - client - .withPreviewDrafts(true) - .get('object', objectName) - .then( - (item) => settle(item && typeof item === 'object' ? (item as LabelledObject) : null), - () => settle(null), - ); - } - return kept; - }, - [client, drafts, revision], - ); - - const resolveObjectLabel = useCallback( - (objectName: string) => { - const published = findPublished(objectName); - const drafted = findDraft(objectName, undefined, published !== undefined); - const label = drafted?.label ?? published?.label; - if (published && drafted?.label !== undefined && drafted.label !== published.label) return drafted.label; - return published || drafted ? i18nObjectLabel({ name: objectName, label: label ?? objectName }) : undefined; - }, - [findPublished, findDraft, i18nObjectLabel], - ); - const resolveFieldLabel = useCallback( - (objectName: string, fieldName: string) => { - const published = findPublished(objectName)?.fields?.[fieldName]; - const drafted = findDraft(objectName, fieldName, published !== undefined)?.fields?.[fieldName]; - const label = drafted?.label ?? published?.label; - if (published && drafted?.label !== undefined && drafted.label !== published.label) return drafted.label; - return published || drafted ? i18nFieldLabel(objectName, fieldName, label ?? fieldName) : undefined; - }, - [findPublished, findDraft, i18nFieldLabel], - ); - return { resolveObjectLabel, resolveFieldLabel }; -} diff --git a/ui/packages/app-shell/src/console/ai/mainAreaDraft.ts b/ui/packages/app-shell/src/console/ai/mainAreaDraft.ts deleted file mode 100644 index da8797052b3..00000000000 --- a/ui/packages/app-shell/src/console/ai/mainAreaDraft.ts +++ /dev/null @@ -1,107 +0,0 @@ -/** - * ObjectUI - * Copyright (c) 2024-present ObjectStack Inc. - * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. - */ - -/** - * objectstack#34610 — the app draft is the console's MAIN AREA, not a pane - * beside the chat. - * - * The build runs in the right-side drawer (objectstack#34608). What it drafts - * shows in the page the drawer sits beside: the main shell opens the app with - * `?preview=draft` (ADR-0037's preview mode, `PreviewModeContext`), so the - * draft bar, the app's own navigation and its renderers are the real ones. - * The nested iframe preview (`LiveCanvas`) is gone; ADR-0037's Decision is - * amended under objectstack#34608 (ADR-0057 Amendment A3). - * - * This module answers WHERE the main area goes for a draft, from where it is - * now. It never refreshes anything: the chat host announces each drafted - * artifact on the assistant bus (`emitCanvasInvalidate`), and the main tree, - * already in preview mode, refetches that type in place. - */ - -import { isPreviewSearch, PREVIEW_QUERY_FLAG, PREVIEW_QUERY_VALUE } from '../../preview/PreviewModeContext.js'; - -/** What the main area should show for a draft the chat produced. */ -export interface MainAreaDraftTarget { - /** The app's route segment: its package id (ADR-0048). */ - segment: string; - /** - * A surface under the app to open instead of the page the main area is on - * (`draftPreviewPath`'s answer, `/apps//…?preview=draft`): a draft - * card's Preview names the page, view or object it drafted. - */ - path?: string; - /** - * ADR-0045: the build was materialized — real tables and rows, app unlisted. - * The main area then shows the real app (no draft overlay); the shell's - * unpublished-app bar narrates that state. - */ - materialized?: boolean; -} - -/** The main area's current address, as the router reports it. */ -export interface MainAreaLocation { - pathname: string; - search: string; - hash: string; -} - -/** Where the main area goes for a target: the address, and whether it is a new history entry. */ -export interface MainAreaMove { - to: string; - /** True when only the query changes on the same page (enter draft mode in place). */ - replace: boolean; - /** True when this move leaves draft preview (a materialized build on a previewed page). */ - leavesPreview: boolean; -} - -/** `/apps/` and everything under it. */ -function isUnderApp(pathname: string, segment: string): boolean { - const base = `/apps/${encodeURIComponent(segment)}`; - return pathname === base || pathname.startsWith(`${base}/`); -} - -/** - * Pure: where the main area goes for `target`, from `here`. - * - * - `inPlace` — the page the drawer sits beside is already the target's app - * (the console app whose package the build is bound to). Then the main area - * stays on its page and only enters draft mode: editing an app shows the - * change where the user is looking. - * - Otherwise the target's own surface (`path`), else the app's landing. - * - * Null when the main area already shows it — nothing to navigate, and the - * bus refresh alone brings the change in. - */ -export function mainAreaDraftMove( - target: MainAreaDraftTarget, - here: MainAreaLocation, - inPlace: boolean, -): MainAreaMove | null { - const stay = !target.path && (inPlace || isUnderApp(here.pathname, target.segment)); - let pathname: string; - let params: URLSearchParams; - if (stay) { - pathname = here.pathname; - params = new URLSearchParams(here.search); - } else { - const [path, query = ''] = (target.path ?? `/apps/${encodeURIComponent(target.segment)}`).split('?'); - pathname = path; - params = new URLSearchParams(query); - } - if (target.materialized) params.delete(PREVIEW_QUERY_FLAG); - else params.set(PREVIEW_QUERY_FLAG, PREVIEW_QUERY_VALUE); - const qs = params.toString(); - const search = qs ? `?${qs}` : ''; - const hash = pathname === here.pathname ? here.hash : ''; - if (pathname === here.pathname && search === here.search) return null; - return { - to: `${pathname}${search}${hash}`, - replace: pathname === here.pathname, - leavesPreview: Boolean(target.materialized) && isPreviewSearch(here.search), - }; -} diff --git a/ui/packages/app-shell/src/console/ai/outboundAgentText.ts b/ui/packages/app-shell/src/console/ai/outboundAgentText.ts index c1fb1e5e52f..9ca141e5f0d 100644 --- a/ui/packages/app-shell/src/console/ai/outboundAgentText.ts +++ b/ui/packages/app-shell/src/console/ai/outboundAgentText.ts @@ -1,104 +1,12 @@ // Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. // -// The text a plan / confirm card SENDS to the agent, resolved by the language of -// the CONVERSATION (objectui#3896). -// -// #772 / #2884 established the rule and `AiChatPage` states it at the gate: -// outbound text follows the conversation, rendered labels follow the console UI -// locale. The gate that reads this text lives in cloud -// (`service-ai-studio` `confirm-gate.ts` `APPROVAL_RE`) and recognises exactly -// two languages — Chinese and English. -// -// The rule was only half implemented. Each site was -// `convZh ? '' : t('console.ai.…')`, and `t()` reads the UI -// PACK — so the non-Chinese branch answered with the UI locale, not with -// English. A zh console holding an English conversation therefore sent -// `确认,开始搭建。` into an English thread (the zh pack defines all four keys): -// the gate matched, the build ran, and the agent switched the whole thread to -// Chinese — #2884's symptom with the trigger reversed. `planAnswerMessage` was -// worse: never gated at all, so it sent the UI locale's value in both -// directions. -// -// Hence this module: ONE resolver, every outbound site, both directions, and the UI pack -// is never consulted. Chinese conversation -> the `zh` pack's value; anything -// else -> the `en` pack's value. Reading the built-in packs directly (instead of -// `t(key, { lng })`) is deliberate: an i18next lookup's answer depends on which -// bundles the host app happened to load and on `fallbackLng`, and a zh lookup -// that falls back to `en` is precisely the wrong-language bug above. Here the -// source of each string is declared, not resolved at runtime. - -import { getLoadedBuiltInLocales } from '@object-ui/i18n'; - -/** - * The `console.ai.*` keys that are outbound message TEXT rather than labels. - * Mirrors `OUTBOUND_KEYS` in `packages/i18n/src/__tests__/outbound-agent-messages.test.ts`, - * which owns the invariant that only the `en` and `zh` packs define them. - */ -export type OutboundAgentTextKey = - | 'planApproveMessage' - | 'planApproveDefaultsMessage' - | 'planAnswerMessage' - | 'planExtendExistingMessage' - | 'planBuildNewAppMessage' - | 'changesConfirmMessage'; - -/** - * Last-resort wording per gate language, used only if a pack stops defining the - * key. Same convention as every `t(key, { defaultValue })` call site in this - * repo — the English default is inline there too — except that a Chinese - * conversation falls back to CHINESE. Falling back to English would re-create - * the defect this module exists to fix, silently. - * - * `outboundAgentText.test.ts` pins each entry byte-identical to its pack value, - * so the mirror cannot drift. - */ -const GATE_TEXT: Record> = { - planApproveMessage: { - zh: '确认,开始搭建。', - en: 'Looks good — build it as proposed.', - }, - planApproveDefaultsMessage: { - zh: '确认搭建,未决问题按你的合理假设和默认处理。', - en: 'Build it with your best assumptions; use sensible defaults for the open questions.', - }, - planAnswerMessage: { - zh: '关于「{{question}}」,我选择「{{option}}」。', - en: 'For "{{question}}", go with: {{option}}.', - }, - // objectstack#27480 — the two answers of the extend-or-new question an - // `iterate_or_new` plan asks. Like `planAnswerMessage` they answer a question - // rather than approve a plan. - planExtendExistingMessage: { - zh: '在「{{app}}」上继续完善,不另建应用。', - en: 'Keep improving "{{app}}" instead of building a new app.', - }, - planBuildNewAppMessage: { - zh: '另建一个独立应用。', - en: 'Build a separate, new app.', - }, - changesConfirmMessage: { - zh: '确认修改,应用你刚才提议的改动。', - en: 'Confirm — apply the change you just proposed.', - }, -}; - -/** - * The pack each gate language reads, by the table tag `getLoadedBuiltInLocales()` - * is keyed by (`@objectstack/spec/system` `PLATFORM_LOCALES`): a Chinese - * conversation's gate text is the Simplified pack's. - */ -const PACK_TAG: Readonly> = { zh: 'zh-Hans', en: 'en' }; - -/** Read `console.ai.` out of a locale pack, or `undefined` if absent. */ -function packText(pack: unknown, key: OutboundAgentTextKey): string | undefined { - const ai = (pack as { console?: { ai?: Record } } | undefined)?.console?.ai; - const value = ai?.[key]; - return typeof value === 'string' && value.trim() !== '' ? value : undefined; -} +// The text the console adds to what a user turn SENDS to the agent, resolved +// by the language of the CONVERSATION, never the console UI locale +// (objectui#3896): Chinese conversation -> Chinese, any other -> English. /** - * Fill `{{name}}` placeholders. i18next's default interpolation syntax, applied - * to a pack value we read ourselves; unknown placeholders are left intact so a + * Fill `{{name}}` placeholders, in i18next's default interpolation syntax; + * unknown placeholders are left intact so a * mis-named variable shows up in the sent text instead of silently vanishing. */ function interpolate(template: string, vars?: Readonly>): string { @@ -108,44 +16,10 @@ function interpolate(template: string, vars?: Readonly>): ); } -/** - * Resolve one outbound message in the CONVERSATION's language. - * - * @param conversationIsZh `isConversationZh(...)` for the thread being sent into. - * @param key which outbound message. - * @param vars values for the message's `{{placeholders}}`. - */ -export function resolveOutboundAgentText( - conversationIsZh: boolean, - key: OutboundAgentTextKey, - vars?: Readonly>, -): string { - const lang = conversationIsZh ? 'zh' : 'en'; - // The RESIDENT catalogue for that language, not a static import of it - // (objectui#7479): `en` is always resident, and the Simplified Chinese pack - // (`zh-Hans`, the table tag the snapshot is keyed by) is resident on exactly - // the boots where the console is running in it. When it is not — an - // English console answering a Chinese thread — this falls through to - // {@link GATE_TEXT}, which `outboundAgentText.test.ts` pins BYTE-IDENTICAL to - // the `zh-Hans` pack's outbound values, so the text that leaves is the same - // either way. ⛔ Do not import the pack back to close that branch: it would - // put a second 156 KB catalogue into every page load to re-derive strings - // that are already pinned equal. - const template = - packText(getLoadedBuiltInLocales()[PACK_TAG[lang]], key) ?? GATE_TEXT[key][lang]; - return interpolate(template, vars); -} - -/** Exposed for the pin that keeps {@link GATE_TEXT} and the packs identical. */ -export const OUTBOUND_GATE_TEXT = GATE_TEXT; - // objectstack#34461 — the notes the console adds to a user turn about its // attachments: the spreadsheet brief and the sent / not-read lines for other -// files. They are outbound text like the messages above, so they follow the -// CONVERSATION's language the same way: Chinese conversation -> Chinese, any -// other -> English. They are not gate text and no pack defines them (a pack -// key is published surface, and no reader of a pack needs these), so their -// one source is this table. +// files. No pack defines them (a pack key is published surface, and no reader +// of a pack needs these), so their one source is this table. /** The attachment notes a user turn can carry. */ export type AttachmentNoteKey = diff --git a/ui/packages/app-shell/src/hooks/__tests__/useChatConversation.editKindRoundTrip-10109.test.ts b/ui/packages/app-shell/src/hooks/__tests__/useChatConversation.editKindRoundTrip-10109.test.ts deleted file mode 100644 index 4301767c3b6..00000000000 --- a/ui/packages/app-shell/src/hooks/__tests__/useChatConversation.editKindRoundTrip-10109.test.ts +++ /dev/null @@ -1,94 +0,0 @@ -/** - * ObjectUI - * Copyright (c) 2024-present ObjectStack Inc. - * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. - * - * objectui#10109 — an INCREMENTAL edit stays an edit across a cache-fallback - * reload. - * - * `apply_edit` answers `kind: 'edit'` and may list the `app` artifact it - * re-staged in `drafted[]`; `apply_blueprint` carries no `kind`. The cache - * does not keep the raw tool output: it re-mints a compact envelope from the - * derived `DraftReview` (`sanitizeChatMessagesForCache`). If that envelope - * drops the producer's `kind`, the reloaded edit reads as a whole-app build - * to every reader that answers "whole-app?" — so the round trip must keep it. - * - * Driven through the real production path: live map → cache → JSON (as - * localStorage does) → cache-fallback re-map. The envelope shapes are the - * producer's declaration as recorded on objectui#10109; the producer lives - * outside this repository. - */ -import { describe, it, expect } from 'vitest'; -import { - detectBuiltAppPackage, - uiMessageToChatMessage, -} from '@object-ui/plugin-chatbot'; -import { sanitizeChatMessagesForCache } from '../useChatConversation'; - -const liveMessage = (toolName: string, output: object) => ({ - id: 'a1', - role: 'assistant' as const, - parts: [ - { type: 'text', text: 'Done.' }, - { - type: `tool-${toolName}`, - toolCallId: 'tc-1', - state: 'output-available' as const, - input: {}, - output, - }, - ], -}); - -/** Live render → cache → JSON round trip → the cached tool part's output. */ -function cachedOutputOf(toolName: string, output: object) { - const live = uiMessageToChatMessage(liveMessage(toolName, output)); - const persisted = JSON.parse(JSON.stringify(sanitizeChatMessagesForCache([live]))) as ReturnType< - typeof sanitizeChatMessagesForCache - >; - const part = persisted[0]?.parts.find((p) => p.type === `tool-${toolName}`); - return { persisted, output: part?.output }; -} - -describe('sanitizeChatMessagesForCache — the producer kind survives the cache round trip (objectui#10109)', () => { - const editOutput = { - status: 'drafted', - kind: 'edit', - packageId: 'app.k9', - drafted: [ - { type: 'object', name: 'k9_invoice' }, - { type: 'app', name: 'k9_app' }, - ], - }; - const blueprintOutput = { - status: 'drafted', - packageId: 'app.k9', - drafted: [ - { type: 'app', name: 'k9_app' }, - { type: 'object', name: 'k9_task' }, - ], - }; - - it('a cached apply_edit keeps kind edit, so the reloaded edit is still not a built app', () => { - const { persisted, output } = cachedOutputOf('apply_edit', editOutput); - expect(output).toMatchObject({ status: 'drafted', kind: 'edit', packageId: 'app.k9' }); - expect(detectBuiltAppPackage(output)).toBeUndefined(); - - const reloaded = uiMessageToChatMessage(persisted[0]); - expect(reloaded.toolInvocations?.[0]?.draftReview).toMatchObject({ kind: 'edit', packageId: 'app.k9' }); - expect(reloaded.buildProgress).toBeUndefined(); - }); - - it('control: a cached apply_blueprint build carries no kind and is still a built app', () => { - const { persisted, output } = cachedOutputOf('apply_blueprint', blueprintOutput); - expect(output).toMatchObject({ status: 'drafted', packageId: 'app.k9' }); - expect(output).not.toHaveProperty('kind'); - expect(detectBuiltAppPackage(output)).toBe('app.k9'); - - const reloaded = uiMessageToChatMessage(persisted[0]); - expect(reloaded.toolInvocations?.[0]?.draftReview).not.toHaveProperty('kind'); - expect(reloaded.buildProgress).toMatchObject({ phase: 'done', appLabel: 'K9 App' }); - }); -}); diff --git a/ui/packages/app-shell/src/hooks/__tests__/useChatConversation.replayedBuild-25887.test.ts b/ui/packages/app-shell/src/hooks/__tests__/useChatConversation.replayedBuild-25887.test.ts deleted file mode 100644 index c4a45d7a1dc..00000000000 --- a/ui/packages/app-shell/src/hooks/__tests__/useChatConversation.replayedBuild-25887.test.ts +++ /dev/null @@ -1,147 +0,0 @@ -/** - * ObjectUI - * Copyright (c) 2024-present ObjectStack Inc. - * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. - * - * objectstack#25887 — a whole-app build that ran as a confirm-replay (the - * approved `apply_blueprint`, re-dispatched under a `replay_` tool-call id) - * keeps its build on both reload paths. - * - * - Server history: raw rows → `toUIMessages` → `hydratedMessagesToChatMessages` - * → the tool part `useObjectChat` rebuilds (`output: tool.result`) → the - * live mapper. The stored envelope reaches the mapper whole; the hydrated - * mapper must keep the draft review so the thread binds to the package it - * built, and the live mapper must draw the done tree. - * - Cache fallback: live map → `sanitizeChatMessagesForCache` → JSON → re-map. - * The bare replay verdict carries no `drafted[]`, so caching it alone lost - * the build. - * - * The envelope is the producer's `apply_blueprint` answer as the card - * records it; the producer lives outside this repository. - */ -import { describe, it, expect } from 'vitest'; -import { uiMessageToChatMessage } from '@object-ui/plugin-chatbot'; -import { deriveBoundPackageId, hydratedMessagesToChatMessages } from '../../console/ai/AiChatPage'; -import { - aiMessageRowsToServerMessages, - sanitizeChatMessagesForCache, - toUIMessages, -} from '../useChatConversation'; - -const REPLAY_ID = 'replay_BFpdNra4mJHv5BMH_0'; - -const buildEnvelope = { - status: 'drafted', - packageId: 'app.z1a4', - drafted: [ - { type: 'app', name: 'z1a4_app' }, - { type: 'object', name: 'z1a4_task' }, - ], - autoPublishable: true, - nextSteps: ['Add a due date to tasks'], -}; - -/** The stored conversation: the approval turn, then the replayed build. */ -function serverHistory(envelope: object) { - return toUIMessages( - aiMessageRowsToServerMessages([ - { id: 'u1', role: 'user', content: 'Looks good — build it as proposed.' }, - { - id: 'a1', - role: 'assistant', - content: 'Built.', - tool_calls: JSON.stringify([ - { type: 'tool-call', toolCallId: REPLAY_ID, toolName: 'apply_blueprint', input: {} }, - ]), - }, - { - id: 't1', - role: 'tool', - tool_call_id: REPLAY_ID, - content: JSON.stringify([ - { - type: 'tool-result', - toolCallId: REPLAY_ID, - toolName: 'apply_blueprint', - output: { type: 'json', value: envelope }, - }, - ]), - }, - ]), - ); -} - -/** What `useObjectChat` hands the live mapper for a hydrated invocation. */ -function rerendered(chat: ReturnType[number]) { - return uiMessageToChatMessage({ - id: chat.id, - role: chat.role, - parts: (chat.toolInvocations ?? []).map((tool) => ({ - type: `tool-${tool.toolName}`, - toolCallId: tool.toolCallId, - state: 'output-available', - input: {}, - output: tool.result, - })), - }); -} - -describe('server history — a replayed build reloads as a build (objectstack#25887)', () => { - it('keeps the draft review, binds the thread to the built package, and draws the done tree', () => { - const chat = hydratedMessagesToChatMessages(serverHistory(buildEnvelope)); - const assistant = chat.find((m) => m.role === 'assistant')!; - const tool = assistant.toolInvocations?.[0]; - expect(tool?.replayOutcome).toMatchObject({ kind: 'drafted', packageId: 'app.z1a4' }); - expect(tool?.draftReview).toMatchObject({ packageId: 'app.z1a4', nextSteps: ['Add a due date to tasks'] }); - expect(deriveBoundPackageId(chat, undefined)).toBe('app.z1a4'); - - const live = rerendered(assistant); - expect(live.toolInvocations?.[0]?.draftReview).toMatchObject({ packageId: 'app.z1a4' }); - expect(live.buildProgress).toMatchObject({ phase: 'done', appLabel: 'Z1a4 App' }); - }); - - it('control: a replay whose publish rolled back still lifts no draft review and binds nothing', () => { - const chat = hydratedMessagesToChatMessages( - serverHistory({ ...buildEnvelope, publishFailed: true, publishOutcome: 'rolled_back' }), - ); - const tool = chat.find((m) => m.role === 'assistant')!.toolInvocations?.[0]; - expect(tool?.replayOutcome).toMatchObject({ kind: 'failed' }); - expect(tool?.draftReview).toBeUndefined(); - expect(deriveBoundPackageId(chat, undefined)).toBeUndefined(); - }); -}); - -describe('cache fallback — a replayed build survives the round trip (objectstack#25887)', () => { - const cachedReload = (envelope: object) => { - const live = uiMessageToChatMessage({ - id: 'a1', - role: 'assistant', - parts: [ - { type: 'text', text: 'Built.' }, - { type: 'tool-apply_blueprint', toolCallId: REPLAY_ID, state: 'output-available', input: {}, output: envelope }, - ], - }); - const persisted = JSON.parse(JSON.stringify(sanitizeChatMessagesForCache([live]))) as ReturnType< - typeof sanitizeChatMessagesForCache - >; - return uiMessageToChatMessage(persisted[0]); - }; - - it('a drafted whole-app replay caches its draft envelope: verdict, review and tree all come back', () => { - const reloaded = cachedReload(buildEnvelope); - const tool = reloaded.toolInvocations?.[0]; - expect(tool?.replayOutcome).toMatchObject({ kind: 'drafted', packageId: 'app.z1a4' }); - expect(tool?.draftReview).toMatchObject({ packageId: 'app.z1a4', nextSteps: ['Add a due date to tasks'] }); - expect(reloaded.buildProgress).toMatchObject({ phase: 'done', appLabel: 'Z1a4 App' }); - }); - - it('control: a failed replay still caches the bare verdict, so it never comes back as a draft card', () => { - const reloaded = cachedReload({ ...buildEnvelope, publishFailed: true, publishOutcome: 'rolled_back' }); - const tool = reloaded.toolInvocations?.[0]; - expect(tool?.replayOutcome).toMatchObject({ kind: 'failed', outcome: 'rolled_back' }); - expect(tool?.draftReview).toBeUndefined(); - expect(reloaded.buildProgress).toBeUndefined(); - }); -}); diff --git a/ui/packages/app-shell/src/hooks/__tests__/useChatConversation.test.tsx b/ui/packages/app-shell/src/hooks/__tests__/useChatConversation.test.tsx index 64cc7a60f59..f85bc441b31 100644 --- a/ui/packages/app-shell/src/hooks/__tests__/useChatConversation.test.tsx +++ b/ui/packages/app-shell/src/hooks/__tests__/useChatConversation.test.tsx @@ -6,11 +6,14 @@ * LICENSE file in the root directory of this source tree. */ +// AiChatPage reads a dropped spreadsheet through `import('@object-ui/plugin-grid')`; load it +// here so collection pays that transform, not a clocked case (check-test-source-alias). +import '@object-ui/plugin-grid'; import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest'; import { renderHook, waitFor, act } from '@testing-library/react'; -// The chat surface derives the draft/plan affordance cards from the tool result -// via these mappers — round-tripping our cache through them is the real -// production path (live render → cache → cache-fallback reload). +// The chat surface derives the affordance cards from the tool result via +// these mappers — round-tripping our cache through them is the real production +// path (live render → cache → cache-fallback reload). import { uiMessageToChatMessage, type AnswerSource } from '@object-ui/plugin-chatbot'; // objectui#9232 — the cache round trip is only proven by driving the affordance // it exists to restore, so the test mounts the real HITL hook over the restored @@ -19,7 +22,6 @@ import { uiMessageToChatMessage, type AnswerSource } from '@object-ui/plugin-cha // `initialMessages` from `useChatConversation`). import { useHitlInChat, - detectDraftResult, detectPendingApproval, } from '@object-ui/plugin-chatbot'; import { hydratedMessagesToChatMessages } from '../../console/ai/AiChatPage'; @@ -430,132 +432,9 @@ describe('useChatConversation — resumeMode "fresh" + startNew (the floating as }); }); -// Regression: a cache-fallback reload (server returns no/partial messages → -// `readMessageCache`) must keep the draft/plan affordance cards, not just the -// bare tool header. `sanitizeChatMessagesForCache` used to drop the tool -// `output`, so `mapMessages.detect*` returned undefined for cache-restored -// messages and the "Review N changes / Publish" card, the ADR-0038 verification -// chip, and the "Proposed plan" card silently vanished. -describe('sanitizeChatMessagesForCache — affordance cards survive a cache round-trip', () => { - // The raw tool outputs exactly as the build/propose tools return them. - const draftedOutput = { - status: 'drafted', - drafted: [ - { type: 'app', name: 'tracker_app' }, - { type: 'object', name: 'task' }, - ], - summary: 'Built Tracker', - packageId: 'pkg_1', - autoPublishable: true, - failed: [{ type: 'view', name: 'broken' }], - materialized: true, - verification: { errors: 0, warnings: 1 }, - issues: [{ severity: 'warning', code: 'lint_x', message: 'Consider X', fix: 'do Y' }], - nextSteps: ['Replace the sample data', 'Publish from the status panel'], - }; - const proposedOutput = { - status: 'blueprint_proposed', - summary: 'A lightweight tracker', - counts: { objects: 2, views: 3, dashboards: 1, seedData: 2 }, - questions: ['Track interviews separately?'], - targetApp: 'recruiting', - blueprint: { - assumptions: ['One pipeline for all roles'], - objects: [ - { name: 'candidate', label: 'Candidate', fields: [{ name: 'full_name' }, { name: 'stage' }] }, - { name: 'job', fields: [{ name: 'title' }] }, - ], - }, - }; - - // An assistant message carrying both an apply_blueprint (drafted) and a - // propose_blueprint (blueprint_proposed) tool output, as the live stream - // produces it. - const liveUiMessage = { - id: 'a1', - role: 'assistant' as const, - parts: [ - { type: 'text', text: 'Done.' }, - { - type: 'tool-apply_blueprint', - toolCallId: 'tc-draft', - state: 'output-available' as const, - input: {}, - output: draftedOutput, - }, - { - type: 'tool-propose_blueprint', - toolCallId: 'tc-plan', - state: 'output-available' as const, - input: {}, - output: proposedOutput, - }, - ], - }; - - it('preserves draftReview + proposedPlan through sanitize → localStorage → re-map', () => { - // 1. Live render derives the cards from the raw tool output (baseline). - const live = uiMessageToChatMessage(liveUiMessage); - expect(live.toolInvocations?.[0]?.draftReview?.items).toEqual(draftedOutput.drafted); - // objectui#12724 — the live plan lifts each field's name for the card's - // field chips; the cache copy below keeps only the count, and the card - // degrades to the object chips there. - expect(live.toolInvocations?.[1]?.proposedPlan?.objects).toEqual([ - { - name: 'candidate', - label: 'Candidate', - fieldCount: 2, - fields: [{ name: 'full_name' }, { name: 'stage' }], - }, - { name: 'job', fieldCount: 1, fields: [{ name: 'title' }] }, - ]); - - // 2. Cache it, then round-trip through JSON exactly like localStorage does. - const cached = sanitizeChatMessagesForCache([live]); - const persisted = JSON.parse(JSON.stringify(cached)) as typeof cached; - - // The cached tool parts keep a compact `output` (no full blueprint). - const draftPart = persisted[0]?.parts.find((p) => p.type === 'tool-apply_blueprint'); - const planPart = persisted[0]?.parts.find((p) => p.type === 'tool-propose_blueprint'); - expect(draftPart?.output).toMatchObject({ status: 'drafted' }); - expect(planPart?.output).toMatchObject({ status: 'blueprint_proposed' }); - // Leanness: the field definitions are dropped, only the count is kept. - expect(JSON.stringify(planPart?.output)).not.toContain('full_name'); - - // 3. Cache-fallback reload re-derives the cards from the cached output. - const reloaded = uiMessageToChatMessage(persisted[0]); - - const draftReview = reloaded.toolInvocations?.[0]?.draftReview; - expect(draftReview).toBeDefined(); - expect(draftReview?.items).toEqual(draftedOutput.drafted); - expect(draftReview?.summary).toBe('Built Tracker'); - expect(draftReview?.packageId).toBe('pkg_1'); - expect(draftReview?.autoPublishable).toBe(true); - expect(draftReview?.materialized).toBe(true); - expect(draftReview?.failedCount).toBe(1); - expect(draftReview?.verification).toEqual({ errors: 0, warnings: 1 }); - expect(draftReview?.issues).toEqual([ - { severity: 'warning', code: 'lint_x', message: 'Consider X', fix: 'do Y' }, - ]); - expect(draftReview?.nextSteps).toEqual([ - 'Replace the sample data', - 'Publish from the status panel', - ]); - - const proposedPlan = reloaded.toolInvocations?.[1]?.proposedPlan; - expect(proposedPlan).toBeDefined(); - expect(proposedPlan?.objects).toEqual([ - { name: 'candidate', label: 'Candidate', fieldCount: 2 }, - { name: 'job', fieldCount: 1 }, - ]); - expect(proposedPlan?.counts).toEqual({ objects: 2, views: 3, dashboards: 1, seedData: 2 }); - expect(proposedPlan?.questions).toEqual(['Track interviews separately?']); - expect(proposedPlan?.assumptions).toEqual(['One pipeline for all roles']); - expect(proposedPlan?.summary).toBe('A lightweight tracker'); - expect(proposedPlan?.targetApp).toBe('recruiting'); - }); - - it('does not add an output to plain (non-draft/plan) tool invocations', () => { +// A tool with nothing to restore gets no cached `output` at all. +describe('sanitizeChatMessagesForCache — plain tool invocations', () => { + it('does not add an output to a plain tool invocation', () => { const cached = sanitizeChatMessagesForCache([ { id: 'a1', @@ -571,8 +450,8 @@ describe('sanitizeChatMessagesForCache — affordance cards survive a cache roun }); // objectstack#31868 — the data tools' `source` block ("How this was -// computed") must survive a cache-fallback reload like the affordance cards -// above. It rides inside the cached `output`, beside any envelope, so a turn +// computed") must survive a cache-fallback reload, like a pending approval +// below. It rides inside the cached `output`, beside any envelope, so a turn // that also waits on an approval keeps both. describe('sanitizeChatMessagesForCache — the answer source survives a cache round-trip (objectstack#31868)', () => { const answerSource: AnswerSource = { @@ -658,7 +537,7 @@ describe('toUIMessages — remaps the ModelMessage tool-call part type', () => { id: 'a1', role: 'assistant', content: [ - { type: 'tool-call', toolCallId: 'tc1', toolName: 'apply_blueprint', input: { goal: 'tracker' } }, + { type: 'tool-call', toolCallId: 'tc1', toolName: 'aggregate_data', input: { object: 'task' } }, ], }, { @@ -667,25 +546,21 @@ describe('toUIMessages — remaps the ModelMessage tool-call part type', () => { { type: 'tool-result', toolCallId: 'tc1', - output: { status: 'drafted', drafted: [{ type: 'app', name: 'tracker_app' }], summary: 'Built' }, + output: { value: 3, summary: 'Counted' }, }, ], }, ]); const part = ui[0]?.parts[0]; - expect(part?.type).toBe('tool-apply_blueprint'); - expect(part?.output).toEqual({ - status: 'drafted', - drafted: [{ type: 'app', name: 'tracker_app' }], - summary: 'Built', - }); + expect(part?.type).toBe('tool-aggregate_data'); + expect(part?.output).toEqual({ value: 3, summary: 'Counted' }); - // Through the mapper the tool reads as the real tool, not "call", and its - // draft card survives because the result merged onto the remapped part. + // Through the mapper the tool reads as the real tool, not "call", and the + // result merged onto the remapped part. const cm = uiMessageToChatMessage(ui[0]); - expect(cm.toolInvocations?.[0]?.toolName).toBe('apply_blueprint'); - expect(cm.toolInvocations?.[0]?.draftReview?.items).toEqual([{ type: 'app', name: 'tracker_app' }]); + expect(cm.toolInvocations?.[0]?.toolName).toBe('aggregate_data'); + expect(cm.toolInvocations?.[0]?.state).toBe('output-available'); }); it('leaves a tool-call without a toolName untouched (no false remap)', () => { @@ -1552,8 +1427,8 @@ describe('sanitizeChatMessagesForCache — a pending approval survives the cache status: 'pending_approval', pendingActionId: PENDING_ACTION_ID, }); - // Leanness, same bargain the draft/plan inverses strike: the operator-facing - // prose and the proposed arguments are NOT re-serialized into the cache. + // Leanness: the operator-facing prose and the proposed arguments are NOT + // re-serialized into the cache. expect(JSON.stringify(toolPart?.output)).not.toContain('Q3 rollout'); expect(JSON.stringify(toolPart?.output)).not.toContain('task_77'); // The state that makes the card render survived the rebuild all along. @@ -1624,90 +1499,12 @@ describe('sanitizeChatMessagesForCache — a pending approval survives the cache expect('approval' in (toolPart as object)).toBe(false); }); - // ── The both-at-once turn ──────────────────────────────────────────────── - // - // objectui#9232 first shipped with the pending arm FIRST in the chain, on the - // argument that the arms were "disjoint by construction, so the order is - // unobservable". That argument was wrong, and a pre-existing pin - // (`AiChatPage.runtimeMessageSeam.test.tsx`) caught it: the detectors are - // disjoint over one RESULT, but `draftReview` and `pendingActionId` are - // independent KEYS on an invocation and a turn can carry both. Pending-first - // therefore stopped the draft envelope reaching the cache for such a turn — - // the exact "Review N changes / Publish" loss the other arms exist to - // prevent. The tests below pin both halves of the answer. - describe('a turn carrying BOTH a draft envelope and a pending approval', () => { - const both = [ - { - id: 'a1', - role: 'assistant' as const, - content: 'Staged the changes; deleting the old object needs your approval.', - toolInvocations: [ - { - toolCallId: 'tc-approve', - toolName: 'apply_blueprint', - state: 'approval-requested', - pendingActionId: PENDING_ACTION_ID, - draftReview: { items: [{ type: 'object', name: 'lead' }], packageId: 'app.crm' }, - }, - ], - }, - ]; - - it('keeps BOTH: the draft card renders and Approve reaches the pending action', async () => { - const persisted = throughLocalStorage(sanitizeChatMessagesForCache(both)); - - // `output` is the DRAFT envelope — the richer affordance keeps the one - // slot it can ride in, exactly as before objectui#9232. - const toolPart = persisted[0]?.parts.find((p) => p.type === 'tool-apply_blueprint'); - expect(toolPart?.output).toMatchObject({ - status: 'drafted', - packageId: 'app.crm', - drafted: [{ type: 'object', name: 'lead' }], - }); - // …and the id rides the part key, which is the carrier left over. - expect(toolPart?.pendingActionId).toBe(PENDING_ACTION_ID); - - const restored = hydratedMessagesToChatMessages(persisted); - const tool = restored[0]?.toolInvocations?.[0]; - - // Half one: the draft card comes back. - expect(tool?.draftReview).toEqual({ - items: [{ type: 'object', name: 'lead' }], - packageId: 'app.crm', - }); - // Half two: DRIVEN, not read off the call graph — the same drive the - // pending-only round trip gets. Approve must reach the pending action. - const { urls, decision } = await pressApprove(restored); - expect(urls).toEqual([`${API_BASE}/pending-actions/${PENDING_ACTION_ID}/approve`]); - expect(decision?.state).toBe('success'); - }); - }); - - // The claim the first version of objectui#9232 asserted in prose and got - // wrong by over-reaching. Pinned in the narrow form that is actually true, - // because the arm ORDER now rests on it: over one RESULT the two envelopes - // are mutually exclusive, which is why a pending-only turn (the shape API - // mode can produce) still has `output` free to carry its id. - it('a single tool result cannot yield both a draft and a pending approval', () => { - const drafted = { status: 'drafted', drafted: [{ type: 'object', name: 'lead' }] }; - const pending = { status: 'pending_approval', pendingActionId: PENDING_ACTION_ID }; - - // Lit controls first: each detector really does fire on its own envelope, - // so the two zeros below are readings and not two dead detectors. - expect(detectDraftResult(drafted)).toBeDefined(); - expect(detectPendingApproval(pending)).toBeDefined(); - - expect(detectPendingApproval(drafted)).toBeUndefined(); - expect(detectDraftResult(pending)).toBeUndefined(); - }); - // ── Stale entries: the decision is READ-SIDE TOLERANCE, not a version bump ── // // Entries written by the OLD code are one format behind. They are kept and // read, because (1) nothing can break on them — both readers of the new keys // answer "absent" rather than throwing; (2) a `:v2` key or a discard would - // blank the transcript, the draft card and the plan card that the old writer - // DID keep, on the one path that renders when the server has nothing; and + // blank the transcript the old writer DID keep, on the one path that renders when the server has nothing; and // (3) they self-heal on the next server-backed load, which rewrites the cache // through the new writer. See the block comment on `readMessageCache`. describe('an entry written by the OLD cache shape', () => { diff --git a/ui/packages/app-shell/src/hooks/useChatConversation.ts b/ui/packages/app-shell/src/hooks/useChatConversation.ts index 15f033132fe..8e5fc93b29a 100644 --- a/ui/packages/app-shell/src/hooks/useChatConversation.ts +++ b/ui/packages/app-shell/src/hooks/useChatConversation.ts @@ -177,67 +177,11 @@ export interface UseChatConversationReturn { rekeyScope: (newScope: string) => void; } -/** - * The subset of plugin-chatbot's `DraftReview` (mapMessages.ts) that the chat's - * draft/publish + ADR-0038 verification cards are derived from. Mirrored here — - * rather than imported — to keep this low-level hook free of a `@object-ui/ - * plugin-chatbot` dependency; the round-trip test in - * `useChatConversation.test.tsx` runs these through the REAL detectors, so any - * incompatible drift fails CI. - */ -interface CachedDraftReview { - items: Array<{ type: string; name: string }>; - summary?: string; - packageId?: string; - autoPublishable?: boolean; - failedCount?: number; - materialized?: boolean; - verification?: { errors: number; warnings: number }; - issues?: Array<{ severity: 'error' | 'warning'; code: string; message: string; fix?: string }>; - nextSteps?: string[]; - /** - * objectui#10109 — the producer's incremental-edit marker (`apply_edit` - * answers `kind: 'edit'`). Kept through the cache because an edit's `items` - * can include the `app` it re-staged: without it a cache-fallback reload - * reads the edit as a whole-app build. - */ - kind?: 'edit'; -} - -/** Mirrors the subset of plugin-chatbot's `ProposedPlan` the "Proposed plan" card needs. */ -interface CachedProposedPlan { - summary?: string; - objects: Array<{ name: string; label?: string; fieldCount: number }>; - counts: { objects: number; views: number; dashboards: number; seedData: number }; - questions: string[]; - assumptions: string[]; - targetApp?: string; - /** - * objectstack#27480 — the extend-or-new question a `decision: 'iterate_or_new'` - * plan asks. Kept through the cache because without it a cache-fallback - * reload turns the question back into a plan with a "Build it" button. - */ - iterateOrNew?: { app?: { name: string; label?: string } }; -} - interface CacheableChatToolInvocation { toolCallId: string; toolName: string; state?: string; errorText?: string; - /** - * The detect-relevant shapes the live render already derived from the tool - * result (`uiMessageToChatMessage`). Present on assistant tool invocations - * that staged a draft (`apply_blueprint` …) or proposed a plan - * (`propose_blueprint`). We re-serialize these into a COMPACT tool `output` - * so the cards survive a cache-fallback reload — see - * `sanitizeChatMessagesForCache`. - */ - draftReview?: CachedDraftReview; - proposedPlan?: CachedProposedPlan; - /** objectui#5695 — the confirm-replay verdict, so the 确认修改 card's terminal - * state (已生效 / 已暂存为草稿 / 未生效) survives a cache-fallback reload. */ - replayOutcome?: { kind: 'published' | 'drafted' | 'failed'; outcome?: string; error?: string; packageId?: string; dispatchError?: boolean }; /** * objectui#9232 — the two halves of an ACTIONABLE approval, mirroring * objectui#8442 on the way IN to the cache. They travel differently and that @@ -278,94 +222,9 @@ interface CacheableChatMessage { recordCitations?: StoredAnswerData['recordCitations']; } -/** - * Rebuild the MINIMAL `{ status:'drafted', … }` envelope that - * `mapMessages.detectDraftResult` re-parses, from the already-derived - * `DraftReview`. Inverse of the detector: we keep only the fields it reads, so - * the draft "Review N changes / Publish" card and the ADR-0038 verification - * chip survive without re-storing the (potentially large) blueprint JSON. - * `failed` is materialized to the right length because the detector counts - * `failed.length`. - */ -function draftReviewToCachedResult(dr: CachedDraftReview): Record { - return { - status: 'drafted', - drafted: dr.items, - ...(dr.summary ? { summary: dr.summary } : {}), - ...(dr.packageId ? { packageId: dr.packageId } : {}), - ...(dr.autoPublishable ? { autoPublishable: true } : {}), - ...(dr.failedCount ? { failed: Array.from({ length: dr.failedCount }, () => null) } : {}), - ...(dr.materialized ? { materialized: true } : {}), - ...(dr.verification ? { verification: dr.verification } : {}), - ...(dr.issues && dr.issues.length ? { issues: dr.issues } : {}), - ...(dr.nextSteps && dr.nextSteps.length ? { nextSteps: dr.nextSteps } : {}), - ...(dr.kind === 'edit' ? { kind: 'edit' } : {}), - }; -} - -/** - * Rebuild the MINIMAL `{ status:'blueprint_proposed', … }` envelope that - * `mapMessages.detectProposedPlan` re-parses, from the already-derived - * `ProposedPlan`. Object `fields` are materialized to the right length because - * the detector reads `fields.length` as the per-object field count — the field - * definitions themselves are dropped (the lean win). - */ -function proposedPlanToCachedResult(pp: CachedProposedPlan): Record { - return { - status: 'blueprint_proposed', - ...(pp.summary ? { summary: pp.summary } : {}), - counts: pp.counts, - questions: pp.questions, - ...(pp.targetApp ? { targetApp: pp.targetApp } : {}), - // objectstack#27480 — the two keys `detectProposedPlan` reads the question from. - ...(pp.iterateOrNew - ? { - decision: 'iterate_or_new', - ...(pp.iterateOrNew.app ? { existingAppOverlap: pp.iterateOrNew.app } : {}), - } - : {}), - blueprint: { - objects: pp.objects.map((o) => ({ - name: o.name, - ...(o.label ? { label: o.label } : {}), - fields: Array.from({ length: o.fieldCount }, () => null), - })), - assumptions: pp.assumptions, - }, - }; -} - -/** - * Rebuild the MINIMAL replay envelope `mapMessages.detectReplayOutcome` - * re-parses (objectui#5695). The detector keys off the persisted `replay_*` - * toolCallId plus these fields; `detectDraftResult` stays quiet over the - * drafted shapes because they carry no `drafted` items — so a rolled-back - * publish can never rehydrate from cache as a live draft card. - */ -function replayOutcomeToCachedResult( - ro: NonNullable, -): Record { - if (ro.kind === 'published') return { status: 'published' }; - // A dispatch error round-trips as the bare `{error}` shape it was detected - // from, so re-detection keeps its provisional (supersedable) semantics. - if (ro.kind === 'failed' && ro.dispatchError) return { error: ro.error ?? 'replay dispatch failed' }; - return { - status: 'drafted', - ...(ro.packageId ? { packageId: ro.packageId } : {}), - ...(ro.kind === 'failed' - ? { - publishFailed: true, - ...(ro.outcome ? { publishOutcome: ro.outcome } : {}), - ...(ro.error ? { publishError: ro.error } : {}), - } - : {}), - }; -} - /** * Rebuild the MINIMAL HITL envelope `mapMessages.detectPendingApproval` - * re-parses (objectui#9232). Inverse of that detector, exactly as - * `draftReviewToCachedResult` is the inverse of `detectDraftResult`. + * re-parses (objectui#9232). Inverse of that detector. * * This exists because the id travels asymmetrically. The AI SDK `approval` * envelope is a persisted PART key, so the cache can write it and the @@ -377,9 +236,8 @@ function replayOutcomeToCachedResult( * * The two keys the detector reads are the only two written: the framework's * real envelope also carries a human `message` and the proposed arguments, and - * none of that is re-serialized — the same leanness the draft/plan inverses - * take, and the reason a cached thread does not grow a copy of every pending - * action's payload. + * none of that is re-serialized, which is why a cached thread does not grow a + * copy of every pending action's payload. */ function pendingApprovalToCachedResult(pendingActionId: string): Record { return { status: 'pending_approval', pendingActionId }; @@ -454,9 +312,8 @@ export function purgeChatCaches(): void { * undefined for a result that is not one. An old entry restores exactly * as it does today. * 2. A version bump or a discard would throw away everything the old writer - * got RIGHT — the transcript text, the draft "Review N changes / Publish" - * card, the ADR-0038 chip, the proposed plan, the objectui#5695 replay - * verdict — to recover one affordance. This cache is only ever read when + * got RIGHT — the transcript text, the charts, the answer sources — to + * recover one affordance. This cache is only ever read when * the server returned no messages, so the discarded thread is the only * thread the operator would have seen: a strictly worse trade. * 3. Old entries self-heal. The cache is rewritten from `runtimeMessages` on @@ -529,39 +386,17 @@ export function sanitizeChatMessagesForCache( ); if (message.role === 'assistant') { for (const tool of message.toolInvocations ?? []) { - // Re-serialize the draft/plan affordance into a compact tool `output`. - // Without it, a cache-fallback reload (server returns no messages → - // `readMessageCache`) drops the draft "Review N changes / Publish" - // card, the ADR-0038 verification chip, and the "Proposed plan" card, - // because `mapMessages.detect*` read the result `output` that the - // earlier cache shape never kept. `output` (not a custom part field) - // is used because the AI SDK preserves it through `useChat` init, - // exactly as the server-backed tool-result merge relies on. - // - // objectui#9232 — the pending-approval arm, and it is LAST on - // purpose. `state` already survived this rebuild, so a cached - // `approval-requested` came back carrying nothing to decide with: - // the operator got Approve / Reject buttons whose only possible - // outcome was "No pending-action id found for this tool call". That - // is the divergence objectui#8442 closed on the way OUT of server - // history, reopened on the way IN to the cache. + // objectui#9232 — the pending approval is re-minted into a compact + // tool `output`. `state` already survived this rebuild, so without + // it a cached `approval-requested` came back carrying nothing to + // decide with: the operator got Approve / Reject buttons whose only + // possible outcome was "No pending-action id found for this tool + // call". `output` (not a custom part field) is used because the AI + // SDK preserves it through `useChat` init, exactly as the + // server-backed tool-result merge relies on. // - // ⚠️ `output` holds ONE envelope, and an invocation can carry more - // than one affordance at a time — `draftReview` and `pendingActionId` - // are independent KEYS on the invocation, not two readings of one - // result. Putting the pending arm first therefore did not merely - // reorder equals: it stopped the draft envelope reaching the cache - // for any turn carrying both, which is the same loss (the "Review N - // changes / Publish" card on a cache-fallback reload) that the other - // three arms exist to prevent, and which - // `AiChatPage.runtimeMessageSeam.test.tsx` already pinned. So the - // three existing arms keep `output` exactly as before and the - // pending envelope is minted only when none of them claims it. - // - // Losing the id is not the price of that, because the id does NOT - // depend on `output` alone here — it is also written as a part key - // below. The two carriers are not redundant; each reaches where the - // other cannot, and that is the whole design: + // The id is also written as a part key below. The two carriers are + // not redundant; each reaches where the other cannot: // // * `output` is the only carrier that survives API mode's SDK // store, because `useObjectChat`'s `aiInitialMessages` rebuilds @@ -570,31 +405,13 @@ export function sanitizeChatMessagesForCache( // that carries `output` and has no place for a cache-side key — // and drops every other key, after which // `extractToolInvocations` re-derives the id by re-parsing the - // result. A pending-only turn — the only shape API mode can - // actually produce, since `detectDraftResult` and - // `detectPendingApproval` read ONE `parseResultEnvelope(result)` - // and require different `status` values — lands here. - // * the PART KEY is the only carrier left when a richer envelope - // has taken `output`. Local mode keeps it, because + // result. + // * the PART KEY is the carrier local mode keeps, because // `normalizeMessages` passes `toolInvocations` through verbatim, // and `hydratedMessagesToChatMessages` lifts it on the way back. - // - // objectstack#25887 — a replay that still carries a `draftReview` is - // a drafted whole-app build (the live mapper keeps the review for - // that replay alone). Its draft envelope is cached, not the bare - // replay verdict: the verdict has no `drafted[]`, and without them a - // cache-fallback reload draws no result card. Re-detected under the - // same `replay_` id, the draft envelope still reads as a drafted - // replay, so the verdict survives too. - const cachedOutput = tool.replayOutcome && !tool.draftReview - ? replayOutcomeToCachedResult(tool.replayOutcome) - : tool.draftReview - ? draftReviewToCachedResult(tool.draftReview) - : tool.proposedPlan - ? proposedPlanToCachedResult(tool.proposedPlan) - : tool.pendingActionId - ? pendingApprovalToCachedResult(tool.pendingActionId) - : undefined; + const cachedOutput = tool.pendingActionId + ? pendingApprovalToCachedResult(tool.pendingActionId) + : undefined; // objectstack#31868 — the source block is a top-level key of the // data tool's result, so it is written as one into `output`, BESIDE // the envelope above rather than as a rival arm: it is not an @@ -703,10 +520,9 @@ const APPROVAL_STATES = new Set(['approval-requested', 'approval-responded']); * tool-call parts that requested them. The server persists conversations in * ModelMessage format, where a tool CALL (assistant message) and its RESULT (a * separate `tool` row) live in different messages. The chat UI needs the output - * ON the call part so `detectDraftResult` can rebuild the publish/preview - * affordances after a reload — otherwise the result, and the whole `tool` row - * (which the UI never renders directly), is dropped and the build card + publish - * button vanish on refresh. + * ON the call part so the result detectors can rebuild the cards after a + * reload — otherwise the result, and the whole `tool` row (which the UI never + * renders directly), is dropped and the cards vanish on refresh. * * ⚠️ The state rewrite below is deliberately NARROW (objectui#9233). Collapsing * a dangling `input-streaming` / `input-available` into a terminal state is why diff --git a/ui/packages/app-shell/src/layout/ChatDock.tsx b/ui/packages/app-shell/src/layout/ChatDock.tsx index 7e7a69868bf..ff0a30c1a8e 100644 --- a/ui/packages/app-shell/src/layout/ChatDock.tsx +++ b/ui/packages/app-shell/src/layout/ChatDock.tsx @@ -39,7 +39,7 @@ import { SheetHeader, SheetTitle, } from '@object-ui/components'; -import { Bug, History, Maximize2, MessagesSquare, Minimize2, MoreHorizontal, Share2, X } from 'lucide-react'; +import { History, Maximize2, MessagesSquare, Minimize2, MoreHorizontal, Share2, X } from 'lucide-react'; import { formatNumber, useObjectTranslation } from '@object-ui/i18n'; import { useAgents } from '@object-ui/plugin-chatbot/core'; import { resolveApiBase } from '../console/ai/resolveApiBase.js'; @@ -53,7 +53,6 @@ import { readStoredDockFullWindow, writeStoredDockFullWindow, type ChatDockConversationActions, - type ChatDockHandoff, type ChatDockTarget, } from './chatDockTarget.js'; import { @@ -238,20 +237,18 @@ interface ChatDockMenuProps { /** What the body reported for its thread; absent with a `children` body or before the body loads. */ actions: ChatDockConversationActions | undefined; onShare: () => void; - onDebug: () => void; /** The rail and the full window offer filling the window (or going back); the phone sheet does not. */ fill?: { full: boolean; onToggle: () => void }; } /** - * objectstack#35445 — the drawer's 「···」 menu: AI usage, Share, filling the - * window and the Build Doctor, which used to stand as icons across two header - * rows. The usage reading is the one {@link AiUsageIndicator} draws (the same - * hook and the same words); while the pool is running low the trigger carries a - * marker, so the warning is still seen before a send hits the limit. The Build - * Doctor is listed only when the body says so (a user who may build). + * objectstack#35445 — the drawer's 「···」 menu: AI usage, Share and filling + * the window, which used to stand as icons across two header rows. The usage + * reading is the one {@link AiUsageIndicator} draws (the same hook and the + * same words); while the pool is running low the trigger carries a marker, so + * the warning is still seen before a send hits the limit. */ -function ChatDockMenu({ apiBase, actions, onShare, onDebug, fill }: ChatDockMenuProps) { +function ChatDockMenu({ apiBase, actions, onShare, fill }: ChatDockMenuProps) { const { t, language } = useObjectTranslation(); // Same gate as the indicator: no usage read until the catalog lists an agent. const { agents } = useAgents({ apiBase }); @@ -350,41 +347,27 @@ function ChatDockMenu({ apiBase, actions, onShare, onDebug, fill }: ChatDockMenu {fillLabel} ) : null} - {actions?.showDebug ? ( - - - {t('console.ai.buildDoctor', { defaultValue: 'Build Doctor' })} - - ) : null} ); } /** - * The body's Share / Build Doctor state, lifted to the chrome that offers them - * in its menu (objectstack#35445). The dialogs themselves stay in the body. + * The body's Share state, lifted to the chrome that offers it in its menu + * (objectstack#35445). The dialog itself stays in the body. */ function useDockBodyActions() { const [actions, setActions] = React.useState(undefined); const [shareOpen, setShareOpen] = React.useState(false); - const [debugOpen, setDebugOpen] = React.useState(false); - return { actions, setActions, shareOpen, setShareOpen, debugOpen, setDebugOpen }; + return { actions, setActions, shareOpen, setShareOpen }; } -/** objectstack#34608 — what the drawer shows, and the handoff it seeds (see `chatDockTarget.ts`). */ +/** objectstack#34608 — what the drawer shows (see `chatDockTarget.ts`). */ export interface ChatDockThreadProps { /** Absent → the ambient thread (see {@link ChatDockConversation}). */ target?: ChatDockTarget; - /** Replaces the target in place: a history row, a minted fresh thread, a binding. */ + /** Replaces the target in place: a history row or a minted fresh thread. */ onTargetChange?: (target: ChatDockTarget | undefined) => void; - /** A Builder handoff to seed once as the build thread's first message. */ - handoff?: ChatDockHandoff; } export interface ChatDockPanelProps extends ChatDockThreadProps { @@ -395,9 +378,9 @@ export interface ChatDockPanelProps extends ChatDockThreadProps { /** `app.defaultAgent` for the default body's resolver. Unused with `children`. */ defaultAgent?: string; /** - * objectui#10926 — the current app's owning package, for the default body's - * build-thread binding (see {@link ChatDockConversation}). Unused with - * `children`. + * objectstack#30043 — the current app's owning package, sent by the default + * body as the turn's `context.activeApp` (see {@link ChatDockConversation}). + * Unused with `children`. */ appPackageId?: string; /** @@ -440,7 +423,6 @@ export function ChatDockPanel({ title, target, onTargetChange, - handoff, children, }: ChatDockPanelProps) { const { t } = useObjectTranslation(); @@ -477,7 +459,7 @@ export function ChatDockPanel({ /> )} {/* objectstack#35445 — ONE title row: History, 「···」, Close. Usage, - Share, filling the window and the Build Doctor are in the menu; the + Share and filling the window are in the menu; the close is the drawer's 「×」 in both presentations, and the conversation is kept for the next open. */}
@@ -508,7 +490,6 @@ export function ChatDockPanel({ apiBase={apiBase} actions={children ? undefined : body.actions} onShare={() => body.setShareOpen(true)} - onDebug={() => body.setDebugOpen(true)} fill={{ full, onToggle: () => { @@ -547,15 +528,12 @@ export function ChatDockPanel({ surfaceArtifactLabel={surfaceArtifactLabel} target={target} onTargetChange={onTargetChange} - handoff={handoff} presentation={full ? 'full' : 'rail'} historyOpen={historyOpen} onHistoryOpenChange={setHistoryOpen} onActionsChange={body.setActions} shareOpen={body.shareOpen} onShareOpenChange={body.setShareOpen} - debugOpen={body.debugOpen} - onDebugOpenChange={body.setDebugOpen} /> )} @@ -608,7 +586,6 @@ export function ChatDockMobileSheet({ title, target, onTargetChange, - handoff, children, }: ChatDockMobileSheetProps) { const { t } = useObjectTranslation(); @@ -653,7 +630,6 @@ export function ChatDockMobileSheet({ apiBase={apiBase} actions={children ? undefined : body.actions} onShare={() => body.setShareOpen(true)} - onDebug={() => body.setDebugOpen(true)} />
@@ -673,15 +649,12 @@ export function ChatDockMobileSheet({ surfaceArtifactLabel={surfaceArtifactLabel} target={target} onTargetChange={onTargetChange} - handoff={handoff} presentation="sheet" historyOpen={historyOpen} onHistoryOpenChange={setHistoryOpen} onActionsChange={body.setActions} shareOpen={body.shareOpen} onShareOpenChange={body.setShareOpen} - debugOpen={body.debugOpen} - onDebugOpenChange={body.setDebugOpen} /> )} diff --git a/ui/packages/app-shell/src/layout/ChatDockConversation.tsx b/ui/packages/app-shell/src/layout/ChatDockConversation.tsx index 3c5a15376e0..e1e6cb726db 100644 --- a/ui/packages/app-shell/src/layout/ChatDockConversation.tsx +++ b/ui/packages/app-shell/src/layout/ChatDockConversation.tsx @@ -13,33 +13,23 @@ import * as React from 'react'; import { ShareDialog } from '@object-ui/components'; import { useAgents, - agentHasCapability, agentRouteName, - isAskAgent, isBuiltinAgentName, resolveAgentParam, } from '@object-ui/plugin-chatbot/core'; -import { - ChatPane, - isThreadBoundToPackage, - type PendingFirstMessage, -} from '../console/ai/AiChatPage.js'; +import { ChatPane, type PendingFirstMessage } from '../console/ai/AiChatPage.js'; import { ConversationsSidebar } from '../console/ai/ConversationsSidebar.js'; -import { BuildDebugDrawer } from '../console/ai/BuildDebugDrawer.js'; import { resolvePublicShareBase } from '../console/organizations/resolveHomeUrl.js'; import { useChatConversation, type HydratedUIMessage } from '../hooks/index.js'; import { fetchConversation } from '../hooks/useChatConversation.js'; import { chatConversationScope, chatProductOfAgent } from '../hooks/chatScope.js'; -import { makerConvergedOnBuild, resolveSurfaceAgent } from '../hooks/surfaceAgent.js'; -import { useCanAuthorMetadata } from '../hooks/useCanAuthorMetadata.js'; +import { resolveSurfaceAgent } from '../hooks/surfaceAgent.js'; import { isAiStudioEnabled } from '../runtime-config.js'; import type { ChatSurfaceContext } from './chatSurfaceContext.js'; import { useConversationFocus } from './chatFocus.js'; import { - ambientAppPackage, sameDockTarget, type ChatDockConversationActions, - type ChatDockHandoff, type ChatDockPresentation, type ChatDockTarget, } from './chatDockTarget.js'; @@ -55,9 +45,9 @@ export interface ChatDockConversationProps { */ defaultAgent?: string; /** - * objectui#10926 — the owning package (`_packageId`) of the app the console - * is showing. Only a `build` thread binds to it, and only when it is - * authorable (see {@link ChatDockConversation}). Absent → app-less. + * objectstack#30043 — the owning package (`_packageId`) of the app the + * console is showing, sent as the turn's `context.activeApp`. Absent → + * app-less. */ appPackageId?: string; /** @@ -74,27 +64,22 @@ export interface ChatDockConversationProps { * Absent → the ambient thread described on {@link ChatDockConversation}. */ target?: ChatDockTarget; - /** Replaces the target in place: a picked history row, a minted fresh thread, a binding. */ + /** Replaces the target in place: a picked history row or a minted fresh thread. */ onTargetChange?: (target: ChatDockTarget | undefined) => void; - /** A Builder handoff to seed once as the build thread's first message. */ - handoff?: ChatDockHandoff; /** Rail (history behind a button), full window (history beside the chat), or phone sheet. */ presentation?: ChatDockPresentation; /** Rail and sheet only: the history list shown over the chat. */ historyOpen?: boolean; onHistoryOpenChange?: (open: boolean) => void; /** - * objectstack#35445 — the drawer's title bar offers Share and the Build - * Doctor in its 「···」 menu. A host that passes this receives what those - * two items act on, and the pane's own header row stops drawing them. The - * share dialog and the doctor's drawer stay here; the host opens them - * through the four props below, as it opens the history. + * objectstack#35445 — the drawer's title bar offers Share in its 「···」 + * menu. A host that passes this receives what that item acts on, and the + * pane's own header row stops drawing it. The share dialog stays here; the + * host opens it through the two props below, as it opens the history. */ onActionsChange?: (actions: ChatDockConversationActions | undefined) => void; shareOpen?: boolean; onShareOpenChange?: (open: boolean) => void; - debugOpen?: boolean; - onDebugOpenChange?: (open: boolean) => void; } const EMPTY_INITIAL_MESSAGES: HydratedUIMessage[] = []; @@ -105,28 +90,16 @@ const EMPTY_INITIAL_MESSAGES: HydratedUIMessage[] = []; * window) or behind the header's History button (rail, sheet). Renders nothing * when the AI catalog is empty (OSS / no seat). * - * With no target the drawer shows its AMBIENT thread, scoped per ADR-0057 as - * amended for objectui#10926 (maintainer ruling 「绑定当前应用(推荐)」): inside - * an AUTHORABLE app — its package is not a `com.objectstack.*` built-in, the - * A1.b switcher's own predicate — a `build` thread binds to that app. - * `editPackageId` is the app's package, the scope is `app:PKG:build`, the key - * the Studio copilot resolves, so the two show ONE thread; the chip, the empty - * state and the agent context (`context.packageId`) name the app. `ask` stays - * ambient, and outside an authorable app the key is the product alone. The - * product-only thread is never cleared: it stays under its own key and in the - * history, and — through the A1.b migration read — it is adopted into the - * app's scope only when its own history is bound to that app. + * With no target the drawer shows its AMBIENT thread, keyed per ADR-0057 on + * the product alone: the ask thread is the same in every app (A2). * * objectstack#34608 — a target names the thread instead (a history row, an old - * `/ai…` link, "Edit with AI", the agent launcher): its agent, conversation, - * package or a fresh start, exactly as named — a target never infers the app. - * A new build stays UNBOUND until the build creates its package (ADR-0057 A1), - * and then re-keys to that app in place (A1.b bind-on-create). + * `/ai…` link, the agent launcher): its agent, conversation or a fresh start, + * exactly as named. * - * objectstack#35014 — a target belongs to the app it was opened in (or the app - * it names); the host withholds it everywhere else, so the drawer's thread - * follows the app with no prompt. `ask` stays ambient (A2): its key carries no - * app, so the ask thread is the same in every app. + * objectstack#35014 — a target belongs to the app it was opened in; the host + * withholds it everywhere else, so the drawer's thread follows the app with + * no prompt. */ export function ChatDockConversation({ userId, @@ -137,33 +110,19 @@ export function ChatDockConversation({ surfaceArtifactLabel, target, onTargetChange, - handoff, presentation = 'rail', historyOpen = false, onHistoryOpenChange, onActionsChange, shareOpen: shareOpenProp, onShareOpenChange, - debugOpen: debugOpenProp, - onDebugOpenChange, }: ChatDockConversationProps) { const { agents, isLoading, error } = useAgents({ apiBase }); const catalogNames = React.useMemo(() => agents.map((a) => a.name), [agents]); - // cloud#1674 maker convergence — the console dock is a maker surface, so an - // authoring-capable principal's ambient thread upgrades ask→build inside the - // ONE resolver; business sessions keep the ask ambient thread unchanged. - const canAuthorMetadata = useCanAuthorMetadata(); const aiStudioEnabled = isAiStudioEnabled(); - const makerConverged = makerConvergedOnBuild(agents, canAuthorMetadata, aiStudioEnabled); const ambientAgent = React.useMemo( - () => - resolveSurfaceAgent('default', { - agents, - appDefaultAgent: defaultAgent, - aiStudioEnabled, - canAuthorMetadata, - }), - [agents, defaultAgent, aiStudioEnabled, canAuthorMetadata], + () => resolveSurfaceAgent('default', { agents, appDefaultAgent: defaultAgent, aiStudioEnabled }), + [agents, defaultAgent, aiStudioEnabled], ); // ── The target's agent ────────────────────────────────────────────────── @@ -178,15 +137,7 @@ export function ChatDockConversation({ targetAgent && agents.length > 0 && !namedAgent && !isBuiltinAgentName(targetAgent) && !target?.conversationId ? targetAgent : undefined; - let activeAgent = ambientAgent; - if (namedAgent) { - // cloud#1674 — a maker opening the bare ask agent lands on the converged - // build composer; an existing ask conversation still opens on its own agent. - activeAgent = - makerConverged && isAskAgent(namedAgent) && !target?.conversationId - ? resolveAgentParam('build', catalogNames) ?? namedAgent - : namedAgent; - } + const activeAgent = namedAgent ?? ambientAgent; const activeAgentRoute = activeAgent ? agentRouteName(activeAgent) : undefined; React.useEffect(() => { @@ -216,21 +167,7 @@ export function ChatDockConversation({ ? `${apiBase}/agents/${encodeURIComponent(activeAgent)}/chat` : undefined; const product = chatProductOfAgent(activeAgent); - const ambientPackageId = ambientAppPackage(appPackageId); - // objectstack#35014 — a target reaches this body only in the app it belongs - // to: the host (`useConsoleChatDock`) hands it down there and nowhere else, - // so moving to another app arrives here as "no target" and the new app's - // ambient thread resolves below. - const editPackageId = - product === 'build' ? (target ? target.packageId : ambientPackageId) : undefined; - const scope = activeAgent - ? chatConversationScope({ appId: editPackageId, product }) - : undefined; - const adoptLegacyBuildThread = React.useCallback( - (messages: HydratedUIMessage[]) => - editPackageId !== undefined && isThreadBoundToPackage(messages, editPackageId), - [editPackageId], - ); + const scope = activeAgent ? chatConversationScope({ product }) : undefined; const requestedConversationId = legacyConversationId ? undefined : target?.conversationId; const forceNew = Boolean(target?.fresh) && !requestedConversationId; // The user the conversation resolves for (none until the agent is known). @@ -241,20 +178,16 @@ export function ChatDockConversation({ initialMessages, ensureConversation, createError, - rekeyScope, } = useChatConversation({ userId: conversationUserId, scope, apiBase, activeId: requestedConversationId, forceNew, - legacyScope: editPackageId && !target ? product : undefined, - adoptLegacy: editPackageId && !target ? adoptLegacyBuildThread : undefined, }); - // #2450 — hand the pane only a scope-matched conversation. Moving between - // apps changes the scope while the dock stays mounted; until the hook - // re-resolves, `conversationId` is still the previous app's thread, and a - // pane mounted on it would pair that thread with the new app's package. + // #2450 — hand the pane only a scope-matched conversation. Switching agents + // changes the scope while the dock stays mounted; until the hook + // re-resolves, `conversationId` is still the previous agent's thread. const scopeMatched = conversationScope === scope; const paneConversationId = scopeMatched ? conversationId : undefined; const paneInitialMessages = scopeMatched ? initialMessages : EMPTY_INITIAL_MESSAGES; @@ -277,35 +210,7 @@ export function ChatDockConversation({ }); }, [forceNew, target, paneConversationId, staleFresh, activeAgentRoute, onTargetChange]); - // ── A1.b bind-on-create ───────────────────────────────────────────────── - // The build just minted (or its history reveals) package `pkg` while this - // thread is keyed product-only: re-key it to `app:PKG:build` first (the - // scope flips synchronously, so the #2450 gate stays matched and the pane is - // never remounted), then name the package on the target. - const handlePackageBound = React.useCallback( - (pkg: string) => { - if (!pkg || editPackageId || product !== 'build' || !activeAgentRoute) return; - if (scope !== product || conversationScope !== scope || !conversationId) return; - rekeyScope(chatConversationScope({ appId: pkg, product })); - onTargetChange?.({ agent: activeAgentRoute, conversationId, packageId: pkg }); - }, - [editPackageId, product, activeAgentRoute, scope, conversationScope, conversationId, rekeyScope, onTargetChange], - ); - const pendingFirstMessageRef = React.useRef(null); - const [pendingFirstMessageSeq, setPendingFirstMessageSeq] = React.useState(0); - // ADR-0057 P4 — seed a handed-off build prompt as the build thread's first - // message, once per handoff; the pane's deferred-send replay sends it when - // the id lands. Targeted at the build agent (#2450), so a pane still bound to - // the previous agent mid-switch never consumes it. - const seededHandoffRef = React.useRef(0); - React.useEffect(() => { - const prompt = handoff?.state.handoffPrompt; - if (!handoff || !prompt || seededHandoffRef.current === handoff.seq) return; - seededHandoffRef.current = handoff.seq; - pendingFirstMessageRef.current = { content: prompt, targetAgentRoute: 'build' }; - setPendingFirstMessageSeq((s) => s + 1); - }, [handoff]); // ADR-0028 — the composer's picked model, held here so it outlives the keyed // pane's remount when the first send mints the conversation. const [selectedModelId, setSelectedModelId] = React.useState(undefined); @@ -329,8 +234,7 @@ export function ChatDockConversation({ }, [conversationUserId, markFocusSending, ensureConversation]); // ── The drawer's own controls over its thread ─────────────────────────── - // The launcher, the app switcher and the handoff in the pane open targets - // through the host. Picking the agent the ambient thread already runs goes + // The launcher in the pane opens targets through the host. Picking the agent the ambient thread already runs goes // back to the ambient thread rather than an unbound copy of it. const host = useChatDockControl(); const drawerControl = React.useMemo(() => { @@ -352,9 +256,9 @@ export function ChatDockConversation({ }, [host, ambientAgent, catalogNames]); const startNewConversation = React.useCallback(() => { - onTargetChange?.({ agent: activeAgentRoute, packageId: editPackageId, fresh: true }); + onTargetChange?.({ agent: activeAgentRoute, fresh: true }); onHistoryOpenChange?.(false); - }, [onTargetChange, activeAgentRoute, editPackageId, onHistoryOpenChange]); + }, [onTargetChange, activeAgentRoute, onHistoryOpenChange]); const openConversation = React.useCallback( (conversation: { id: string; agentId?: string }) => { const next: ChatDockTarget = { @@ -382,27 +286,21 @@ export function ChatDockConversation({ [conversationId], ); - // Share and the Build Doctor: the drawer's 「···」 menu offers them when its - // host takes them (objectstack#35445), else the pane's header does. + // Share: the drawer's 「···」 menu offers it when its host takes it + // (objectstack#35445), else the pane's header does. const [ownShareOpen, setOwnShareOpen] = React.useState(false); - const [ownDebugOpen, setOwnDebugOpen] = React.useState(false); const shareOpen = shareOpenProp ?? ownShareOpen; - const debugOpen = debugOpenProp ?? ownDebugOpen; const setShareOpen = onShareOpenChange ?? setOwnShareOpen; - const setDebugOpen = onDebugOpenChange ?? setOwnDebugOpen; const actionsInHost = onActionsChange !== undefined; const restApiBase = React.useMemo( () => apiBase.replace(/\/v1\/ai$/, '').replace(/\/ai$/, '') || '/api', [apiBase], ); const publicShareBase = React.useMemo(() => resolvePublicShareBase(), []); - // objectstack#35445 — the Build Doctor reads a build's internals: offered - // only to a user who may build, whichever agent the thread runs. - const showDebug = agentHasCapability(agents, activeAgent, 'debug') && canAuthorMetadata; const inert = !isLoading && agents.length === 0; React.useEffect(() => { - onActionsChange?.(inert ? undefined : { conversationId, showDebug }); - }, [onActionsChange, inert, conversationId, showDebug]); + onActionsChange?.(inert ? undefined : { conversationId, showDebug: false }); + }, [onActionsChange, inert, conversationId]); // OSS / no AI seat → the whole dock body is inert (the robot is gated too). if (inert) return null; @@ -412,7 +310,6 @@ export function ChatDockConversation({ userId={userId} apiBase={apiBase} activeAgent={activeAgent} - includeAskConversations={makerConverged} refreshKey={refreshKey} activeConversationId={paneConversationId} onSelectConversation={openConversation} @@ -436,27 +333,20 @@ export function ChatDockConversation({ apiBase={apiBase} conversationId={paneConversationId} requestedConversationId={requestedConversationId} - editPackageId={editPackageId} - onPackageBound={handlePackageBound} - canBind={Boolean(paneConversationId)} - parentHandoffConversationId={handoff?.state.parentConversationId} // objectstack#30043 — the app the dock sits in is the selected app, - // whichever agent runs and whether or not a build thread binds to it. + // whichever agent runs. activeAppPackageId={appPackageId} surfaceContext={surfaceContext} surfaceArtifactLabel={surfaceArtifactLabel} conversationFocus={conversationFocus} initialMessages={paneInitialMessages} pendingFirstMessageRef={pendingFirstMessageRef} - pendingFirstMessageSeq={pendingFirstMessageSeq} ensureConversation={ensureConversationForSend} conversationCreateError={createError} selectedModelId={selectedModelId} onSelectedModelChange={setSelectedModelId} onSent={handleSent} onShare={() => setShareOpen(true)} - onDebug={() => setDebugOpen(true)} - showDebug={showDebug} actionsInHost={actionsInHost} />
@@ -479,14 +369,6 @@ export function ChatDockConversation({ publicBaseUrl={publicShareBase} /> ) : null} - {conversationId && showDebug ? ( - - ) : null} ); } diff --git a/ui/packages/app-shell/src/layout/__tests__/ChatDock.appBinding-10926.test.tsx b/ui/packages/app-shell/src/layout/__tests__/ChatDock.appBinding-10926.test.tsx index 260c5f1668e..aabb5829396 100644 --- a/ui/packages/app-shell/src/layout/__tests__/ChatDock.appBinding-10926.test.tsx +++ b/ui/packages/app-shell/src/layout/__tests__/ChatDock.appBinding-10926.test.tsx @@ -1,32 +1,30 @@ // Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. /** - * objectui#10926 — the console dock binds its BUILD thread to the current app - * (ADR-0057, amended per the maintainer ruling 「绑定当前应用(推荐)」). - * - * Inside an authorable app (its package is not a `com.objectstack.*` built-in), - * a dock whose agent resolves to `build` is keyed `app:PKG:build` — the key the - * Studio copilot and `/ai/build?package=PKG` resolve — so the three show ONE - * thread, and the chip, the empty state and the agent context name the app. - * `ask` stays ambient; a built-in app and an app-less console keep the - * product-only key, as before. + * objectui#10926 — the console dock's thread is keyed on the product alone + * (ADR-0057 A2, "ask stays ambient"): the same thread in every app, with the + * app in view sent only as the turn's `context.activeApp` (objectstack#30043). + * The per-app build thread this file used to pin left with the in-app build + * entry (objectstack#37682). * * ## Real subjects * - * `ChatDockPanel` / `ChatDockMobileSheet` with their REAL default body, the REAL - * `ChatPane`, the REAL `useChatConversation` (its per-`(user, scope)` - * localStorage cache is the seam the surfaces share) and, for the sharing pin, - * the REAL full-page `AiChatPage`. The stand-ins: the agent catalog, the - * authoring capability, the metadata apps list, the chat transport + * `ChatDockPanel` and the console host (`useConsoleChatDock`) with their REAL + * default body, the REAL `ChatPane` and the REAL `useChatConversation` (its + * per-`(user, scope)` localStorage cache is the seam the surfaces share). The + * stand-ins: the agent catalog, the metadata apps list, the chat transport * (`useObjectChat` records its options — the request `body` rides them) and * `ChatbotEnhanced` (renders the header slot and the empty-state title it is * handed). The conversation API is a `fetch` stub over an in-memory store. */ +// AiChatPage reads a dropped spreadsheet through `import('@object-ui/plugin-grid')`; load it +// here so collection pays that transform, not a clocked case (check-test-source-alias). +import '@object-ui/plugin-grid'; import '@testing-library/jest-dom/vitest'; import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; -import { act, cleanup, fireEvent, render, screen, waitFor, within } from '@testing-library/react'; -import { MemoryRouter, Route, Routes } from 'react-router-dom'; +import { cleanup, fireEvent, render, screen, waitFor, within } from '@testing-library/react'; +import { MemoryRouter } from 'react-router-dom'; import React from 'react'; interface ChatOptions { @@ -36,10 +34,7 @@ interface ChatOptions { const state = { agents: [] as Array<{ name: string; label: string }>, - canAuthor: true, chat: undefined as ChatOptions | undefined, - /** Every `(conversationId, context.packageId)` pair the transport was handed. */ - pairs: [] as Array<[string | undefined, unknown]>, }; vi.mock('@object-ui/plugin-chatbot', async (importOriginal) => { @@ -50,7 +45,6 @@ vi.mock('@object-ui/plugin-chatbot', async (importOriginal) => { useHitlInChat: () => ({ decide: vi.fn(), decisions: {} }), useObjectChat: (options: ChatOptions) => { state.chat = options; - state.pairs.push([options.conversationId, options.body?.context?.packageId]); return { messages: [], isLoading: false, @@ -81,9 +75,6 @@ vi.mock('@object-ui/plugin-chatbot/core', async (importOriginal) => ({ ...(await importOriginal()), useAgents: () => ({ agents: state.agents, isLoading: false, error: undefined, refetch: vi.fn() }), })); -vi.mock('../../hooks/useCanAuthorMetadata', () => ({ - useCanAuthorMetadata: () => state.canAuthor, -})); vi.mock('@object-ui/auth', async (importOriginal) => ({ ...(await importOriginal>()), useAuth: () => ({ user: { id: 'u1' } }), @@ -103,19 +94,20 @@ vi.mock('../../providers/AdapterProvider', async (importOriginal) => ({ useAdapter: () => null, })); vi.mock('../AiUsageIndicator', () => ({ AiUsageIndicator: () => null })); -vi.mock('../../console/ai/PendingDraftsBar', () => ({ PendingDraftsBar: () => null })); vi.mock('../../console/ai/ConversationsSidebar', () => ({ ConversationsSidebar: () =>
, })); import { I18nProvider } from '@object-ui/i18n'; -import { ChatDockMobileSheet, ChatDockPanel, type ChatDockState } from '../ChatDock'; -import { DOCK_TARGET_STORAGE_KEY, type ChatDockTarget } from '../chatDockTarget'; +import { ChatDockPanel, type ChatDockState } from '../ChatDock'; +// The dock body is a `lazy()` chunk carrying the whole chat UI. Loaded at module +// scope, so no test's send-wait spends its budget on the first cold import and +// the `lazy()` resolves from the module cache. +import '../ChatDockConversation'; +import type { ChatDockTarget } from '../chatDockTarget'; import { DOCK_EXPANDED_STORAGE_KEY } from '../chatDockState'; import { useConsoleChatDock } from '../useConsoleChatDock'; -import type { ChatDockControl } from '../chatDockControl'; -import { AiChatPage } from '../../console/ai/AiChatPage'; window.matchMedia = ((query: string) => ({ matches: false, @@ -159,41 +151,6 @@ function installFetch(): void { ); } -/** A persisted build thread whose own history binds it to `packageId`. */ -function boundTurns(packageId: string): unknown[] { - return [ - { id: 'r1', role: 'user', content: [{ type: 'text', text: 'add a field' }] }, - { - id: 'r2', - role: 'assistant', - content: [ - { type: 'text', text: 'Staged.' }, - { type: 'tool-call', toolCallId: 't1', toolName: 'apply_edit' }, - ], - }, - { - id: 'r3', - role: 'tool', - content: [ - { - type: 'tool-result', - toolCallId: 't1', - toolName: 'apply_edit', - output: { - type: 'text', - value: JSON.stringify({ - status: 'drafted', - kind: 'edit', - packageId, - drafted: [{ type: 'field', name: 'x' }], - }), - }, - }, - ], - }, - ]; -} - function dockState(): ChatDockState { return { expanded: true, @@ -244,14 +201,11 @@ async function settledConversationId(): Promise { return state.chat!.conversationId!; } -const BUILD = { name: 'build', label: 'Build' }; const ASK = { name: 'ask', label: 'Ask' }; beforeEach(() => { - state.agents = [BUILD, ASK]; - state.canAuthor = true; + state.agents = [ASK]; state.chat = undefined; - state.pairs = []; server = new Map(); minted = 0; window.localStorage.clear(); @@ -264,192 +218,22 @@ afterEach(() => { vi.unstubAllGlobals(); }); -describe('console dock — build thread bound to the current authorable app (objectui#10926)', () => { - it('inside app X the build chip names X, the empty state names X, and the request carries X', async () => { - renderDock('app.crm'); - // objectstack#32031 — opening the dock creates no conversation; the chip, - // the empty state and the agent context already name the app. - expect(await screen.findByTestId('ai-build-package-chip')).toHaveTextContent('Customer Desk'); - expect(screen.getByTestId('pane-empty-title')).toHaveTextContent('Customer Desk'); - expect(state.chat?.body?.context?.packageId).toBe('app.crm'); - expect(minted).toBe(0); - await sendFirst(); - const id = await settledConversationId(); - expect(minted).toBe(1); - - expect(screen.getByTestId('ai-build-package-chip')).toHaveTextContent('Customer Desk'); - expect(screen.getByTestId('pane-empty-title')).toHaveTextContent('Customer Desk'); - expect(state.chat?.body?.context?.packageId).toBe('app.crm'); - // Keyed `app:X:build`, never the product-only key. - expect(window.localStorage.getItem(cacheKey('app:app.crm:build'))).toBe(id); - expect(window.localStorage.getItem(cacheKey('build'))).toBeNull(); - }); - - it('the dock and /ai/build?package=X resolve the SAME thread', async () => { - renderDock('app.crm'); - await sendFirst(); - const dockThread = await settledConversationId(); - cleanup(); - state.chat = undefined; - - render( - - - } /> - } /> - - , - ); - expect(await settledConversationId()).toBe(dockThread); - expect(minted).toBe(1); - }); - - it('the dock resumes the thread another app:X:build surface (the Studio copilot) already keyed', async () => { - server.set('conv-studio', []); - window.localStorage.setItem(cacheKey('app:app.crm:build'), 'conv-studio'); - renderDock('app.crm'); - expect(await settledConversationId()).toBe('conv-studio'); - expect(minted).toBe(0); - }); - - it('ask stays ambient: product-only key, no package in the agent context, no chip', async () => { - state.canAuthor = false; // no maker convergence → the dock resolves `ask` +describe('console dock — one ambient thread, keyed on the product (objectui#10926)', () => { + it('inside an app the thread is keyed on the product alone, and the app rides as context.activeApp', async () => { renderDock('app.crm'); await sendFirst(); - const id = await settledConversationId(); - - expect(window.localStorage.getItem(cacheKey('ask'))).toBe(id); + const thread = await settledConversationId(); + expect(window.localStorage.getItem(cacheKey('ask'))).toBe(thread); expect(window.localStorage.getItem(cacheKey('app:app.crm:ask'))).toBeNull(); + expect(state.chat?.body?.context?.activeApp).toBe('app.crm'); expect(state.chat?.body?.context).not.toHaveProperty('packageId'); - expect(screen.queryByTestId('ai-build-package-chip')).not.toBeInTheDocument(); - }); - - it.each([ - ['a com.objectstack.* built-in app', 'com.objectstack.setup'], - ['no app', undefined], - ])('%s keeps the product-only build thread, unchanged', async (_label, appPackageId) => { - renderDock(appPackageId); - await sendFirst(); - const id = await settledConversationId(); - - expect(window.localStorage.getItem(cacheKey('build'))).toBe(id); - expect(state.chat?.body?.context).not.toHaveProperty('packageId'); - expect(screen.getByTestId('ai-build-package-chip')).toHaveTextContent('New app'); - }); - - it('adopts the product-only thread whose own history binds it to X, and leaves that key in place', async () => { - server.set('conv-legacy', boundTurns('app.crm')); - window.localStorage.setItem(cacheKey('build'), 'conv-legacy'); - renderDock('app.crm'); - - expect(await settledConversationId()).toBe('conv-legacy'); - expect(window.localStorage.getItem(cacheKey('app:app.crm:build'))).toBe('conv-legacy'); - expect(window.localStorage.getItem(cacheKey('build'))).toBe('conv-legacy'); - expect(minted).toBe(0); - }); - - it('does not adopt a product-only thread bound to another app', async () => { - server.set('conv-legacy', boundTurns('app.other')); - window.localStorage.setItem(cacheKey('build'), 'conv-legacy'); - renderDock('app.crm'); - - await sendFirst(); - const id = await settledConversationId(); - expect(id).not.toBe('conv-legacy'); - expect(minted).toBe(1); - expect(window.localStorage.getItem(cacheKey('build'))).toBe('conv-legacy'); - }); - - it('moving to another app never pairs the previous app\'s thread with the new package', async () => { - const dock = renderDock('app.crm'); - await sendFirst(); - const crmThread = await settledConversationId(); - state.chat = undefined; - dock.switchApp('app.other'); - await sendFirst(); - const otherThread = await settledConversationId(); - - expect(otherThread).not.toBe(crmThread); - expect(window.localStorage.getItem(cacheKey('app:app.other:build'))).toBe(otherThread); - const crmPairs = state.pairs.filter(([id]) => id === crmThread); - expect(crmPairs.length).toBeGreaterThan(0); - for (const [, pkg] of crmPairs) expect(pkg).toBe('app.crm'); - }); - - // objectstack#34608 — the drawer has no page to hand a thread to any more: - // an old `/ai/build?package=X` link (and the "Edit with AI" entries) open - // the drawer on a TARGET naming the app, from wherever it is hosted (Home has - // no app in view). It must land on the same thread the in-app dock bound. - it('a build target naming app X, opened where no app is in view, resumes the thread the dock bound to X', async () => { - renderDock('app.crm'); - await sendFirst(); - const dockThread = await settledConversationId(); - cleanup(); - state.chat = undefined; - - renderDock(undefined, { agent: 'build', packageId: 'app.crm' }); - expect(await settledConversationId()).toBe(dockThread); - expect((state.chat as ChatOptions | undefined)?.body?.context?.packageId).toBe('app.crm'); - expect(await screen.findByTestId('ai-build-package-chip')).toHaveTextContent('Customer Desk'); - expect(minted).toBe(1); }); - it('a target naming a conversation shows that conversation (an old /ai/build/ID link)', async () => { - renderDock('app.crm'); - await sendFirst(); - const dockThread = await settledConversationId(); - cleanup(); - state.chat = undefined; - - renderDock(undefined, { agent: 'build', conversationId: dockThread }); - expect(await settledConversationId()).toBe(dockThread); - expect(minted).toBe(1); - }); - - it('the mobile sheet binds the same way', async () => { - const onOpenChange = vi.fn(); - const sheet = (open: boolean) => ( - - - - - - ); - render(sheet(true)); - await sendFirst(); - await settledConversationId(); - expect(state.chat?.body?.context?.packageId).toBe('app.crm'); - }); -}); - -/** - * objectstack#35014 — the drawer's conversation follows the app. The maintainer - * ruled the switch automatic, with no "start a new conversation?" prompt. - * - * Real subject here: the console's drawer HOST, `useConsoleChatDock`, the hook - * `ConsoleLayout` and `HomeLayout` call. It holds what the drawer shows (the - * target) per tab, so the pins drive it through its own handle - * (`control.open`, the call the history list, the app switcher and "Edit with - * AI" make) and by moving the app the host is in. A remount reads the per-tab - * storage again, which is what moving between Home and an app does. - */ -describe('the drawer follows the app (objectstack#35014)', () => { - let control: ChatDockControl | null = null; - - function DockHost({ pkg }: { pkg: string | undefined }) { - const dock = useConsoleChatDock({ enabled: true, userId: 'u1', appPackageId: pkg }); - control = dock.control; - return <>{dock.rail}; - } - - function renderHost(appPackageId: string | undefined) { + it('ask is not per app (ADR-0057 A2): moving to another app keeps the same thread', async () => { window.sessionStorage.setItem(DOCK_EXPANDED_STORAGE_KEY, '1'); + function DockHost({ pkg }: { pkg: string | undefined }) { + return <>{useConsoleChatDock({ enabled: true, userId: 'u1', appPackageId: pkg }).rail}; + } const tree = (pkg: string | undefined) => ( @@ -457,156 +241,42 @@ describe('the drawer follows the app (objectstack#35014)', () => { ); - const { rerender } = render(tree(appPackageId)); - return { switchApp: (pkg: string | undefined) => rerender(tree(pkg)) }; - } - - const open = (target: ChatDockTarget | null) => - act(() => { - control?.open(target); - }); - - /** The pane is on no conversation yet, and the request context names `pkg`. */ - async function onBlankStartOf(pkg: string | undefined, chip: string): Promise { - await waitFor(() => expect(screen.getByTestId('ai-build-package-chip')).toHaveTextContent(chip)); - await waitFor(() => expect(state.chat?.body?.context?.packageId).toBe(pkg)); - expect(state.chat?.conversationId).toBeUndefined(); - } - - it("a thread opened in app A does not follow the user into app B: B shows its own start page, scoped to B", async () => { - const host = renderHost('app.crm'); - await sendFirst(); - const crmThread = await settledConversationId(); - // What a picked history row or a minted "New chat" leaves the drawer on. - await open({ agent: 'build', conversationId: crmThread, packageId: 'app.crm' }); - expect(await settledConversationId()).toBe(crmThread); - - state.chat = undefined; - host.switchApp('app.notes'); - await onBlankStartOf('app.notes', 'Meeting Notes'); - expect(screen.getByTestId('pane-empty-title')).toHaveTextContent('Meeting Notes'); - for (const [id, pkg] of state.pairs) if (id === crmThread) expect(pkg).toBe('app.crm'); - - // A send there lands in B's own thread. - await sendFirst(); - const notesThread = await settledConversationId(); - expect(notesThread).not.toBe(crmThread); - await waitFor(() => expect(state.chat?.body?.context?.packageId).toBe('app.notes')); - expect(window.localStorage.getItem(cacheKey('app:app.notes:build'))).toBe(notesThread); - }); - - it("back in app A, A's thread is still there, on the key the Studio copilot reads", async () => { - server.set('conv-crm', boundTurns('app.crm')); - const host = renderHost('app.crm'); - await open({ agent: 'build', conversationId: 'conv-crm', packageId: 'app.crm' }); - expect(await settledConversationId()).toBe('conv-crm'); - - host.switchApp('app.notes'); - await onBlankStartOf('app.notes', 'Meeting Notes'); - - state.chat = undefined; - host.switchApp('app.crm'); - expect(await settledConversationId()).toBe('conv-crm'); - expect(screen.getByTestId('ai-build-package-chip')).toHaveTextContent('Customer Desk'); - expect(window.localStorage.getItem(cacheKey('app:app.crm:build'))).toBe('conv-crm'); - }); - - it("picking app B in the scope switcher switches to B's thread and never re-binds A's thread to B", async () => { - server.set('conv-crm', boundTurns('app.crm')); - window.localStorage.setItem(cacheKey('app:app.crm:build'), 'conv-crm'); - const host = renderHost('app.crm'); - expect(await settledConversationId()).toBe('conv-crm'); - - // The switcher's own call (`openAssistant({ agent: 'build', packageId })`). - state.chat = undefined; - await open({ agent: 'build', packageId: 'app.notes' }); - await onBlankStartOf('app.notes', 'Meeting Notes'); - for (const [id, pkg] of state.pairs) if (id === 'conv-crm') expect(pkg).toBe('app.crm'); - expect(window.localStorage.getItem(cacheKey('app:app.crm:build'))).toBe('conv-crm'); - - // Entering B keeps B's thread; the header and the content still agree. - host.switchApp('app.notes'); - await onBlankStartOf('app.notes', 'Meeting Notes'); - }); - - it("app A's thread is not shown at Home or in the built-in Setup app, nor in app B after a remount", async () => { - server.set('conv-crm', boundTurns('app.crm')); - renderHost('app.crm'); - await open({ agent: 'build', conversationId: 'conv-crm', packageId: 'app.crm' }); - expect(await settledConversationId()).toBe('conv-crm'); - - for (const elsewhere of [undefined, 'com.objectstack.setup', 'app.notes']) { - cleanup(); - state.chat = undefined; - renderHost(elsewhere); - if (elsewhere === 'app.notes') await onBlankStartOf('app.notes', 'Meeting Notes'); - else await onBlankStartOf(undefined, 'New app'); - } - }); - - it('a target that names app X ("Edit with AI" at Home) shows at Home, stays when entering X, and goes when entering Y', async () => { - server.set('conv-crm', []); - window.localStorage.setItem(cacheKey('app:app.crm:build'), 'conv-crm'); - const host = renderHost(undefined); - await open({ agent: 'build', packageId: 'app.crm', fresh: true }); - await onBlankStartOf('app.crm', 'Customer Desk'); - - // Entering X keeps the fresh X thread the user asked for (not X's cached one). - host.switchApp('app.crm'); - await onBlankStartOf('app.crm', 'Customer Desk'); - - host.switchApp('app.notes'); - await onBlankStartOf('app.notes', 'Meeting Notes'); - }); - - it('an old /ai… link opens its conversation in the app it lands in, and that thread stays in that app', async () => { - server.set('conv-old', []); - // What `AiAddressRedirect` stores before replacing the visit by the landing. - window.sessionStorage.setItem( - DOCK_TARGET_STORAGE_KEY, - JSON.stringify({ agent: 'build', conversationId: 'conv-old' }), - ); - const host = renderHost('app.notes'); - expect(await settledConversationId()).toBe('conv-old'); - - state.chat = undefined; - host.switchApp('app.crm'); - await onBlankStartOf('app.crm', 'Customer Desk'); - }); - - it('ask is not per app (ADR-0057 A2, "ask stays ambient"): the ask thread is the same in every app', async () => { - state.canAuthor = false; // no maker convergence → the drawer resolves `ask` - const host = renderHost('app.crm'); + const { rerender } = render(tree('app.crm')); await sendFirst(); const askThread = await settledConversationId(); state.chat = undefined; - host.switchApp('app.notes'); + rerender(tree('app.notes')); expect(await settledConversationId()).toBe(askThread); expect(window.localStorage.getItem(cacheKey('ask'))).toBe(askThread); expect(window.localStorage.getItem(cacheKey('app:app.notes:ask'))).toBeNull(); }); + + it('a target naming a conversation shows that conversation (an old /ai/ask/ID link)', async () => { + server.set('conv-old', []); + renderDock('app.crm', { agent: 'ask', conversationId: 'conv-old' } satisfies ChatDockTarget); + expect(await settledConversationId()).toBe('conv-old'); + }); }); -describe('the drawer offers Share and the Build Doctor in its 「···」 menu (objectstack#35445)', () => { +describe('the drawer offers Share in its 「···」 menu (objectstack#35445)', () => { function openMenu(): HTMLElement { fireEvent.keyDown(screen.getByTestId('chat-dock-more'), { key: 'Enter' }); return screen.getByTestId('chat-dock-menu'); } - it('the pane row under the title keeps the app chip and draws no Share or Build Doctor of its own', async () => { + it('the pane row under the title draws no Share of its own', async () => { renderDock('app.crm'); - expect(await screen.findByTestId('ai-build-package-chip')).toBeInTheDocument(); + await screen.findByTestId('pane'); expect(screen.queryByTestId('ai-chat-share-button')).toBeNull(); - expect(screen.queryByTestId('ai-chat-debug-button')).toBeNull(); }); - it('a user who may build gets the Build Doctor; Share and the doctor wait for the thread to exist', async () => { + it('Share waits for the thread to exist, and the menu lists no build tooling', async () => { renderDock('app.crm'); - await screen.findByTestId('ai-build-package-chip'); + await screen.findByTestId('pane'); let menu = openMenu(); expect(within(menu).getByTestId('chat-dock-share')).toHaveAttribute('data-disabled'); - expect(within(menu).getByTestId('chat-dock-build-doctor')).toHaveAttribute('data-disabled'); + expect(within(menu).queryByTestId('chat-dock-build-doctor')).toBeNull(); fireEvent.keyDown(menu, { key: 'Escape' }); await sendFirst(); await settledConversationId(); @@ -614,22 +284,5 @@ describe('the drawer offers Share and the Build Doctor in its 「···」 menu menu = openMenu(); expect(within(menu).getByTestId('chat-dock-share')).not.toHaveAttribute('data-disabled'); }); - expect(within(menu).getByTestId('chat-dock-build-doctor')).not.toHaveAttribute('data-disabled'); - }); - - it('a user who may not build never sees the Build Doctor, even on a build thread', async () => { - state.canAuthor = false; - // A target naming the build agent puts the drawer on it without maker convergence. - renderDock('app.crm', { agent: 'build' }); - await screen.findByTestId('ai-build-package-chip'); - const menu = openMenu(); - expect(within(menu).getByTestId('chat-dock-share')).toBeInTheDocument(); - expect(within(menu).queryByTestId('chat-dock-build-doctor')).toBeNull(); - }); - - it('CONTROL: the same build thread for a user who may build lists it', async () => { - renderDock('app.crm', { agent: 'build' }); - await screen.findByTestId('ai-build-package-chip'); - expect(within(openMenu()).getByTestId('chat-dock-build-doctor')).toBeInTheDocument(); }); }); diff --git a/ui/packages/app-shell/src/layout/__tests__/ChatDock.requestContext-30043.test.tsx b/ui/packages/app-shell/src/layout/__tests__/ChatDock.requestContext-30043.test.tsx index 7cf98babf76..c4b896ec126 100644 --- a/ui/packages/app-shell/src/layout/__tests__/ChatDock.requestContext-30043.test.tsx +++ b/ui/packages/app-shell/src/layout/__tests__/ChatDock.requestContext-30043.test.tsx @@ -20,6 +20,9 @@ * (a recorder that exposes the pane's send) and the conversation API. */ +// AiChatPage reads a dropped spreadsheet through `import('@object-ui/plugin-grid')`; load it +// here so collection pays that transform, not a clocked case (check-test-source-alias). +import '@object-ui/plugin-grid'; import '@testing-library/jest-dom/vitest'; import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; import { act, cleanup, render, waitFor } from '@testing-library/react'; @@ -75,7 +78,6 @@ vi.mock('../../providers/AdapterProvider', async (importOriginal) => ({ useAdapter: () => null, })); vi.mock('../AiUsageIndicator', () => ({ AiUsageIndicator: () => null })); -vi.mock('../../console/ai/PendingDraftsBar', () => ({ PendingDraftsBar: () => null })); vi.mock('../UnifiedSidebar', () => ({ UnifiedSidebar: () => null })); vi.mock('../AppHeader', () => ({ AppHeader: () => null })); @@ -228,14 +230,14 @@ describe('console dock — the request names the selected app and the page in vi expect(context.surface).toEqual({ artifact: { type: 'object', name: 'account' } }); }); - it('the build agent bound to the app sends the same app as activeApp and packageId', async () => { + it('a build agent in the catalog binds no package: the turn names the app as activeApp alone (objectstack#37682)', async () => { state.agents = [{ name: 'build', label: 'Build' }]; state.canAuthor = true; mount('/apps/crm_app/dashboard/pipeline'); const context = await send('add a chart'); expect(context.activeApp).toBe('app.crm'); - expect(context.packageId).toBe('app.crm'); + expect(context.packageId).toBeUndefined(); expect(context.surface).toEqual({ artifact: { type: 'dashboard', name: 'pipeline' } }); }); diff --git a/ui/packages/app-shell/src/layout/__tests__/ChatDock.test.tsx b/ui/packages/app-shell/src/layout/__tests__/ChatDock.test.tsx index 6a3f405d072..8f48c49fff6 100644 --- a/ui/packages/app-shell/src/layout/__tests__/ChatDock.test.tsx +++ b/ui/packages/app-shell/src/layout/__tests__/ChatDock.test.tsx @@ -13,10 +13,12 @@ * the screen, so it has no expand button, only History. * * objectstack#35445 — the title bar is ONE row: History, 「···」 and the - * drawer's 「×」 close. Usage, Share, filling the window and the Build Doctor - * are items of the 「···」 menu; the Build Doctor is listed only when the body - * reports it (a user who may build). + * drawer's 「×」 close. Usage, Share and filling the window are items of the + * 「···」 menu (the Build Doctor entry left with the build chat, objectstack#37682). */ +// AiChatPage reads a dropped spreadsheet through `import('@object-ui/plugin-grid')`; load it +// here so collection pays that transform, not a clocked case (check-test-source-alias). +import '@object-ui/plugin-grid'; import '@testing-library/jest-dom/vitest'; import { describe, it, expect, vi, afterEach } from 'vitest'; import { render, screen, fireEvent, act, within } from '@testing-library/react'; @@ -64,7 +66,6 @@ vi.mock('../ChatDockConversation', async () => { presentation?: string; historyOpen?: boolean; shareOpen?: boolean; - debugOpen?: boolean; onActionsChange?: (a: unknown) => void; }) => { const { onActionsChange } = props; @@ -77,7 +78,6 @@ vi.mock('../ChatDockConversation', async () => { data-presentation={props.presentation} data-history-open={String(Boolean(props.historyOpen))} data-share-open={String(Boolean(props.shareOpen))} - data-debug-open={String(Boolean(props.debugOpen))} /> ); }, @@ -309,7 +309,7 @@ describe('the drawer title bar is one row: History, 「···」, Close (objects expect(screen.getByTestId('chat-dock-collapse').querySelector('svg.lucide-x')).not.toBeNull(); }); - it('the menu holds usage, Share, Expand and the Build Doctor, and opens the body\'s dialogs', async () => { + it('the menu holds usage, Share and Expand, and opens the body\'s Share dialog (no Build Doctor, objectstack#37682)', async () => { bodyState.actions = { conversationId: 'c1', showDebug: true }; usageState.usage = { pool: { fraction: 0.3, unmetered: false, upgrade: false, topUp: false } }; render(); @@ -317,24 +317,12 @@ describe('the drawer title bar is one row: History, 「···」, Close (objects const menu = openMenu(); expect(within(menu).getByTestId('chat-dock-usage')).toHaveTextContent('AI usage'); expect(within(menu).getByTestId('chat-dock-usage')).toHaveTextContent('Plenty left'); - expect(within(menu).getAllByRole('menuitem').map((i) => i.textContent)).toEqual([ - 'Share', - 'Expand', - 'Build Doctor', - ]); - fireEvent.click(within(menu).getByTestId('chat-dock-share')); - expect(screen.getByTestId('default-dock-body')).toHaveAttribute('data-share-open', 'true'); - fireEvent.click(within(openMenu()).getByTestId('chat-dock-build-doctor')); - expect(screen.getByTestId('default-dock-body')).toHaveAttribute('data-debug-open', 'true'); - }); - - it('the Build Doctor is not listed when the body withholds it (a user who may not build)', async () => { - bodyState.actions = { conversationId: 'c1', showDebug: false }; - render(); - await screen.findByTestId('default-dock-body'); - const menu = openMenu(); + // A body that still reports `showDebug: true` draws no doctor entry: the + // drawer it opened left with the build chat. expect(within(menu).getAllByRole('menuitem').map((i) => i.textContent)).toEqual(['Share', 'Expand']); expect(within(menu).queryByTestId('chat-dock-build-doctor')).toBeNull(); + fireEvent.click(within(menu).getByTestId('chat-dock-share')); + expect(screen.getByTestId('default-dock-body')).toHaveAttribute('data-share-open', 'true'); }); it('a pool running low marks the 「···」 trigger, so the warning is seen with the menu closed', async () => { diff --git a/ui/packages/app-shell/src/layout/__tests__/ConsoleLayout.dockBinding-10926.test.tsx b/ui/packages/app-shell/src/layout/__tests__/ConsoleLayout.dockBinding-10926.test.tsx index 41341d1bd98..3e872b1029c 100644 --- a/ui/packages/app-shell/src/layout/__tests__/ConsoleLayout.dockBinding-10926.test.tsx +++ b/ui/packages/app-shell/src/layout/__tests__/ConsoleLayout.dockBinding-10926.test.tsx @@ -7,14 +7,17 @@ * layout remounts (Home ↔ an app). Maximizing no longer leaves the page: it is * the panel's own full-window mode, pinned in `ChatDock.test.tsx`. * - * The binding decision itself (build only, authorable only) lives in the dock - * and is pinned in `ChatDock.appBinding-10926.test.tsx`. + * What the dock does with the package (it rides as the turn's + * `context.activeApp`) is pinned in `ChatDock.appBinding-10926.test.tsx`. * * `ConsoleLayout` renders for real under the real `NavigationProvider` and * router; the dock components are prop recorders, and the chrome siblings this * card does not touch are stubbed. */ +// AiChatPage reads a dropped spreadsheet through `import('@object-ui/plugin-grid')`; load it +// here so collection pays that transform, not a clocked case (check-test-source-alias). +import '@object-ui/plugin-grid'; import '@testing-library/jest-dom/vitest'; // The layout reaches `import('@objectstack/lint')` (the draft bar's publish // preflight); pay its first load at collection, never inside a clocked case. diff --git a/ui/packages/app-shell/src/layout/__tests__/chatFocus-36999.test.tsx b/ui/packages/app-shell/src/layout/__tests__/chatFocus-36999.test.tsx index 7af275dc60d..dccaff45936 100644 --- a/ui/packages/app-shell/src/layout/__tests__/chatFocus-36999.test.tsx +++ b/ui/packages/app-shell/src/layout/__tests__/chatFocus-36999.test.tsx @@ -19,6 +19,9 @@ * exposes the send). */ +// AiChatPage reads a dropped spreadsheet through `import('@object-ui/plugin-grid')`; load it +// here so collection pays that transform, not a clocked case (check-test-source-alias). +import '@object-ui/plugin-grid'; import '@testing-library/jest-dom/vitest'; import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; import { act, cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react'; @@ -81,7 +84,6 @@ vi.mock('../../providers/AdapterProvider', async (importOriginal) => ({ })); vi.mock('../../hooks/useCanAuthorMetadata', () => ({ useCanAuthorMetadata: () => false })); vi.mock('../../console/ai/ConversationsSidebar', () => ({ ConversationsSidebar: () => null })); -vi.mock('../../console/ai/PendingDraftsBar', () => ({ PendingDraftsBar: () => null })); import { I18nProvider } from '@object-ui/i18n'; import { AiChatPage } from '../../console/ai/AiChatPage'; diff --git a/ui/packages/app-shell/src/views/metadata-admin/PackageFormDialog.newAppStep-36748.test.tsx b/ui/packages/app-shell/src/views/metadata-admin/PackageFormDialog.newAppStep-36748.test.tsx index 08a165e5ffd..5fc29c2f95d 100644 --- a/ui/packages/app-shell/src/views/metadata-admin/PackageFormDialog.newAppStep-36748.test.tsx +++ b/ui/packages/app-shell/src/views/metadata-admin/PackageFormDialog.newAppStep-36748.test.tsx @@ -63,7 +63,6 @@ vi.mock('sonner', () => ({ })); vi.mock('../../components/SuggestedBindingsPanel', () => ({ SuggestedBindingsPanel: () => null })); vi.mock('./AccessExplainPanel', () => ({ AccessExplainPanel: () => null })); -vi.mock('../studio-design/StudioAiCopilot', () => ({ StudioChatDock: () => null })); vi.mock('../../preview/DraftChangesPanel', () => ({ DraftChangesPanel: () => null })); import { toast } from 'sonner'; diff --git a/ui/packages/app-shell/src/views/metadata-admin/PermissionMatrixEditor.saveSurface-12725.test.tsx b/ui/packages/app-shell/src/views/metadata-admin/PermissionMatrixEditor.saveSurface-12725.test.tsx index ef11e489ca8..c7bb608fc50 100644 --- a/ui/packages/app-shell/src/views/metadata-admin/PermissionMatrixEditor.saveSurface-12725.test.tsx +++ b/ui/packages/app-shell/src/views/metadata-admin/PermissionMatrixEditor.saveSurface-12725.test.tsx @@ -86,7 +86,6 @@ vi.mock('./useMetadata', async (importOriginal) => { vi.mock('./AssignedUsersSection', () => ({ AssignedUsersSection: () => null })); vi.mock('./AccessExplainPanel', () => ({ AccessExplainPanel: () => null })); vi.mock('../../components/SuggestedBindingsPanel', () => ({ SuggestedBindingsPanel: () => null })); -vi.mock('../studio-design/StudioAiCopilot', () => ({ StudioChatDock: () => null })); import '../../services/builtinComponents.js'; import { MetadataResourceEditPage } from './ResourceEditPage'; diff --git a/ui/packages/app-shell/src/views/metadata-admin/PermissionMatrixEditor.studioSave-36511.test.tsx b/ui/packages/app-shell/src/views/metadata-admin/PermissionMatrixEditor.studioSave-36511.test.tsx index c1b5d597fd6..b4c6d98ce77 100644 --- a/ui/packages/app-shell/src/views/metadata-admin/PermissionMatrixEditor.studioSave-36511.test.tsx +++ b/ui/packages/app-shell/src/views/metadata-admin/PermissionMatrixEditor.studioSave-36511.test.tsx @@ -99,7 +99,6 @@ vi.mock('sonner', () => ({ vi.mock('./AssignedUsersSection', () => ({ AssignedUsersSection: () => null })); vi.mock('./AccessExplainPanel', () => ({ AccessExplainPanel: () => null })); vi.mock('../../components/SuggestedBindingsPanel', () => ({ SuggestedBindingsPanel: () => null })); -vi.mock('../studio-design/StudioAiCopilot', () => ({ StudioChatDock: () => null })); import { toast } from 'sonner'; import { StudioPermissionSetPage } from '../studio-design/StudioPermissionSetPage'; diff --git a/ui/packages/app-shell/src/views/studio-design/AutomationsPillar.tsx b/ui/packages/app-shell/src/views/studio-design/AutomationsPillar.tsx index 4bdc2189bd1..7608a4d6174 100644 --- a/ui/packages/app-shell/src/views/studio-design/AutomationsPillar.tsx +++ b/ui/packages/app-shell/src/views/studio-design/AutomationsPillar.tsx @@ -25,7 +25,6 @@ import { createPortal } from 'react-dom'; import { useNavigate, useLocation, useSearchParams } from 'react-router-dom'; import { extractDraftBody, formatMetadataError, readDraftChanges, type DraftChange } from '@object-ui/data-objectstack'; import type { MetadataClient } from '@object-ui/data-objectstack'; -import { type StudioSurfaceLabel } from './StudioAiCopilot.js'; import { isSlotEscapeExempt, useStudioRightSlot } from './studioRightSlotState.js'; import { AUTOMATIONS_CONFIG_FOLD_WIDTH, useIsNarrowerThan } from './wideViewport.js'; import { STUDIO_FOLD_LABEL } from './studio-tokens.js'; @@ -183,7 +182,6 @@ export function AutomationsPillar({ readOnly: packageReadOnly = false, customization = null, onHeldEditChange, - onSurfaceLabelChange, }: { /** * The package whose flow this is, or `null` for the package-less scope @@ -201,11 +199,6 @@ export function AutomationsPillar({ customization?: StudioBaseCustomization | null; /** objectui#11786 — the clause of the edit the autosave holds unsent, for the surface's Publish. */ onHeldEditChange?: (clause: string | null) => void; - /** - * objectstack#35018 — the open flow's label for the copilot's chip: - * 「正在看:流程 · 新会议提醒」, never the type word and machine name. - */ - onSurfaceLabelChange?: (surface: StudioSurfaceLabel | null) => void; }): React.ReactElement { const client = useMetadataClient(); const locale = useMetadataLocale(); @@ -345,30 +338,6 @@ export function AutomationsPillar({ const [selection, setSelection] = React.useState(null); // The package's translations of the flow label and its approval-step labels (flow-label-translations.tsx). const flowLabels = useFlowLabelTranslations(current?.name ?? ''); - // objectstack#35018 — lift the open flow's label to the copilot's chip, the - // pillar's word first: 「正在看:流程 · 新会议提醒」 — the label the canvas - // header reads. Keyed on primitives, the callback read through a ref. - const onSurfaceLabelChangeRef = React.useRef(onSurfaceLabelChange); - React.useEffect(() => { - onSurfaceLabelChangeRef.current = onSurfaceLabelChange; - }); - const currentFlowType = current?.type; - const currentFlowName = current?.name; - const currentFlowLabel = current ? flowLabels?.flowLabel || current.label : undefined; - const flowSubject = t('engine.studio.copilot.subject.flow', locale); - React.useEffect(() => { - onSurfaceLabelChangeRef.current?.( - currentFlowType && currentFlowName && currentFlowLabel - ? { type: currentFlowType, name: currentFlowName, label: `${flowSubject} · ${currentFlowLabel}` } - : null, - ); - }, [currentFlowType, currentFlowName, currentFlowLabel, flowSubject]); - React.useEffect( - () => () => { - onSurfaceLabelChangeRef.current?.(null); - }, - [], - ); const [loading, setLoading] = React.useState(false); const [saving, setSaving] = React.useState(false); const [hasDraft, setHasDraft] = React.useState(false); diff --git a/ui/packages/app-shell/src/views/studio-design/CreateItemDialog.labels-13128.test.tsx b/ui/packages/app-shell/src/views/studio-design/CreateItemDialog.labels-13128.test.tsx index a092e165a80..5f7aa25a163 100644 --- a/ui/packages/app-shell/src/views/studio-design/CreateItemDialog.labels-13128.test.tsx +++ b/ui/packages/app-shell/src/views/studio-design/CreateItemDialog.labels-13128.test.tsx @@ -44,7 +44,6 @@ vi.mock('./packages-io', async (importOriginal) => { }; }); -vi.mock('./StudioAiCopilot', () => ({ StudioChatDock: () => null })); vi.mock('../../preview/DraftChangesPanel', () => ({ DraftChangesPanel: () => null })); import { StudioDesignSurface } from './StudioDesignSurface'; diff --git a/ui/packages/app-shell/src/views/studio-design/DataPillar.copilotChangesLine-34725.test.tsx b/ui/packages/app-shell/src/views/studio-design/DataPillar.copilotChangesLine-34725.test.tsx index 7411f49e437..69183cbe3bb 100644 --- a/ui/packages/app-shell/src/views/studio-design/DataPillar.copilotChangesLine-34725.test.tsx +++ b/ui/packages/app-shell/src/views/studio-design/DataPillar.copilotChangesLine-34725.test.tsx @@ -7,9 +7,7 @@ * pending-changes sheet) and 放弃全部未发布改动 (the package's discard door, * `packages.discardDrafts`, after a confirm) — the one undo there is; * - the Form canvas's card of each field the assistant changed carries the - * 草稿 chip; - * - item 6: the copilot's chip names the open object by its label and the view - * on screen (`Task · Records`), never its internal name. + * 草稿 chip. * CONTROL: entries a person wrote in Studio, or no draft, draw no line. * * The records grid's column marks ride on `GridFieldAuthoring.columnMarks`, @@ -194,24 +192,6 @@ describe('the AI assistant’s drafts on the Data canvas (objectstack#34725)', ( window.confirm = original; }); - it('the copilot’s chip reads the object’s label and the view on screen', async () => { - const onSurfaceLabelChange = vi.fn(); - renderPillar({ onSurfaceLabelChange }); - await waitFor(() => - expect(onSurfaceLabelChange).toHaveBeenLastCalledWith({ - type: 'object', - name: 'showcase_task', - label: `Task · ${L('engine.studio.data.tab.records')}`, - }), - ); - fireEvent.click(await screen.findByRole('button', { name: L('engine.studio.data.tab.form') })); - await waitFor(() => - expect(onSurfaceLabelChange).toHaveBeenLastCalledWith( - expect.objectContaining({ label: `Task · ${L('engine.studio.data.tab.form')}` }), - ), - ); - }); - it('CONTROL: entries a person wrote in Studio, or no draft at all, draw no line', async () => { serveDraft([{ path: ['fields', 'renewal_count'], by: 'studio', actor: 'usr_1', at: minutesAgo(2) }]); renderPillar(); diff --git a/ui/packages/app-shell/src/views/studio-design/DataPillar.tsx b/ui/packages/app-shell/src/views/studio-design/DataPillar.tsx index e9924602f60..07f37ff9d1f 100644 --- a/ui/packages/app-shell/src/views/studio-design/DataPillar.tsx +++ b/ui/packages/app-shell/src/views/studio-design/DataPillar.tsx @@ -27,7 +27,6 @@ import { type DraftChange, } from '@object-ui/data-objectstack'; import { resolveI18nLabel, type I18nLabel } from '@objectstack/spec/ui'; -import { type StudioSurfaceLabel } from './StudioAiCopilot.js'; import { useStudioRightSlot } from './studioRightSlotState.js'; import { StudioInspector } from './StudioInspector.js'; import { agentDraftMarkOf, DraftChip, DraftSourceLine, isAgentDraftSurface } from './StudioDraftMark.js'; @@ -288,7 +287,6 @@ export function DataPillar({ readOnly: packageReadOnly = false, customization = null, onHeldEditChange, - onSurfaceLabelChange, onReviewChanges, }: { packageId: string; @@ -296,8 +294,6 @@ export function DataPillar({ objectName: string; publishNonce?: number; onDraftSaved?: (saved?: StudioSavedDraft) => void; - /** objectstack#34725 — the open object's display label and tab, for the copilot's chip (see the Interfaces pillar's prop). */ - onSurfaceLabelChange?: (surface: StudioSurfaceLabel | null) => void; /** objectstack#34725 — the copilot-changes line's 查看: open the package's pending changes. */ onReviewChanges?: () => void; /** Courtesy gate: hide/disable metadata-authoring affordances (records stay usable). */ @@ -484,35 +480,6 @@ export function DataPillar({ const designerTab = useObjectDesignerTab(toolTabs); const viewMode = designerTab.location.view; const toolTab = designerTab.location.tool; - // objectstack#34725 — lift the open object's label to the copilot's chip, - // with the tab in view: 「正在看:会议 · 记录」, never the machine name. The - // Interfaces pillar's report (objectui#8219) is the same seam; keyed on - // primitives, the callback read through a ref. - const onSurfaceLabelChangeRef = React.useRef(onSurfaceLabelChange); - React.useEffect(() => { - onSurfaceLabelChangeRef.current = onSurfaceLabelChange; - }); - const currentObjectName = current.name; - const currentObjectLabel = current.label; - const viewModeLabel = t( - toolTab - ? `engine.studio.itemTabs.${toolTab.tab}` - : (OBJECT_DESIGNER_VIEWS.find((v) => v.view === viewMode)?.label ?? 'engine.studio.data.tab.records'), - locale, - ); - React.useEffect(() => { - onSurfaceLabelChangeRef.current?.( - currentObjectName && currentObjectLabel - ? { type: 'object', name: currentObjectName, label: `${currentObjectLabel} · ${viewModeLabel}` } - : null, - ); - }, [currentObjectName, currentObjectLabel, viewModeLabel]); - React.useEffect( - () => () => { - onSurfaceLabelChangeRef.current?.(null); - }, - [], - ); // objectui#11781 — the field inspector belongs to the view that opened it, // so a view switch closes it, the same act as its own Close: the selection // goes, and its blocking count expires with it (see `blockingReport`). Left diff --git a/ui/packages/app-shell/src/views/studio-design/StudioAiCopilot.tsx b/ui/packages/app-shell/src/views/studio-design/StudioAiCopilot.tsx deleted file mode 100644 index 285b5d017f1..00000000000 --- a/ui/packages/app-shell/src/views/studio-design/StudioAiCopilot.tsx +++ /dev/null @@ -1,366 +0,0 @@ -// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license. - -import React from 'react'; -import { useLocation, useParams } from 'react-router-dom'; -import { useAuth } from '@object-ui/auth'; -import { Button, ShareDialog } from '@object-ui/components'; -import { Share2 } from 'lucide-react'; -import { useObjectTranslation } from '@object-ui/i18n'; -import { useAgents } from '@object-ui/plugin-chatbot/core'; -import { useChatConversation } from '../../hooks/useChatConversation.js'; -import { chatConversationScope, chatProductOfAgent } from '../../hooks/chatScope.js'; -import { catalogServesBuild, resolveSurfaceAgent } from '../../hooks/surfaceAgent.js'; -import { ChatPane, resolveApiBase, type PendingFirstMessage } from '../../console/ai/AiChatPage.js'; -import { ConversationsSidebar } from '../../console/ai/ConversationsSidebar.js'; -import { resolvePublicShareBase } from '../../console/organizations/resolveHomeUrl.js'; -import { AiUsageIndicator } from '../../layout/AiUsageIndicator.js'; -import { usePlanApprovalPendingCount } from '../../assistant/assistantBus.js'; -import { STUDIO_METADATA_AREA, areaDesignerItemOf, orgScopeFlowOf } from './metadataArea.js'; - -/** - * objectui#8219 — the display label of the artifact a pillar has open, tagged - * with the identity it labels. Reported by pillars that know a label (today: - * the Interfaces pillar's open leaf); the others report nothing. - */ -export interface StudioSurfaceLabel { - type: string; - name: string; - label: string; -} - -interface StudioCopilotConversationProps { - /** The package the Studio surface is editing — scopes the build agent to it. */ - packageId: string; - /** - * objectui#8219 — the open artifact's display label, for the "discussing" - * chip only. Passed to ChatPane as its own prop when it labels the SAME - * artifact the URL names; it never enters `surfaceContext` (the agent's - * `context.surface`). Absent → the chip reads `type · name`. - */ - surfaceLabel?: StudioSurfaceLabel | null; - /** - * objectstack#34725 — a thread picked from the History list: that - * conversation, or (`fresh`) a new one. Absent → the package's build thread. - */ - target?: StudioCopilotTarget | null; - /** The conversation the pane shows, reported for the History list's active row and Share. */ - onConversationChange?: (conversationId: string | undefined) => void; - /** Bumped after a send, so the History list re-reads (a new thread is titled after its first answer). */ - onSent?: (firstUserMessage?: string) => void; -} - -/** objectstack#34725 — what the History list opened in the Studio copilot. */ -export interface StudioCopilotTarget { - conversationId?: string; - fresh?: boolean; -} - -/** - * The Studio copilot's chat body — the build agent scoped to the package being - * designed, over the ADR-0057 P1 `(user, app, product)` conversation, hosted by - * {@link StudioChatDock} in the surface's right slot. Renders nothing when the AI - * catalog is empty (community edition / no seat) — callers that add chrome - * around it must apply the same gate so no empty shell renders. - */ -export function StudioCopilotConversation({ - packageId, - surfaceLabel, - target, - onConversationChange, - onSent, -}: StudioCopilotConversationProps): React.ReactElement | null { - // cloud#1610 — the URL is the single source of the surface context: the - // pillar is the :tab route segment, the artifact is the `?surface=type:name` - // deep-link every pillar already mirrors (useSurfaceDeepLink). Derived per - // render; the ChatPane transport reads it per send, so each turn carries - // what the user is looking at RIGHT NOW. - const { tab, packageId: segment } = useParams<{ tab?: string; packageId?: string }>(); - const copilotLocation = useLocation(); - const surfaceContext = React.useMemo(() => { - const raw = new URLSearchParams(copilotLocation.search).get('surface'); - let artifact: { type: string; name: string } | undefined; - let pillar = tab; - if (raw) { - const idx = raw.indexOf(':'); - if (idx > 0 && idx < raw.length - 1) { - artifact = { type: raw.slice(0, idx), name: raw.slice(idx + 1) }; - } - } - // objectstack#36905, objectstack#36904, objectstack#36903 — a designer that - // opens full-screen at its metadata address (the permission set's matrix, - // the object designer, the flow designer) carries its item in the path, - // under the area's segment, not in a `?surface=`; on the package-less - // scope's leg (`~org`) so does the flow designer. - if (!tab && !artifact) { - const item = - areaDesignerItemOf(copilotLocation.pathname, segment) ?? - // Dormant today: the package-less scope mounts no copilot (objectui#11553); kept for when it does. - orgScopeFlowOf(copilotLocation.pathname, segment); - if (item) { - artifact = item; - pillar = STUDIO_METADATA_AREA; - } - } - if (!pillar && !artifact) return undefined; - return { ...(pillar ? { pillar } : {}), ...(artifact ? { artifact } : {}) }; - }, [tab, segment, copilotLocation.pathname, copilotLocation.search]); - // objectui#8219 — the chip's display label, read beside the context rather - // than inside it. Shown only when it labels the artifact the URL names: the - // URL stays the single source of WHAT is discussed, so a label that lags or - // leads the `?surface=` mirror is dropped instead of naming the wrong item. - const artifact = surfaceContext?.artifact; - const surfaceArtifactLabel = - artifact && surfaceLabel && surfaceLabel.type === artifact.type && surfaceLabel.name === artifact.name - ? surfaceLabel.label || undefined - : undefined; - const { user } = useAuth(); - const userId = user?.id; - const apiBase = React.useMemo(() => resolveApiBase(), []); - - const { agents, isLoading: agentsLoading, error: agentsError } = useAgents({ apiBase }); - - // ADR-0057 P2: the Studio authoring surface resolves through the ONE - // declarative resolver (`studio-build` → build, else platform default), not a - // local `isBuildAgent` pick. Same result, single source of truth. - const activeAgent = React.useMemo( - () => resolveSurfaceAgent('studio-build', { agents }), - [agents], - ); - - const chatApi = activeAgent - ? `${apiBase}/agents/${encodeURIComponent(activeAgent)}/chat` - : undefined; - - // One durable conversation per (user, app, product) — ADR-0057. Keyed on the - // PACKAGE and PRODUCT, not on this surface, so reopening the same app's design - // chat in the console's drawer (`/ai/build?package=…` opens it there) - // resumes THIS thread (no `studio:` fork). See {@link chatConversationScope}. - const { conversationId, initialMessages, ensureConversation, createError } = useChatConversation({ - userId: activeAgent ? userId : undefined, - scope: activeAgent - ? chatConversationScope({ appId: packageId, product: chatProductOfAgent(activeAgent) }) - : undefined, - apiBase, - activeId: target?.conversationId, - forceNew: Boolean(target?.fresh) && !target?.conversationId, - }); - const onConversationChangeRef = React.useRef(onConversationChange); - React.useEffect(() => { - onConversationChangeRef.current = onConversationChange; - }); - React.useEffect(() => { - onConversationChangeRef.current?.(conversationId); - }, [conversationId]); - - const pendingFirstMessageRef = React.useRef(null); - // ADR-0028 — the composer's picked model, held here so it outlives the keyed - // pane's remount when the first send mints the conversation. - const [selectedModelId, setSelectedModelId] = React.useState(undefined); - - // No agent served (community edition / misconfigured) → no copilot, plain surface. - if (!agentsLoading && agents.length === 0) return null; - - return ( - {})} - onShare={() => {}} - showDebug={false} - // objectstack#34725 — the right slot draws the one title bar; Share - // and the usage reading sit in the History view (`StudioChatDock`). - hideHeader - /> - ); -} - -// (The legacy LEFT copilot panel that used to live here was removed by the -// final ADR-0057 cleanup. The cloud `aiSlot` seam in StudioDesignSurface still -// accepts an injected left panel.) - -/** What the copilot reports up to the slot that hosts it (objectui#12725). */ -export interface StudioCopilotStatus { - available: boolean; - /** Items the copilot proposed that await the author's confirmation; 0 when none. */ - planPendingCount: number; -} - -export interface StudioChatDockProps { - /** The package the Studio surface is editing — scopes the build agent to it. */ - packageId: string; - /** objectui#8219 — the open artifact's display label, for the chat's - * "discussing" chip; see {@link StudioCopilotConversation}. */ - surfaceLabel?: StudioSurfaceLabel | null; - /** - * objectui#12725 — what the right slot draws of the copilot around it: - * `available`, whether the agent catalog serves one (true while it is still - * being read, as the dock always rendered then), so no segment, strip or - * empty body stands for a copilot that is not there; and `planPendingCount`, - * the objectui#11666 reading of a proposal awaiting approval with the number - * of items it asks the author to confirm (objectstack#25943). Reported on - * every change, and as unavailable on unmount. - */ - onStatusChange?: (status: StudioCopilotStatus) => void; - /** - * objectstack#34725 — the conversation history covers the chat while open - * (the pane stays mounted under it, so a streaming answer is never cut); the - * slot header's History button toggles it. Picking a row or New chat closes it. - */ - historyOpen?: boolean; - onHistoryOpenChange?: (open: boolean) => void; -} - -/** - * The Studio copilot as the body of the surface's right slot (objectui#12725; - * it was the ADR-0057 P3c right dock in the shared `ChatDockPanel` chrome - * until then). Same conversation as before — the build agent over the P1 - * `(user, package, build)` scope — and the same open-in-full-page door; only - * its host moved. The slot owns showing and hiding, its width, the small - * screen and the one title bar (objectstack#34725); this renders the - * conversation and, behind the slot's History button, the history list with - * Share and the usage reading (the console drawer keeps them in its header). - * - * - objectstack#34610 — the slot's widen control (in its header) widens the - * slot in place and narrows it again. It used to open - * `/ai/build?package=…`, which after objectstack#34608 lands on Home with - * the drawer full window, so the Studio page was lost. - */ -export function StudioChatDock({ - packageId, - surfaceLabel, - onStatusChange, - historyOpen = false, - onHistoryOpenChange, -}: StudioChatDockProps): React.ReactElement | null { - const { t: tc } = useObjectTranslation(); - const apiBase = React.useMemo(() => resolveApiBase(), []); - const { user } = useAuth(); - - // The catalog gate lives HERE: the slot asks it, and draws nothing of a - // copilot the catalog does not serve (community edition / no seat). - // objectstack#36969 — the copilot is the build agent, so the gate is the - // build agent being served (alias-aware), not any agent: where in-app - // building is closed the catalog keeps `ask`, and a copilot resolving to it - // would offer building it cannot do. The slot then shows the properties - // alone, as it does for an empty catalog; ask stays in the console's drawer. - const { agents, isLoading: agentsLoading } = useAgents({ apiBase }); - const available = agentsLoading || catalogServesBuild(agents); - // objectui#11666 — read off the assistant bus the chat publishes to. - const planPendingCount = usePlanApprovalPendingCount(); - const onStatusChangeRef = React.useRef(onStatusChange); - React.useEffect(() => { - onStatusChangeRef.current = onStatusChange; - }); - React.useEffect(() => { - onStatusChangeRef.current?.({ available, planPendingCount: available ? planPendingCount : 0 }); - }, [available, planPendingCount]); - React.useEffect( - () => () => { - onStatusChangeRef.current?.({ available: false, planPendingCount: 0 }); - }, - [], - ); - - // objectstack#34725 — the History list's pick, and the thread on screen. - const [target, setTarget] = React.useState(null); - const [conversationId, setConversationId] = React.useState(undefined); - // A fresh thread is named once its first send mints it, so the pick stops - // asking for a new one; the id on screen when New chat was pressed is never it. - const freshFromRef = React.useRef(undefined); - const onConversationChange = React.useCallback((id: string | undefined) => { - setConversationId(id); - if (!id || id === freshFromRef.current) return; - setTarget((prev) => (prev?.fresh ? { conversationId: id } : prev)); - }, []); - const activeAgent = React.useMemo(() => resolveSurfaceAgent('studio-build', { agents }), [agents]); - const [refreshKey, setRefreshKey] = React.useState(0); - const onSent = React.useCallback(() => setRefreshKey((k) => k + 1), []); - const [shareOpen, setShareOpen] = React.useState(false); - const restApiBase = React.useMemo( - () => apiBase.replace(/\/v1\/ai$/, '').replace(/\/ai$/, '') || '/api', - [apiBase], - ); - const publicShareBase = React.useMemo(() => resolvePublicShareBase(), []); - - if (!available) return null; - - return ( - <> - {/* flex-col so the ChatPane child (its root is `flex min-h-0 flex-1`) - gets a bounded flex-column parent and keeps its composer on screen. */} -
- - {historyOpen ? ( -
-
- {/* ADR-0057 #8 — proactive AI usage indicator (hides itself when the - usage endpoint is absent / returns nothing to show). */} - - -
- { - if (conversation.id !== conversationId) setTarget({ conversationId: conversation.id }); - onHistoryOpenChange?.(false); - }} - onNewConversation={() => { - freshFromRef.current = conversationId; - setTarget({ fresh: true }); - onHistoryOpenChange?.(false); - }} - className="min-h-0 flex-1 border-r-0" - /> -
- ) : null} -
- {conversationId ? ( - - ) : null} - - ); -} diff --git a/ui/packages/app-shell/src/views/studio-design/StudioDesignSurface.accessNewSimilar-28573.test.tsx b/ui/packages/app-shell/src/views/studio-design/StudioDesignSurface.accessNewSimilar-28573.test.tsx index 45bab7c95cb..ac44ff8ee92 100644 --- a/ui/packages/app-shell/src/views/studio-design/StudioDesignSurface.accessNewSimilar-28573.test.tsx +++ b/ui/packages/app-shell/src/views/studio-design/StudioDesignSurface.accessNewSimilar-28573.test.tsx @@ -89,7 +89,6 @@ vi.mock('../metadata-admin/catalog-scope', async (importOriginal) => ({ vi.mock('sonner', () => ({ toast: { success: vi.fn(), error: vi.fn() } })); vi.mock('../../components/SuggestedBindingsPanel', () => ({ SuggestedBindingsPanel: () => null })); vi.mock('../metadata-admin/AccessExplainPanel', () => ({ AccessExplainPanel: () => null })); -vi.mock('./StudioAiCopilot', () => ({ StudioChatDock: () => null })); import { t, tFormat, translateMetadataType } from '../metadata-admin/i18n'; import { StudioPermissionSetPage } from './StudioPermissionSetPage'; diff --git a/ui/packages/app-shell/src/views/studio-design/StudioDesignSurface.accessPairCopy-29674.test.tsx b/ui/packages/app-shell/src/views/studio-design/StudioDesignSurface.accessPairCopy-29674.test.tsx index ccce5dcfa15..030385eb6b3 100644 --- a/ui/packages/app-shell/src/views/studio-design/StudioDesignSurface.accessPairCopy-29674.test.tsx +++ b/ui/packages/app-shell/src/views/studio-design/StudioDesignSurface.accessPairCopy-29674.test.tsx @@ -94,7 +94,6 @@ vi.mock('sonner', () => ({ vi.mock('../../components/SuggestedBindingsPanel', () => ({ SuggestedBindingsPanel: () => null })); vi.mock('../metadata-admin/AccessExplainPanel', () => ({ AccessExplainPanel: () => null })); vi.mock('../metadata-admin/AssignedUsersSection', () => ({ AssignedUsersSection: () => null })); -vi.mock('./StudioAiCopilot', () => ({ StudioChatDock: () => null })); vi.mock('../../preview/DraftChangesPanel', () => ({ DraftChangesPanel: () => null })); import { StudioDesignSurface } from './StudioDesignSurface'; diff --git a/ui/packages/app-shell/src/views/studio-design/StudioDesignSurface.accessSegment-12452.test.tsx b/ui/packages/app-shell/src/views/studio-design/StudioDesignSurface.accessSegment-12452.test.tsx index 5e6f806d431..f964878177c 100644 --- a/ui/packages/app-shell/src/views/studio-design/StudioDesignSurface.accessSegment-12452.test.tsx +++ b/ui/packages/app-shell/src/views/studio-design/StudioDesignSurface.accessSegment-12452.test.tsx @@ -125,7 +125,6 @@ vi.mock('../metadata-admin/index.js', () => ({ MetadataResourceEditPage: () =>
, MetadataResourceHistoryPage: () =>
, })); -vi.mock('./StudioAiCopilot', () => ({ StudioChatDock: () => null })); vi.mock('../../preview/DraftChangesPanel', () => ({ DraftChangesPanel: () => null })); import { StudioDesignSurface } from './StudioDesignSurface'; diff --git a/ui/packages/app-shell/src/views/studio-design/StudioDesignSurface.accessSuggestionsReadOnly-33158.test.tsx b/ui/packages/app-shell/src/views/studio-design/StudioDesignSurface.accessSuggestionsReadOnly-33158.test.tsx index 1a03835c3dd..5fcf52fdead 100644 --- a/ui/packages/app-shell/src/views/studio-design/StudioDesignSurface.accessSuggestionsReadOnly-33158.test.tsx +++ b/ui/packages/app-shell/src/views/studio-design/StudioDesignSurface.accessSuggestionsReadOnly-33158.test.tsx @@ -74,7 +74,6 @@ vi.mock('../metadata-admin/useMetadata', async (importOriginal) => { }); vi.mock('sonner', () => ({ toast: { success: vi.fn(), error: vi.fn(), warning: vi.fn() } })); vi.mock('../metadata-admin/AccessExplainPanel', () => ({ AccessExplainPanel: () => null })); -vi.mock('./StudioAiCopilot', () => ({ StudioChatDock: () => null })); import { toast } from 'sonner'; import { t, tFormat } from '../metadata-admin/i18n'; diff --git a/ui/packages/app-shell/src/views/studio-design/StudioDesignSurface.accessWording-34795.test.tsx b/ui/packages/app-shell/src/views/studio-design/StudioDesignSurface.accessWording-34795.test.tsx index 2eb1b23df24..b0a402540e8 100644 --- a/ui/packages/app-shell/src/views/studio-design/StudioDesignSurface.accessWording-34795.test.tsx +++ b/ui/packages/app-shell/src/views/studio-design/StudioDesignSurface.accessWording-34795.test.tsx @@ -92,7 +92,6 @@ vi.mock('../metadata-admin/useMetadata', async (importOriginal) => { }); vi.mock('sonner', () => ({ toast: { success: vi.fn(), error: vi.fn(), warning: vi.fn() } })); vi.mock('../metadata-admin/AccessExplainPanel', () => ({ AccessExplainPanel: () => null })); -vi.mock('./StudioAiCopilot', () => ({ StudioChatDock: () => null })); import { t } from '../metadata-admin/i18n'; import { StudioPermissionSetPage } from './StudioPermissionSetPage'; diff --git a/ui/packages/app-shell/src/views/studio-design/StudioDesignSurface.aiChipLabel.test.tsx b/ui/packages/app-shell/src/views/studio-design/StudioDesignSurface.aiChipLabel.test.tsx deleted file mode 100644 index ccdd722ae8e..00000000000 --- a/ui/packages/app-shell/src/views/studio-design/StudioDesignSurface.aiChipLabel.test.tsx +++ /dev/null @@ -1,245 +0,0 @@ -// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. - -/** - * objectui#8219 item 3, end to end — selecting a labelled item in the - * Interfaces pillar makes the copilot dock's "discussing" chip read that - * item's LABEL, with the internal `type · name` pair on the chip's tooltip. - * - * objectui#7254's ruling: what is READ is the label; the internal identity - * stays REACHABLE on a tooltip. The label exists only in the Interfaces - * pillar's open leaf, while the dock is mounted by the outer surface — so this - * pin mounts the real `StudioDesignSurface`, the real dock and the real - * `ChatPane`, and replaces only `ChatbotEnhanced` (a prop recorder: its props - * ARE the chip) and the chat transport (`useObjectChat`, a recorder of the - * request body the agent would receive). - * - * The fetch stub answers the REST reads the surface makes; everything it does - * not recognise answers an empty list. - * - * objectui#11196 re-judged the unlabelled-leaf case. It pinned the chip's - * `type · name` fallback, which the chip reached because a label-less leaf's - * Surface carried no label. A label-less entry now shows what it inherits — - * its target's current label, the runtime's rule — on every designer surface, - * the chip included; `type · name` stays reachable on the chip's tooltip - * (objectui#7254's reachable half). The host's metadata cache therefore - * labels the object, so the inherited text differs from the machine name. - */ - -import '@testing-library/jest-dom/vitest'; -import * as React from 'react'; -import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; -import { cleanup, render, waitFor } from '@testing-library/react'; -import { MemoryRouter, Route, Routes } from 'react-router-dom'; -import { I18nProvider } from '@object-ui/i18n'; - -const PACKAGE_ID = 'com.acme.app'; - -/** Props of the last `ChatbotEnhanced` render — the chip under assertion. */ -let chip: Record = {}; -/** Options of the last `useObjectChat` call — carries the agent-bound body. */ -let chatOptions: Record = {}; - -vi.mock('@object-ui/plugin-chatbot', async (importOriginal) => { - const actual = await importOriginal>(); - return { - ...actual, - ChatbotEnhanced: (props: Record) => { - chip = props; - return null; - }, - useObjectChat: (options: Record) => { - chatOptions = options; - return { - messages: [], - isLoading: false, - error: undefined, - sendMessage: vi.fn(), - stop: vi.fn(), - reload: vi.fn(), - clear: vi.fn(), - setMessages: vi.fn(), - }; - }, - useAiModels: () => ({ models: [], defaultModelId: undefined }), - }; -}); -vi.mock('@object-ui/plugin-chatbot/core', async (importOriginal) => ({ - ...(await importOriginal()), - useAgents: () => ({ - agents: [{ name: 'metadata_assistant', label: 'Build', capabilities: ['build'] }], - isLoading: false, - loading: false, - error: undefined, - refetch: vi.fn(), - }), -})); -vi.mock('@object-ui/auth', async (importOriginal) => { - const actual = await importOriginal>(); - return { ...actual, useAuth: () => ({ user: { id: 'u1' } }) }; -}); -vi.mock('./packages-io', async (importOriginal) => { - const actual = await importOriginal>(); - return { - ...actual, - fetchPackages: vi.fn(async () => [{ id: PACKAGE_ID, name: '客户管理', writable: true }]), - }; -}); -vi.mock('@object-ui/react', async (importOriginal) => { - const actual = await importOriginal>(); - return { ...actual, useAdapter: () => ({}) }; -}); -// ChatPane reads `apps` for the bound-package chip and the adapter for the -// Excel→App bar; neither is part of this pin. `objects` is what the console's -// nav-target resolver reads for what a label-less leaf inherits -// (objectui#11196). One module-level value, so its identity is stable. -const metadataCache = vi.hoisted(() => ({ - apps: [] as unknown[], - objects: [{ name: 'b2r4_customer', label: '客户' }], -})); -vi.mock('../../providers/MetadataProvider', async (importOriginal) => { - const actual = await importOriginal>(); - return { ...actual, useMetadata: () => metadataCache }; -}); -vi.mock('../../providers/AdapterProvider', async (importOriginal) => { - const actual = await importOriginal>(); - return { ...actual, useAdapter: () => null }; -}); -vi.mock('../../components/SuggestedBindingsPanel', () => ({ SuggestedBindingsPanel: () => null })); -vi.mock('../metadata-admin/AccessExplainPanel', () => ({ AccessExplainPanel: () => null })); - -// The source loads `@objectstack/lint` lazily; paid here, at collection, not -// inside a case's clock (check:test-source-alias). -import '@objectstack/lint'; -// objectstack#36900 — the surface mounts the command palette, which reaches the -// record preview's `lazy()` detail entry: its first load is paid at collection too. -import '@object-ui/plugin-detail'; -import { StudioDesignSurface } from './StudioDesignSurface'; -import { StudioPillarRedirect } from './StudioPillarRedirect'; -// The source under test reaches these dynamic imports (the command palette's -// record preview, the drafts panel's lint, the code editor): their first load -// is paid here, at collection, never inside a case's clock (`check:test-source-alias`). -import '@object-ui/plugin-detail'; - -window.matchMedia = ((query: string) => ({ - matches: false, - media: query, - onchange: null, - addEventListener: () => {}, - removeEventListener: () => {}, - addListener: () => {}, - removeListener: () => {}, - dispatchEvent: () => false, -})) as unknown as typeof window.matchMedia; -(globalThis as unknown as { ResizeObserver: unknown }).ResizeObserver = - (globalThis as unknown as { ResizeObserver?: unknown }).ResizeObserver ?? - class { - observe() {} - unobserve() {} - disconnect() {} - }; - -const SET = 'b2r4_member_access'; -const FLOW = 'b2r4_new_meeting_alert'; - -const NAV = [ - { id: 'nav_dash', type: 'dashboard', label: '客户仪表盘', dashboardName: 'b2r4_customer_dashboard' }, - // A leaf the author never labelled. - { id: 'nav_obj', type: 'object', objectName: 'b2r4_customer' }, -]; - -function json(body: unknown, status = 200) { - return new Response(JSON.stringify(body), { - status, - headers: { 'content-type': 'application/json' }, - }); -} - -beforeEach(() => { - chip = {}; - chatOptions = {}; - window.localStorage.clear(); - vi.stubGlobal( - 'fetch', - vi.fn(async (input: unknown) => { - const raw = - input && typeof input === 'object' && 'url' in input ? (input as { url: unknown }).url : input; - const path = new URL(String(raw), 'http://localhost').pathname; - if (path === '/api/v1/ai/conversations') return json({ id: 'conv_8219', messages: [] }); - if (path.startsWith('/api/v1/ai/conversations/')) return json({ id: 'conv_8219', messages: [] }); - if (path === '/api/v1/meta/_drafts') return json([]); - if (path === '/api/v1/meta/app') return json([{ name: 'acme_app', label: '客户管理' }]); - // objectstack#35018 — the Access and Automations rails' items. - if (path === '/api/v1/meta/permission') return json([{ name: SET, label: '组织成员', isDefault: true }]); - if (path === '/api/v1/meta/flow') return json([{ name: FLOW, label: '新会议提醒', type: 'autolaunched' }]); - if (path === '/api/v1/meta/app/acme_app/layers') { - return json({ - code: null, - overlay: null, - overlayScope: null, - effective: { name: 'acme_app', label: '客户管理', navigation: NAV }, - }); - } - if (path.endsWith('/layers')) return json({ code: null, overlay: null, overlayScope: null, effective: null }); - if (/^\/api\/v1\/meta\/[^/]+\/[^/]+$/.test(path)) return json({}, 404); - return json([]); - }) as unknown as typeof fetch, - ); -}); - -afterEach(() => { - cleanup(); - vi.unstubAllGlobals(); -}); - -function renderStudio(entry = `/studio/${PACKAGE_ID}/interfaces`) { - return render( - - - - } /> - } /> - {/* objectstack#36905 — a permission set opens at its metadata address. */} - } /> - - - , - ); -} - -const agentSurface = () => - (chatOptions.body as { context: { surface?: unknown } } | undefined)?.context.surface; - -// objectstack#35018 — the Access and Automations rails report their open -// item's label too: the chip reads the rail's word and the label, as the Data -// rail's 「会议 · 记录」 does — never the type word (`permission` / `flow`) or -// the machine name, which stay on the tooltip and in the agent's data. -// objectstack#36905 — a permission set now opens full-screen at its metadata -// address, and keeps its chip there: the agent reads the item off the path. -describe('objectstack#35018 — 正在看 on the Access and Automations rails reads a label', () => { - it('Access: 「正在看:权限 · 组织成员」, no type word, no machine name', async () => { - renderStudio(`/studio/${PACKAGE_ID}/metadata/permission/${SET}?package=${PACKAGE_ID}`); - await waitFor(() => expect(chip.surfaceContextLabel).toBe('正在看:权限 · 组织成员'), { timeout: 6000 }); - expect(String(chip.surfaceContextLabel)).not.toContain('permission'); - expect(String(chip.surfaceContextLabel)).not.toContain(SET); - // CONTROL: the identity stays reachable on the tooltip, and the agent's data is the URL's. - expect(chip.surfaceContextTitle).toBe(`permission · ${SET}`); - expect(JSON.stringify(agentSurface())).toBe( - JSON.stringify({ pillar: 'metadata', artifact: { type: 'permission', name: SET } }), - ); - }); - - it('Automations: 「正在看:流程 · 新会议提醒」, no type word, no machine name', async () => { - // objectstack#36903 — the flow designer, full-screen on the flow's address. - renderStudio(`/studio/${PACKAGE_ID}/metadata/flow/${FLOW}`); - await waitFor(() => expect(chip.surfaceContextLabel).toBe('正在看:流程 · 新会议提醒'), { timeout: 6000 }); - expect(String(chip.surfaceContextLabel)).not.toContain('flow'); - expect(String(chip.surfaceContextLabel)).not.toContain(FLOW); - expect(chip.surfaceContextTitle).toBe(`flow · ${FLOW}`); - // The agent's data is the URL's: the address names the flow, with no - // `?surface=`, under the metadata area — the shape every designer on its - // metadata address sends (objectstack#36904, objectstack#36905). - expect(JSON.stringify(agentSurface())).toBe( - JSON.stringify({ pillar: 'metadata', artifact: { type: 'flow', name: FLOW } }), - ); - }); -}); diff --git a/ui/packages/app-shell/src/views/studio-design/StudioDesignSurface.backToApp-36501.test.tsx b/ui/packages/app-shell/src/views/studio-design/StudioDesignSurface.backToApp-36501.test.tsx index 1e6c15c88d8..ce5442b2d17 100644 --- a/ui/packages/app-shell/src/views/studio-design/StudioDesignSurface.backToApp-36501.test.tsx +++ b/ui/packages/app-shell/src/views/studio-design/StudioDesignSurface.backToApp-36501.test.tsx @@ -54,7 +54,6 @@ vi.mock('sonner', () => ({ })); vi.mock('../../components/SuggestedBindingsPanel', () => ({ SuggestedBindingsPanel: () => null })); vi.mock('../metadata-admin/AccessExplainPanel', () => ({ AccessExplainPanel: () => null })); -vi.mock('./StudioAiCopilot', () => ({ StudioChatDock: () => null })); vi.mock('../../preview/DraftChangesPanel', () => ({ DraftChangesPanel: () => null })); import { StudioDesignSurface } from './StudioDesignSurface'; diff --git a/ui/packages/app-shell/src/views/studio-design/StudioDesignSurface.canvasStripServedLabel-36480.test.tsx b/ui/packages/app-shell/src/views/studio-design/StudioDesignSurface.canvasStripServedLabel-36480.test.tsx index 9b56e564621..0782a761147 100644 --- a/ui/packages/app-shell/src/views/studio-design/StudioDesignSurface.canvasStripServedLabel-36480.test.tsx +++ b/ui/packages/app-shell/src/views/studio-design/StudioDesignSurface.canvasStripServedLabel-36480.test.tsx @@ -107,16 +107,6 @@ vi.mock('../../components/SuggestedBindingsPanel', () => ({ SuggestedBindingsPan vi.mock('../metadata-admin/AccessExplainPanel', () => ({ AccessExplainPanel: () => null })); vi.mock('../../preview/DraftChangesPanel', () => ({ DraftChangesPanel: () => null })); -// A copilot is served, so the surface keeps its one right slot, where the strip draws. -vi.mock('./StudioAiCopilot', () => ({ - StudioChatDock: ({ onStatusChange }: { onStatusChange?: (s: { available: boolean; planPendingCount: number }) => void }) => { - React.useEffect(() => { - onStatusChange?.({ available: true, planPendingCount: 0 }); - }, [onStatusChange]); - return
conversation
; - }, -})); - // Pay the dynamic `@objectstack/lint` load at collection, never inside a case's // clocked window (`check:test-source-alias`). import '@objectstack/lint'; diff --git a/ui/packages/app-shell/src/views/studio-design/StudioDesignSurface.changesCount-11787.test.tsx b/ui/packages/app-shell/src/views/studio-design/StudioDesignSurface.changesCount-11787.test.tsx index e6682606e22..5277b8a58a9 100644 --- a/ui/packages/app-shell/src/views/studio-design/StudioDesignSurface.changesCount-11787.test.tsx +++ b/ui/packages/app-shell/src/views/studio-design/StudioDesignSurface.changesCount-11787.test.tsx @@ -56,7 +56,6 @@ vi.mock('@object-ui/react', async (importOriginal) => { vi.mock('../../components/SuggestedBindingsPanel', () => ({ SuggestedBindingsPanel: () => null })); vi.mock('../metadata-admin/AccessExplainPanel', () => ({ AccessExplainPanel: () => null })); -vi.mock('./StudioAiCopilot', () => ({ StudioChatDock: () => null })); vi.mock('../../preview/DraftChangesPanel', () => ({ DraftChangesPanel: () => null })); // The console's preview and authoring code loads `@objectstack/lint` lazily; diff --git a/ui/packages/app-shell/src/views/studio-design/StudioDesignSurface.copilotDoors-12894.test.tsx b/ui/packages/app-shell/src/views/studio-design/StudioDesignSurface.copilotDoors-12894.test.tsx deleted file mode 100644 index 0f037b41f50..00000000000 --- a/ui/packages/app-shell/src/views/studio-design/StudioDesignSurface.copilotDoors-12894.test.tsx +++ /dev/null @@ -1,399 +0,0 @@ -// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. - -/** - * objectui#12894 (the console wiring), carried by objectui#12725 phase 6 — the - * two doors on the Studio copilot's applied card, end to end. - * - * A change the copilot saved as a draft (objectstack-ai/cloud#2924) ends in the - * applied card 「已存为草稿 · N 项」 with 查看变更并发布 and 撤销. The card is - * `plugin-chatbot`'s; the doors are the host's, and `ChatPane` is the host the - * Studio copilot mounts: - * - * - 撤销 → `POST /packages/:id/discard-drafts` for the card's package (through - * the SDK client the console's adapter holds), then the assistant bus's - * pulse, so the top bar's 变更 badge re-reads its ledger; - * - 查看变更并发布 → the surface's 变更 drawer, through its one declared way in - * (`?changes=review`, `studioChangesLink.ts`). The copilot is already inside - * Studio, so the surface stays mounted: same tree, same pillar, same - * selection, and the param is dropped once read. - * - * Real: the surface, its top bar and `usePendingDrafts`, the right slot, the - * Studio copilot (`StudioChatDock` → `StudioCopilotConversation` → `ChatPane`), - * and the chat itself (`ChatbotEnhanced`, with the chat package's own mapping - * of each tool part), fed the producer's envelope shapes. Stubbed: - * `globalThis.fetch` (the server), the SDK client's `packages.discardDrafts`, - * the chat transport (`useObjectChat` serves a scripted thread), the agent - * catalog, the conversation lookup, and the drawer's body (`DraftChangesPanel`, - * reduced to its `open` and `posture`). - */ - -import '@testing-library/jest-dom/vitest'; -import * as React from 'react'; -import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; -import { act, cleanup, fireEvent, render, screen, waitFor, within } from '@testing-library/react'; -import { MemoryRouter, Route, Routes, useLocation } from 'react-router-dom'; - -const PACKAGE_ID = 'app.hcpl'; -const DRAFTS = `/api/v1/meta/_drafts?package=${encodeURIComponent(PACKAGE_ID)}`; - -/** The scripted thread the mocked transport serves. */ -const chat = vi.hoisted(() => { - type Snapshot = { messages: unknown[]; isLoading: boolean }; - let snapshot: Snapshot = { messages: [], isLoading: false }; - const listeners = new Set<() => void>(); - return { - get: (): Snapshot => snapshot, - subscribe(listener: () => void): () => void { - listeners.add(listener); - return () => { - listeners.delete(listener); - }; - }, - set(next: Snapshot): void { - snapshot = next; - for (const l of listeners) l(); - }, - }; -}); - -/** The SDK client's discard door (`packages.discardDrafts`). */ -const sdk = vi.hoisted(() => ({ discardDrafts: vi.fn() })); - -vi.mock('@object-ui/plugin-chatbot', async (importOriginal) => { - const actual = await importOriginal>(); - return { - ...actual, - useAiModels: () => ({ models: [], defaultModelId: undefined }), - // `ChatbotEnhanced` stays REAL: its applied card and the two buttons on it - // are what the user clicks. - useObjectChat: () => { - const s = React.useSyncExternalStore(chat.subscribe, chat.get, chat.get); - return { - messages: s.messages, - isLoading: s.isLoading, - error: undefined, - sendMessage: vi.fn(), - stop: vi.fn(), - reload: vi.fn(), - clear: vi.fn(), - setMessages: vi.fn(), - }; - }, - }; -}); -vi.mock('@object-ui/plugin-chatbot/core', async (importOriginal) => ({ - ...(await importOriginal()), - useAgents: () => ({ - agents: [{ name: 'build', label: 'Builder', capabilities: ['build'] }], - isLoading: false, - loading: false, - error: undefined, - refetch: vi.fn(), - }), -})); - -vi.mock('../../hooks/useChatConversation', async (importOriginal) => ({ - ...(await importOriginal>()), - useChatConversation: () => ({ conversationId: 'conv-hcpl', initialMessages: [] }), -})); -vi.mock('@object-ui/auth', async (importOriginal) => ({ - ...(await importOriginal>()), - useAuth: () => ({ user: { id: 'u1' } }), -})); -vi.mock('../../layout/AiUsageIndicator', () => ({ AiUsageIndicator: () => null })); - -vi.mock('sonner', () => ({ - toast: { warning: vi.fn(), error: vi.fn(), success: vi.fn(), info: vi.fn(), message: vi.fn(), dismiss: vi.fn() }, - Toaster: () => null, -})); -vi.mock('./packages-io', async (importOriginal) => { - const actual = await importOriginal>(); - return { - ...actual, - fetchPackages: vi.fn(async () => [{ id: PACKAGE_ID, name: PACKAGE_ID, writable: true, namespace: 'hcpl' }]), - }; -}); -vi.mock('@object-ui/react', async (importOriginal) => { - const actual = await importOriginal>(); - const adapter = { getClient: () => ({ packages: { discardDrafts: sdk.discardDrafts } }) }; - return { ...actual, useAdapter: () => adapter }; -}); -vi.mock('../../components/SuggestedBindingsPanel', () => ({ SuggestedBindingsPanel: () => null })); -vi.mock('../metadata-admin/AccessExplainPanel', () => ({ AccessExplainPanel: () => null })); -vi.mock('../../preview/DraftChangesPanel', () => ({ - DraftChangesPanel: ({ open, posture }: { open: boolean; posture?: string }) => ( -
- ), -})); - -import { uiMessagesToChatMessages } from '@object-ui/plugin-chatbot'; -import { I18nProvider } from '@object-ui/i18n'; -// The console's preview and authoring code loads `@objectstack/lint` lazily; -// warmed here so its first load is paid at import, not inside a test's clock. -import '@objectstack/lint'; -import '@object-ui/plugin-detail'; -import { StudioDesignSurface } from './StudioDesignSurface'; -import { StudioPillarRedirect } from './StudioPillarRedirect'; -import { subscribeMetadataRefresh } from '../../assistant/assistantBus'; - -window.matchMedia = ((query: string) => ({ - matches: false, - media: query, - onchange: null, - addEventListener: () => {}, - removeEventListener: () => {}, - addListener: () => {}, - removeListener: () => {}, - dispatchEvent: () => false, -})) as unknown as typeof window.matchMedia; -(globalThis as unknown as { ResizeObserver: unknown }).ResizeObserver = - (globalThis as unknown as { ResizeObserver?: unknown }).ResizeObserver ?? - class { - observe() {} - unobserve() {} - disconnect() {} - }; - -/** What `_drafts` answers: the package's pending drafts, server-side. */ -let serverDrafts: Array> = []; -/** How many `_drafts` reads the page sent. */ -let draftReads = 0; -/** What the package's published object list answers (the Data pillar's rail). */ -let objectRows: Array> = []; - -function json(body: unknown) { - return new Response(JSON.stringify(body), { status: 200, headers: { 'content-type': 'application/json' } }); -} - -// ── The producer's envelopes (objectstack-ai/cloud#2924) ────────────────── - -const BORROWING_ROW = { - type: 'object', - name: 'hcpl_borrowing', - label: '借阅记录', - packageId: PACKAGE_ID, - updatedAt: null, - updatedBy: 'u1', -}; - -/** The 确认修改 card: `apply_edit` answered `changes_proposed`, draft posture. */ -const PROPOSED = { - status: 'changes_proposed', - applied: false, - changes: [{ verb: 'add_field', object: 'hcpl_borrowing', field: 'renew_count', type: 'number', details: '续借次数 · 默认 0 · 不必填' }], - summary: '这个应用已上线,有 12 条记录在用。改动先存为草稿;画布和右侧属性里能看到效果,你在「变更」里核对后再发布。', - posture: { mode: 'draft', liveRecords: 12 }, - primaryAction: 'save_draft', -}; - -/** Its confirm replay: one draft staged, the applied card's title and lines. */ -const DRAFTED = { - status: 'drafted', - kind: 'edit', - drafted: [{ type: 'object', name: 'hcpl_borrowing' }], - packageId: PACKAGE_ID, - summary: '已起草 1 处改动', - posture: { mode: 'draft', liveRecords: 12 }, - draftState: { pending: 1, items: [{ type: 'object', name: 'hcpl_borrowing' }], others: 0 }, - existingRows: [{ object: 'hcpl_borrowing', field: 'renew_count', label: '续借次数', rows: 12 }], - appliedCard: { title: '已存为草稿 · 1 项未发布', lines: ['已有 12 条记录的续借次数为空', '核对:结构 ✓'] }, -}; - -const THREAD = [ - { id: 'm-user-1', role: 'user', parts: [{ type: 'text', text: '给借阅记录加一个续借次数字段' }] }, - { - id: 'm-asst-1', - role: 'assistant', - parts: [{ type: 'tool-apply_edit', toolCallId: 'call_1', state: 'output-available', input: {}, output: JSON.stringify(PROPOSED) }], - }, - { id: 'm-user-2', role: 'user', parts: [{ type: 'text', text: '存为草稿' }] }, - { - id: 'm-asst-2', - role: 'assistant', - parts: [ - { type: 'tool-apply_edit', toolCallId: 'replay_t2_0', state: 'output-available', input: {}, output: JSON.stringify(DRAFTED) }, - { type: 'text', text: '已存为草稿。' }, - ], - }, -]; - -beforeEach(() => { - serverDrafts = [BORROWING_ROW]; - draftReads = 0; - objectRows = []; - sdk.discardDrafts.mockReset(); - chat.set({ messages: uiMessagesToChatMessages(THREAD as never, { isStreaming: false }), isLoading: false }); - window.sessionStorage.clear(); - vi.stubGlobal( - 'fetch', - vi.fn(async (input: unknown) => { - const url = String(input); - if (url === DRAFTS) { - draftReads += 1; - return json({ drafts: serverDrafts }); - } - if (url === `/api/v1/meta/object?package=${encodeURIComponent(PACKAGE_ID)}`) return json(objectRows); - // objectstack#36904 — the object designer reads its one object's layers. - const layers = /^\/api\/v1\/meta\/object\/([^/?]+)\/layers/.exec(url); - const row = layers && objectRows.find((r) => r.name === decodeURIComponent(layers[1])); - if (row) return json({ code: row, overlay: null, overlayScope: null, effective: row }); - return json([]); - }) as unknown as typeof fetch, - ); -}); - -afterEach(() => { - cleanup(); - vi.unstubAllGlobals(); -}); - -/** objectstack#36904 — where the old Studio home (`/data`) lands: the package's object list. */ -const OBJECT_LIST = `/studio/${PACKAGE_ID}/metadata/object?package=${encodeURIComponent(PACKAGE_ID)}`; - -function LocationProbe(): React.ReactElement { - const location = useLocation(); - return
{`${location.pathname}${location.search}`}
; -} - -function renderStudio(entry = `/studio/${PACKAGE_ID}/data?surface=object%3Ahcpl_borrowing`) { - return render( - - - - } /> - } /> - - , - ); -} - -async function drain() { - for (let i = 0; i < 5; i++) await new Promise((r) => setTimeout(r, 0)); -} - -/** Mount the surface with one pending draft and the applied card on screen. */ -async function mountWithAppliedCard() { - const view = renderStudio(); - const card = await screen.findByTestId('applied-card'); - await waitFor(() => expect(screen.getByTestId('studio-changes-count')).toHaveTextContent('1')); - await act(drain); - return { view, card }; -} - -describe('the Studio copilot\'s applied card opens the 变更 drawer in place (objectui#12894)', () => { - it('查看变更并发布 opens the drawer to review, with no remount and no change of pillar', async () => { - const { view, card } = await mountWithAppliedCard(); - const surfaceRoot = view.container.lastElementChild; - const location = screen.getByTestId('location').textContent; - expect(screen.getByTestId('draft-changes-panel')).toHaveAttribute('data-open', 'false'); - - fireEvent.click(within(card).getByTestId('applied-card-review')); - - await waitFor(() => expect(screen.getByTestId('draft-changes-panel')).toHaveAttribute('data-open', 'true')); - expect(screen.getByTestId('draft-changes-panel')).toHaveAttribute('data-posture', 'review'); - // The param was read and dropped: the URL is the one the user was on. - await waitFor(() => expect(screen.getByTestId('location').textContent).toBe(location)); - // In place: the same surface tree, and the conversation is still there. - expect(view.container.lastElementChild).toBe(surfaceRoot); - expect(screen.getByTestId('applied-card')).toBe(card); - }); - - it('arriving with ?changes=review (the full-page chat\'s link) opens the drawer, then drops the param', async () => { - renderStudio(`/studio/${PACKAGE_ID}/data?changes=review`); - await waitFor(() => expect(screen.getByTestId('draft-changes-panel')).toHaveAttribute('data-open', 'true')); - expect(screen.getByTestId('draft-changes-panel')).toHaveAttribute('data-posture', 'review'); - await waitFor(() => expect(screen.getByTestId('location').textContent).toBe(OBJECT_LIST)); - }); - - // objectstack#36502 — the link printed before the Interfaces pillar retired - // still opens the drawer: the redirect to the Data pillar keeps `?changes=`. - it('an old /interfaces?changes=review link lands on the Data pillar with the drawer open', async () => { - renderStudio(`/studio/${PACKAGE_ID}/interfaces?changes=review`); - await waitFor(() => expect(screen.getByTestId('draft-changes-panel')).toHaveAttribute('data-open', 'true')); - expect(screen.getByTestId('draft-changes-panel')).toHaveAttribute('data-posture', 'review'); - await waitFor(() => expect(screen.getByTestId('location').textContent).toBe(OBJECT_LIST)); - }); - - it('CONTROL: a value the surface does not know opens nothing, and is dropped all the same', async () => { - renderStudio(`/studio/${PACKAGE_ID}/data?changes=publish`); - await waitFor(() => expect(screen.getByTestId('location').textContent).toBe(OBJECT_LIST)); - await act(drain); - expect(screen.getByTestId('draft-changes-panel')).toHaveAttribute('data-open', 'false'); - }); -}); - -describe('the Studio copilot\'s composer (objectui#12725 Target item 4)', () => { - it('zh: the placeholder reads「问问数据,或让我改改这个应用…」, and the chip names the item in view', async () => { - objectRows = [{ name: 'hcpl_borrowing', label: '借阅记录' }]; - render( - - - - } /> - } /> - - - , - ); - const slot = await screen.findByTestId('studio-slot-copilot'); - const composer = await within(slot).findByRole('textbox'); - expect(composer).toHaveAttribute('placeholder', '问问数据,或让我改改这个应用…'); - // The chip `plugin-chatbot` declares (`surfaceContextLabel`), naming the - // item the URL has open — objectstack#34725: 「正在看:借阅记录 · 记录」, - // the object's label and the view on screen, never the internal name. - const chip = within(slot).getByTestId('surface-context-chip'); - await waitFor(() => expect(chip).toHaveTextContent('正在看:借阅记录 · 记录')); - expect(chip).not.toHaveTextContent('hcpl_borrowing'); - }); -}); - -describe('the Studio copilot\'s applied card undoes through discard-drafts (objectui#12894)', () => { - it('撤销 discards the card\'s package and the 变更 badge re-reads its ledger', async () => { - sdk.discardDrafts.mockImplementation(async () => { - serverDrafts = []; - return { - success: true, - discardedCount: 1, - failedCount: 0, - discarded: [{ type: 'object', name: 'hcpl_borrowing' }], - failed: [], - }; - }); - const { card } = await mountWithAppliedCard(); - const readsBefore = draftReads; - - fireEvent.click(within(card).getByTestId('applied-card-discard')); - - await waitFor(() => expect(within(card).getByTestId('applied-card-discarded')).toBeInTheDocument()); - expect(sdk.discardDrafts).toHaveBeenCalledTimes(1); - expect(sdk.discardDrafts).toHaveBeenCalledWith(PACKAGE_ID); - await waitFor(() => expect(screen.queryByTestId('studio-changes-count')).toBeNull()); - expect(draftReads).toBeGreaterThan(readsBefore); - }); - - it('a draft the server could not drop is a failure the card shows with the server\'s reason; the pulse still goes out', async () => { - sdk.discardDrafts.mockImplementation(async () => ({ - success: false, - discardedCount: 0, - failedCount: 1, - discarded: [], - failed: [{ type: 'object', name: 'hcpl_borrowing', error: 'draft is locked by a publish in progress' }], - })); - const { card } = await mountWithAppliedCard(); - let pulses = 0; - const unsubscribe = subscribeMetadataRefresh(() => { - pulses += 1; - }); - try { - fireEvent.click(within(card).getByTestId('applied-card-discard')); - - const failed = await within(card).findByTestId('applied-card-discard-failed'); - expect(failed).toHaveTextContent('object/hcpl_borrowing: draft is locked by a publish in progress'); - expect(within(card).queryByTestId('applied-card-discarded')).toBeNull(); - expect(pulses).toBe(1); - expect(screen.getByTestId('studio-changes-count')).toHaveTextContent('1'); - } finally { - unsubscribe(); - } - }); -}); diff --git a/ui/packages/app-shell/src/views/studio-design/StudioDesignSurface.copilotDraftBadge-12725.test.tsx b/ui/packages/app-shell/src/views/studio-design/StudioDesignSurface.copilotDraftBadge-12725.test.tsx deleted file mode 100644 index c898fe9bcd6..00000000000 --- a/ui/packages/app-shell/src/views/studio-design/StudioDesignSurface.copilotDraftBadge-12725.test.tsx +++ /dev/null @@ -1,441 +0,0 @@ -// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. - -/** - * objectui#12725, phase 5 (Target item 5) — the top bar's 变更 badge counts the - * copilot's drafts the moment they land, with no reload and no navigation. - * - * The chain, end to end: - * - the copilot's tool stages the draft server-side and answers - * `status: 'drafted'` (objectstack-ai/cloud#2924; its envelope's own - * `draftState` is read through `listDrafts` AFTER the write); - * - the copilot's chat host, `ChatPane`, sees the result land in the stream - * and announces it on the assistant bus (`emitMetadataRefresh`); - * - the badge's source, `usePendingDrafts`, re-reads `_drafts` on that pulse. - * - * Before this phase the announcement waited for the turn to END: the badge - * stayed on the old count for as long as the agent kept narrating after the - * tool answered. These cases play the stream with the turn still running. - * - * Phase 6 adds the result phase 5 left out: a `status: 'published'` answer that - * is not a confirm-replay (cloud's in-turn auto-publish, which promotes every - * pending draft of the package) carries neither lifted field, and is announced - * through the chat package's own reader of the envelope. - * - * Real: the surface, its top bar, `usePendingDrafts`, the right slot, the - * Studio copilot (`StudioChatDock` → `StudioCopilotConversation` → - * `ChatPane`), and the chat package's own mapping of a tool part - * (`uiMessagesToChatMessages`), fed the producer's envelope shapes. Stubbed: - * `globalThis.fetch` (the server), the chat transport (`useObjectChat` plays a - * scripted stream), the agent catalog, the conversation lookup, and the chat - * body (`ChatbotEnhanced`), which no assertion reads. - */ - -import '@testing-library/jest-dom/vitest'; -import * as React from 'react'; -import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; -import { act, cleanup, render, screen, waitFor } from '@testing-library/react'; -import { MemoryRouter, Route, Routes, useLocation } from 'react-router-dom'; - -const PACKAGE_ID = 'app.hcpl'; -const DRAFTS = `/api/v1/meta/_drafts?package=${encodeURIComponent(PACKAGE_ID)}`; - -/** The scripted chat stream the mocked transport serves. */ -const chat = vi.hoisted(() => { - type Snapshot = { messages: unknown[]; isLoading: boolean }; - let snapshot: Snapshot = { messages: [], isLoading: false }; - const listeners = new Set<() => void>(); - return { - get: (): Snapshot => snapshot, - subscribe(listener: () => void): () => void { - listeners.add(listener); - return () => { - listeners.delete(listener); - }; - }, - set(next: Snapshot): void { - snapshot = next; - for (const l of listeners) l(); - }, - }; -}); - -vi.mock('@object-ui/plugin-chatbot', async (importOriginal) => { - const actual = await importOriginal>(); - return { - ...actual, - useAiModels: () => ({ models: [], defaultModelId: undefined }), - ChatbotEnhanced: () =>
, - useObjectChat: () => { - const s = React.useSyncExternalStore(chat.subscribe, chat.get, chat.get); - return { - messages: s.messages, - isLoading: s.isLoading, - error: undefined, - sendMessage: vi.fn(), - stop: vi.fn(), - reload: vi.fn(), - clear: vi.fn(), - setMessages: vi.fn(), - }; - }, - }; -}); -vi.mock('@object-ui/plugin-chatbot/core', async (importOriginal) => ({ - ...(await importOriginal()), - useAgents: () => ({ - agents: [{ name: 'metadata_assistant', label: 'Build', capabilities: ['build'] }], - isLoading: false, - loading: false, - error: undefined, - refetch: vi.fn(), - }), -})); - -vi.mock('../../hooks/useChatConversation', async (importOriginal) => ({ - ...(await importOriginal>()), - useChatConversation: () => ({ conversationId: 'conv-hcpl', initialMessages: [] }), -})); -vi.mock('@object-ui/auth', async (importOriginal) => ({ - ...(await importOriginal>()), - useAuth: () => ({ user: { id: 'u1' } }), -})); -vi.mock('../../layout/AiUsageIndicator', () => ({ AiUsageIndicator: () => null })); - -vi.mock('sonner', () => ({ - toast: { warning: vi.fn(), error: vi.fn(), success: vi.fn(), info: vi.fn(), message: vi.fn(), dismiss: vi.fn() }, - Toaster: () => null, -})); -vi.mock('./packages-io', async (importOriginal) => { - const actual = await importOriginal>(); - return { - ...actual, - fetchPackages: vi.fn(async () => [{ id: PACKAGE_ID, name: PACKAGE_ID, writable: true, namespace: 'hcpl' }]), - }; -}); -vi.mock('@object-ui/react', async (importOriginal) => { - const actual = await importOriginal>(); - return { ...actual, useAdapter: () => ({}) }; -}); -vi.mock('../../components/SuggestedBindingsPanel', () => ({ SuggestedBindingsPanel: () => null })); -vi.mock('../metadata-admin/AccessExplainPanel', () => ({ AccessExplainPanel: () => null })); -vi.mock('../../preview/DraftChangesPanel', () => ({ DraftChangesPanel: () => null })); - -import { uiMessagesToChatMessages } from '@object-ui/plugin-chatbot'; -// The console's preview and authoring code loads `@objectstack/lint` lazily; -// warmed here so its first load is paid at import, not inside a test's clock. -import '@objectstack/lint'; -// objectstack#36900 — the surface mounts the command palette, which reaches the -// record preview's `lazy()` detail entry: its first load is paid at collection too. -import '@object-ui/plugin-detail'; -import { StudioDesignSurface } from './StudioDesignSurface'; -import { StudioPillarRedirect } from './StudioPillarRedirect'; -import { subscribeMetadataRefresh } from '../../assistant/assistantBus'; - -window.matchMedia = ((query: string) => ({ - matches: false, - media: query, - onchange: null, - addEventListener: () => {}, - removeEventListener: () => {}, - addListener: () => {}, - removeListener: () => {}, - dispatchEvent: () => false, -})) as unknown as typeof window.matchMedia; -(globalThis as unknown as { ResizeObserver: unknown }).ResizeObserver = - (globalThis as unknown as { ResizeObserver?: unknown }).ResizeObserver ?? - class { - observe() {} - unobserve() {} - disconnect() {} - }; - -/** What `_drafts` answers: the package's pending drafts, server-side. */ -let serverDrafts: Array> = []; -/** How many `_drafts` reads the page sent. */ -let draftReads = 0; - -function json(body: unknown) { - return new Response(JSON.stringify(body), { status: 200, headers: { 'content-type': 'application/json' } }); -} - -beforeEach(() => { - serverDrafts = []; - draftReads = 0; - chat.set({ messages: [], isLoading: false }); - window.sessionStorage.clear(); - vi.stubGlobal( - 'fetch', - vi.fn(async (input: unknown) => { - const url = String(input); - if (url === DRAFTS) { - draftReads += 1; - return json({ drafts: serverDrafts }); - } - return json([]); - }) as unknown as typeof fetch, - ); -}); - -afterEach(() => { - cleanup(); - vi.unstubAllGlobals(); -}); - -// ── The producer's envelopes (objectstack-ai/cloud#2924, cloud `f9e45145`) ── - -const DRAFTED_ROWS = [ - { type: 'object', name: 'hcpl_borrowing', label: '借阅记录', packageId: PACKAGE_ID, updatedAt: null, updatedBy: 'u1' }, - { type: 'view', name: 'hcpl_borrowing.board', label: '借阅看板', packageId: PACKAGE_ID, updatedAt: null, updatedBy: 'u1' }, -]; - -/** `apply_edit` on a live app with records: saved as a draft, `kind: 'edit'`. */ -const APPLY_EDIT_DRAFTED = { - status: 'drafted', - kind: 'edit', - drafted: [ - { type: 'object', name: 'hcpl_borrowing' }, - { type: 'view', name: 'hcpl_borrowing.board' }, - ], - failed: [], - packageId: PACKAGE_ID, - summary: 'Add 续借次数 to 借阅记录 and show it on the board cards', - posture: { mode: 'draft', liveRecords: 12 }, - draftState: { pending: 2, items: [{ type: 'object', name: 'hcpl_borrowing' }, { type: 'view', name: 'hcpl_borrowing.board' }], others: 0 }, - note: 'SAVED AS A STUDIO DRAFT — NOT LIVE.', -}; - -/** A 确认修改 confirm-replay's result: the single-item draft envelope under a `replay_` id. */ -const REPLAY_DRAFTED = { - status: 'drafted', - type: 'object', - name: 'hcpl_borrowing', - packageId: PACKAGE_ID, - summary: 'Add 续借次数', - changedKeys: ['fields.renew_count'], - posture: { mode: 'draft', liveRecords: 12 }, - draftState: { pending: 1, items: [{ type: 'object', name: 'hcpl_borrowing' }], others: 0 }, -}; - -/** - * The same `apply_edit` where the environment publishes AI changes in the turn - * (cloud `maybeAutoPublish`): the package's drafts are promoted, ALL of them, - * and the envelope is rewritten to `status: 'published'`. Not a replay, so the - * chat lifts neither `draftReview` nor `replayOutcome` from it. - */ -const APPLY_EDIT_PUBLISHED = { - ...APPLY_EDIT_DRAFTED, - status: 'published', - note: 'LIVE. Published in-turn — the table/field/view now exists and is visible to users; no separate Publish step is needed. You may tell the user it is created and live.', -}; - -/** A read tool's answer: no authoring envelope. */ -const READ_RESULT = { name: 'hcpl_borrowing', label: '借阅记录', fields: { title: { type: 'text' } } }; - -const USER_TURN = { id: 'm-user-1', role: 'user', parts: [{ type: 'text', text: '给借阅记录加一个续借次数字段' }] }; - -function toolPart(toolName: string, toolCallId: string, output: unknown) { - return { type: `tool-${toolName}`, toolCallId, state: 'output-available', input: {}, output: JSON.stringify(output) }; -} - -/** Play the stream: the thread so far, mapped by the chat package's own reader. */ -function play(uiMessages: unknown[], isLoading: boolean): void { - act(() => { - chat.set({ - messages: uiMessagesToChatMessages(uiMessages as never, { isStreaming: isLoading }), - isLoading, - }); - }); -} - -function LocationProbe(): React.ReactElement { - const location = useLocation(); - return
{`${location.pathname}${location.search}`}
; -} - -function renderStudio() { - return render( - - - - } /> - - , - ); -} - -async function drain() { - for (let i = 0; i < 5; i++) await new Promise((r) => setTimeout(r, 0)); -} - -/** Mount the surface with an empty ledger and the copilot's chat on screen. */ -async function mountQuiet() { - const view = renderStudio(); - await screen.findByTestId('copilot-chat-body'); - await act(drain); - expect(screen.queryByTestId('studio-changes-count')).toBeNull(); - return view; -} - -describe('the 变更 badge counts the copilot\'s drafts the moment they land (objectui#12725)', () => { - it('a drafted apply_edit result re-reads the badge while the agent is still answering, in place', async () => { - const view = await mountQuiet(); - const surfaceRoot = view.container.lastElementChild; - const location = screen.getByTestId('location').textContent; - - // The turn starts: the agent is thinking, nothing is staged yet. - play([USER_TURN, { id: 'm-asst-1', role: 'assistant', parts: [{ type: 'text', text: '好的,' }] }], true); - await act(drain); - const readsBeforeLanding = draftReads; - - // The tool stages both drafts server-side, then answers `drafted` — and the - // agent goes on narrating: the turn is still running. - serverDrafts = DRAFTED_ROWS; - play( - [ - USER_TURN, - { - id: 'm-asst-1', - role: 'assistant', - parts: [ - { type: 'text', text: '好的,' }, - toolPart('apply_edit', 'call_apply_edit_1', APPLY_EDIT_DRAFTED), - { type: 'text', text: '已存为草稿' }, - ], - }, - ], - true, - ); - - await waitFor(() => expect(screen.getByTestId('studio-changes-count')).toHaveTextContent('2')); - expect(draftReads).toBeGreaterThan(readsBeforeLanding); - // No reload: the same surface tree; no navigation: the same location. - expect(view.container.lastElementChild).toBe(surfaceRoot); - expect(screen.getByTestId('location').textContent).toBe(location); - }); - - it('a 确认修改 replay that saved the change as a draft re-reads the badge as it lands', async () => { - await mountQuiet(); - serverDrafts = DRAFTED_ROWS.slice(0, 1); - play( - [ - USER_TURN, - { - id: 'm-asst-2', - role: 'assistant', - parts: [toolPart('apply_edit', 'replay_t2_0', REPLAY_DRAFTED), { type: 'text', text: '已存为草稿。' }], - }, - ], - true, - ); - await waitFor(() => expect(screen.getByTestId('studio-changes-count')).toHaveTextContent('1')); - }); - - it('announces each result once: later chunks and the turn\'s end send no second pulse for it', async () => { - await mountQuiet(); - let pulses = 0; - const unsubscribe = subscribeMetadataRefresh(() => { - pulses += 1; - }); - try { - serverDrafts = DRAFTED_ROWS; - const landed = { - id: 'm-asst-3', - role: 'assistant', - parts: [toolPart('apply_edit', 'call_apply_edit_3', APPLY_EDIT_DRAFTED)], - }; - play([USER_TURN, landed], true); - await act(drain); - expect(pulses).toBe(1); - - // More narration streams in, then the turn ends. - play([USER_TURN, { ...landed, parts: [...landed.parts, { type: 'text', text: '已存为草稿,' }] }], true); - play([USER_TURN, { ...landed, parts: [...landed.parts, { type: 'text', text: '已存为草稿,请在「变更」里发布。' }] }], false); - await act(drain); - expect(pulses).toBe(1); - await waitFor(() => expect(screen.getByTestId('studio-changes-count')).toHaveTextContent('2')); - } finally { - unsubscribe(); - } - }); - - it('a published result that is not a replay (in-turn auto-publish) re-reads the badge as it lands', async () => { - // Two drafts are pending when the turn starts. - serverDrafts = DRAFTED_ROWS; - renderStudio(); - await screen.findByTestId('copilot-chat-body'); - await waitFor(() => expect(screen.getByTestId('studio-changes-count')).toHaveTextContent('2')); - let pulses = 0; - const unsubscribe = subscribeMetadataRefresh(() => { - pulses += 1; - }); - try { - // The tool publishes in the turn, which promotes every pending draft. - serverDrafts = []; - play( - [USER_TURN, { id: 'm-asst-5', role: 'assistant', parts: [toolPart('apply_edit', 'call_apply_edit_5', APPLY_EDIT_PUBLISHED)] }], - true, - ); - await waitFor(() => expect(screen.queryByTestId('studio-changes-count')).toBeNull()); - expect(pulses).toBe(1); - } finally { - unsubscribe(); - } - }); - - it('CONTROL: a tool result with no authoring envelope sends no pulse', async () => { - await mountQuiet(); - let pulses = 0; - const unsubscribe = subscribeMetadataRefresh(() => { - pulses += 1; - }); - try { - play( - [USER_TURN, { id: 'm-asst-4', role: 'assistant', parts: [toolPart('get_metadata', 'call_read_4', READ_RESULT)] }], - true, - ); - play( - [ - USER_TURN, - { - id: 'm-asst-4', - role: 'assistant', - parts: [toolPart('get_metadata', 'call_read_4', READ_RESULT), { type: 'text', text: '它有一个标题字段。' }], - }, - ], - false, - ); - await act(drain); - // (The chat's own pending-drafts bar re-reads on the turn's idle edge, as - // it always has; that read is its own, not an announcement.) - expect(pulses).toBe(0); - expect(screen.queryByTestId('studio-changes-count')).toBeNull(); - } finally { - unsubscribe(); - } - }); - - it('a drafted result already in the thread when the copilot mounts is history, not a landing', async () => { - chat.set({ - messages: uiMessagesToChatMessages( - [USER_TURN, { id: 'm-asst-old', role: 'assistant', parts: [toolPart('apply_edit', 'call_old', APPLY_EDIT_DRAFTED)] }] as never, - { isStreaming: false }, - ), - isLoading: false, - }); - let pulses = 0; - const unsubscribe = subscribeMetadataRefresh(() => { - pulses += 1; - }); - try { - serverDrafts = DRAFTED_ROWS; - renderStudio(); - await screen.findByTestId('copilot-chat-body'); - await act(drain); - expect(pulses).toBe(0); - // The badge reads the ledger on its own mount, as it always has. - await waitFor(() => expect(screen.getByTestId('studio-changes-count')).toHaveTextContent('2')); - } finally { - unsubscribe(); - } - }); -}); diff --git a/ui/packages/app-shell/src/views/studio-design/StudioDesignSurface.createAppAccessibleName.test.tsx b/ui/packages/app-shell/src/views/studio-design/StudioDesignSurface.createAppAccessibleName.test.tsx index 542a03793fb..ce22a03d27b 100644 --- a/ui/packages/app-shell/src/views/studio-design/StudioDesignSurface.createAppAccessibleName.test.tsx +++ b/ui/packages/app-shell/src/views/studio-design/StudioDesignSurface.createAppAccessibleName.test.tsx @@ -73,7 +73,6 @@ vi.mock('./packages-io', async (importOriginal) => { }); // Docks irrelevant to the names under test — keep the render light. -vi.mock('./StudioAiCopilot', () => ({ StudioChatDock: () => null })); vi.mock('../../preview/DraftChangesPanel', () => ({ DraftChangesPanel: () => null })); import { StudioDesignSurface } from './StudioDesignSurface'; diff --git a/ui/packages/app-shell/src/views/studio-design/StudioDesignSurface.createTaken-26917.test.tsx b/ui/packages/app-shell/src/views/studio-design/StudioDesignSurface.createTaken-26917.test.tsx index 635299657d2..6069d8de2d7 100644 --- a/ui/packages/app-shell/src/views/studio-design/StudioDesignSurface.createTaken-26917.test.tsx +++ b/ui/packages/app-shell/src/views/studio-design/StudioDesignSurface.createTaken-26917.test.tsx @@ -121,7 +121,6 @@ vi.mock('@object-ui/react', async (importOriginal) => { vi.mock('sonner', () => ({ toast: { success: vi.fn(), error: vi.fn(), message: vi.fn() } })); vi.mock('../../components/SuggestedBindingsPanel', () => ({ SuggestedBindingsPanel: () => null })); vi.mock('../metadata-admin/AccessExplainPanel', () => ({ AccessExplainPanel: () => null })); -vi.mock('./StudioAiCopilot', () => ({ StudioChatDock: () => null })); vi.mock('../../preview/DraftChangesPanel', () => ({ DraftChangesPanel: () => null })); import { StudioDesignSurface } from './StudioDesignSurface'; diff --git a/ui/packages/app-shell/src/views/studio-design/StudioDesignSurface.customizePublish-28562.test.tsx b/ui/packages/app-shell/src/views/studio-design/StudioDesignSurface.customizePublish-28562.test.tsx index 812798c3050..b2697b7b902 100644 --- a/ui/packages/app-shell/src/views/studio-design/StudioDesignSurface.customizePublish-28562.test.tsx +++ b/ui/packages/app-shell/src/views/studio-design/StudioDesignSurface.customizePublish-28562.test.tsx @@ -85,7 +85,6 @@ vi.mock('sonner', () => ({ })); vi.mock('../../components/SuggestedBindingsPanel', () => ({ SuggestedBindingsPanel: () => null })); vi.mock('../metadata-admin/AccessExplainPanel', () => ({ AccessExplainPanel: () => null })); -vi.mock('./StudioAiCopilot', () => ({ StudioChatDock: () => null })); /** objectstack#29691 — the sheet's "saved to" line, in the sheet's own words. */ function SheetSavedTo({ baseLabel }: { baseLabel: string }) { const { t } = useObjectTranslation(); diff --git a/ui/packages/app-shell/src/views/studio-design/StudioDesignSurface.desktopHint-11795.test.tsx b/ui/packages/app-shell/src/views/studio-design/StudioDesignSurface.desktopHint-11795.test.tsx index c9e1de70f47..e1a661abd84 100644 --- a/ui/packages/app-shell/src/views/studio-design/StudioDesignSurface.desktopHint-11795.test.tsx +++ b/ui/packages/app-shell/src/views/studio-design/StudioDesignSurface.desktopHint-11795.test.tsx @@ -50,7 +50,6 @@ vi.mock('@object-ui/react', async (importOriginal) => { vi.mock('../../components/SuggestedBindingsPanel', () => ({ SuggestedBindingsPanel: () => null })); vi.mock('../metadata-admin/AccessExplainPanel', () => ({ AccessExplainPanel: () => null })); -vi.mock('./StudioAiCopilot', () => ({ StudioChatDock: () => null })); vi.mock('../../preview/DraftChangesPanel', () => ({ DraftChangesPanel: () => null })); import { StudioDesignSurface } from './StudioDesignSurface'; diff --git a/ui/packages/app-shell/src/views/studio-design/StudioDesignSurface.emptyStates-12514.test.tsx b/ui/packages/app-shell/src/views/studio-design/StudioDesignSurface.emptyStates-12514.test.tsx index f2a83042083..9043aa138d3 100644 --- a/ui/packages/app-shell/src/views/studio-design/StudioDesignSurface.emptyStates-12514.test.tsx +++ b/ui/packages/app-shell/src/views/studio-design/StudioDesignSurface.emptyStates-12514.test.tsx @@ -58,7 +58,6 @@ vi.mock('@object-ui/react', async (importOriginal) => { vi.mock('sonner', () => ({ toast: { success: vi.fn(), error: vi.fn() } })); vi.mock('../../components/SuggestedBindingsPanel', () => ({ SuggestedBindingsPanel: () => null })); vi.mock('../metadata-admin/AccessExplainPanel', () => ({ AccessExplainPanel: () => null })); -vi.mock('./StudioAiCopilot', () => ({ StudioChatDock: () => null })); import { AutomationsPillar } from './StudioDesignSurface'; import { createEmptyDataSource, failOnAbsorbedFetchError } from './__tests__/emptyDataSource'; diff --git a/ui/packages/app-shell/src/views/studio-design/StudioDesignSurface.entryReadsOnce-11797.test.tsx b/ui/packages/app-shell/src/views/studio-design/StudioDesignSurface.entryReadsOnce-11797.test.tsx index dde19dfe9f1..c16ea816d49 100644 --- a/ui/packages/app-shell/src/views/studio-design/StudioDesignSurface.entryReadsOnce-11797.test.tsx +++ b/ui/packages/app-shell/src/views/studio-design/StudioDesignSurface.entryReadsOnce-11797.test.tsx @@ -57,7 +57,6 @@ vi.mock('@object-ui/react', async (importOriginal) => { vi.mock('../../components/SuggestedBindingsPanel', () => ({ SuggestedBindingsPanel: () => null })); vi.mock('../metadata-admin/AccessExplainPanel', () => ({ AccessExplainPanel: () => null })); -vi.mock('./StudioAiCopilot', () => ({ StudioChatDock: () => null })); vi.mock('../../preview/DraftChangesPanel', () => ({ DraftChangesPanel: () => null })); // The console's preview and authoring code loads `@objectstack/lint` lazily; diff --git a/ui/packages/app-shell/src/views/studio-design/StudioDesignSurface.flowAutosave-34818.test.tsx b/ui/packages/app-shell/src/views/studio-design/StudioDesignSurface.flowAutosave-34818.test.tsx index f29c37bc54b..1f55305be7b 100644 --- a/ui/packages/app-shell/src/views/studio-design/StudioDesignSurface.flowAutosave-34818.test.tsx +++ b/ui/packages/app-shell/src/views/studio-design/StudioDesignSurface.flowAutosave-34818.test.tsx @@ -198,7 +198,7 @@ describe('the Debug section takes the Configuration aside’s place (#34818 item function SlotHost({ children }: { children: React.ReactNode }) { const [target, setTarget] = React.useState(null); const handle = React.useMemo( - () => ({ propsTarget: target, mode: 'props' as const, claimProps: () => () => {}, showProps }), + () => ({ propsTarget: target, claimProps: () => () => {}, showProps }), [target], ); return ( diff --git a/ui/packages/app-shell/src/views/studio-design/StudioDesignSurface.graphite-37455.test.tsx b/ui/packages/app-shell/src/views/studio-design/StudioDesignSurface.graphite-37455.test.tsx index dbe9f5f4e50..13b2d8d2fcf 100644 --- a/ui/packages/app-shell/src/views/studio-design/StudioDesignSurface.graphite-37455.test.tsx +++ b/ui/packages/app-shell/src/views/studio-design/StudioDesignSurface.graphite-37455.test.tsx @@ -64,14 +64,6 @@ vi.mock('@object-ui/react', async (importOriginal) => { vi.mock('../../components/SuggestedBindingsPanel', () => ({ SuggestedBindingsPanel: () => null })); vi.mock('../metadata-admin/AccessExplainPanel', () => ({ AccessExplainPanel: () => null })); vi.mock('../../preview/DraftChangesPanel', () => ({ DraftChangesPanel: () => null })); -vi.mock('./StudioAiCopilot', () => ({ - StudioChatDock: ({ onStatusChange }: { onStatusChange?: (s: { available: boolean; planPendingCount: number }) => void }) => { - React.useEffect(() => { - onStatusChange?.({ available: true, planPendingCount: 0 }); - }, [onStatusChange]); - return
conversation
; - }, -})); // The source loads `@objectstack/lint` lazily; paid here, at collection, not // inside a case's clock (check:test-source-alias). @@ -157,7 +149,7 @@ describe('a non-default app theme does not tint Studio (objectstack#37455)', () expect(root.getPropertyValue('--primary').trim()).not.toBe(STUDIO_ACCENT_HSL.light); }); - it('the surface\'s root carries Studio\'s accent: its header, the page and its buttons sit under it', async () => { + it('the surface\'s root carries Studio\'s accent: its header and the page sit under it', async () => { render(); const header = await screen.findByTestId('studio-shell-header'); const scope = header.closest(ACCENT_SCOPE); @@ -165,7 +157,6 @@ describe('a non-default app theme does not tint Studio (objectstack#37455)', () expect(scope).not.toBe(document.body); expect(carriesAccent(scope as Element)).toBe(true); expect(scope).toContainElement(screen.getByTestId('studio-pillars-host')); - expect(scope).toContainElement(await screen.findByTestId('topbar-ai-assistant')); }); it('a portalled surface (the command palette) is outside the root and still under the accent, on body', async () => { diff --git a/ui/packages/app-shell/src/views/studio-design/StudioDesignSurface.heldDataCreate-26845.test.tsx b/ui/packages/app-shell/src/views/studio-design/StudioDesignSurface.heldDataCreate-26845.test.tsx index 0ac1edf143b..cbfeae99f0d 100644 --- a/ui/packages/app-shell/src/views/studio-design/StudioDesignSurface.heldDataCreate-26845.test.tsx +++ b/ui/packages/app-shell/src/views/studio-design/StudioDesignSurface.heldDataCreate-26845.test.tsx @@ -81,7 +81,6 @@ vi.mock('@object-ui/react', async (importOriginal) => { return { ...mod, useAdapter: () => dataSource }; }); -vi.mock('./StudioAiCopilot', () => ({ StudioChatDock: () => null })); // Stands in for the Pending changes sheet: its security block asks the host to // open the object (or permission set) a draft names, through the surface channel. vi.mock('../../preview/DraftChangesPanel', async () => { diff --git a/ui/packages/app-shell/src/views/studio-design/StudioDesignSurface.heldDataLeave-26705.test.tsx b/ui/packages/app-shell/src/views/studio-design/StudioDesignSurface.heldDataLeave-26705.test.tsx index 39194980702..b25abaa1a96 100644 --- a/ui/packages/app-shell/src/views/studio-design/StudioDesignSurface.heldDataLeave-26705.test.tsx +++ b/ui/packages/app-shell/src/views/studio-design/StudioDesignSurface.heldDataLeave-26705.test.tsx @@ -69,7 +69,6 @@ vi.mock('@object-ui/react', async (importOriginal) => { return { ...mod, useAdapter: () => dataSource }; }); -vi.mock('./StudioAiCopilot', () => ({ StudioChatDock: () => null })); vi.mock('../../preview/DraftChangesPanel', () => ({ DraftChangesPanel: () => null })); // The source under test reaches a dynamic import of `@objectstack/lint`: its first diff --git a/ui/packages/app-shell/src/views/studio-design/StudioDesignSurface.heldFlowCreate-26845.test.tsx b/ui/packages/app-shell/src/views/studio-design/StudioDesignSurface.heldFlowCreate-26845.test.tsx index 3b56fde81d7..2a722695545 100644 --- a/ui/packages/app-shell/src/views/studio-design/StudioDesignSurface.heldFlowCreate-26845.test.tsx +++ b/ui/packages/app-shell/src/views/studio-design/StudioDesignSurface.heldFlowCreate-26845.test.tsx @@ -80,7 +80,6 @@ vi.mock('@object-ui/react', async (importOriginal) => { return { ...mod, useAdapter: () => dataSource }; }); -vi.mock('./StudioAiCopilot', () => ({ StudioChatDock: () => null })); // Stands in for the Pending changes sheet: its security block asks the host to // open the object a draft names, through the surface channel. vi.mock('../../preview/DraftChangesPanel', async () => { diff --git a/ui/packages/app-shell/src/views/studio-design/StudioDesignSurface.heldFlowLeave-26705.test.tsx b/ui/packages/app-shell/src/views/studio-design/StudioDesignSurface.heldFlowLeave-26705.test.tsx index 675c7f0b789..0e8f90bf7f7 100644 --- a/ui/packages/app-shell/src/views/studio-design/StudioDesignSurface.heldFlowLeave-26705.test.tsx +++ b/ui/packages/app-shell/src/views/studio-design/StudioDesignSurface.heldFlowLeave-26705.test.tsx @@ -83,7 +83,6 @@ vi.mock('@object-ui/react', async (importOriginal) => { return { ...mod, useAdapter: () => dataSource }; }); -vi.mock('./StudioAiCopilot', () => ({ StudioChatDock: () => null })); // Stands in for the Pending changes sheet: its entries ask the host to open the // flow a draft names, through the surface channel (objectstack#36903). vi.mock('../../preview/DraftChangesPanel', async () => { diff --git a/ui/packages/app-shell/src/views/studio-design/StudioDesignSurface.heldPublish-11786.test.tsx b/ui/packages/app-shell/src/views/studio-design/StudioDesignSurface.heldPublish-11786.test.tsx index aba7de32794..a4ed9880514 100644 --- a/ui/packages/app-shell/src/views/studio-design/StudioDesignSurface.heldPublish-11786.test.tsx +++ b/ui/packages/app-shell/src/views/studio-design/StudioDesignSurface.heldPublish-11786.test.tsx @@ -77,7 +77,6 @@ vi.mock('@object-ui/react', async (importOriginal) => { return { ...mod, useAdapter: () => dataSource }; }); -vi.mock('./StudioAiCopilot', () => ({ StudioChatDock: () => null })); vi.mock('../../preview/DraftChangesPanel', () => ({ DraftChangesPanel: (props: Record) => { diff --git a/ui/packages/app-shell/src/views/studio-design/StudioDesignSurface.homeLoop-12513.test.tsx b/ui/packages/app-shell/src/views/studio-design/StudioDesignSurface.homeLoop-12513.test.tsx index ba2228d7158..4296574a701 100644 --- a/ui/packages/app-shell/src/views/studio-design/StudioDesignSurface.homeLoop-12513.test.tsx +++ b/ui/packages/app-shell/src/views/studio-design/StudioDesignSurface.homeLoop-12513.test.tsx @@ -86,7 +86,6 @@ const mockClient = vi.hoisted(() => ({ /** What the surface handed the pending-changes sheet, last render. */ const panel = vi.hoisted(() => ({ props: null as null | Record })); -const chatDock = vi.hoisted(() => ({ mounts: 0 })); vi.mock('../metadata-admin/useMetadata', async (importOriginal) => { const mod = await importOriginal(); @@ -107,13 +106,6 @@ vi.mock('@object-ui/react', async (importOriginal) => { return { ...mod, useAdapter: () => dataSource }; }); -vi.mock('./StudioAiCopilot', () => ({ - StudioChatDock: () => { - chatDock.mounts += 1; - return null; - }, -})); - vi.mock('../../preview/DraftChangesPanel', () => ({ DraftChangesPanel: (props: Record) => { panel.props = props; @@ -189,7 +181,6 @@ beforeEach(() => { server.publishedByRef.length = 0; server.packageBatches.length = 0; panel.props = null; - chatDock.mounts = 0; for (const fn of Object.values(mockClient)) (fn as unknown as { mockClear: () => void }).mockClear(); // Two packaged flows on the read-only showcase, and the clone, which names no package. seed(flow('showcase_urgent_task_alert', 'Urgent task alert', SHOWCASE)); diff --git a/ui/packages/app-shell/src/views/studio-design/StudioDesignSurface.interfacesRetired-36502.test.tsx b/ui/packages/app-shell/src/views/studio-design/StudioDesignSurface.interfacesRetired-36502.test.tsx index 4a48e76ad49..cadee904bae 100644 --- a/ui/packages/app-shell/src/views/studio-design/StudioDesignSurface.interfacesRetired-36502.test.tsx +++ b/ui/packages/app-shell/src/views/studio-design/StudioDesignSurface.interfacesRetired-36502.test.tsx @@ -116,7 +116,6 @@ vi.mock('sonner', () => ({ vi.mock('../../components/SuggestedBindingsPanel', () => ({ SuggestedBindingsPanel: () => null })); vi.mock('../metadata-admin/AccessExplainPanel', () => ({ AccessExplainPanel: () => null })); -vi.mock('./StudioAiCopilot', () => ({ StudioChatDock: () => null })); vi.mock('../../preview/DraftChangesPanel', () => ({ DraftChangesPanel: () => null })); import { StudioDesignSurface } from './StudioDesignSurface'; diff --git a/ui/packages/app-shell/src/views/studio-design/StudioDesignSurface.itemDraftLine-12725.test.tsx b/ui/packages/app-shell/src/views/studio-design/StudioDesignSurface.itemDraftLine-12725.test.tsx index 84945ff36b3..78b0f7f41ac 100644 --- a/ui/packages/app-shell/src/views/studio-design/StudioDesignSurface.itemDraftLine-12725.test.tsx +++ b/ui/packages/app-shell/src/views/studio-design/StudioDesignSurface.itemDraftLine-12725.test.tsx @@ -94,7 +94,6 @@ vi.mock('@object-ui/react', async (importOriginal) => { }); vi.mock('../../components/SuggestedBindingsPanel', () => ({ SuggestedBindingsPanel: () => null })); vi.mock('../metadata-admin/AccessExplainPanel', () => ({ AccessExplainPanel: () => null })); -vi.mock('./StudioAiCopilot', () => ({ StudioChatDock: () => null })); vi.mock('../../preview/DraftChangesPanel', () => ({ DraftChangesPanel: ({ onPublish }: { onPublish?: () => void | Promise }) => (
@@ -238,7 +234,6 @@ function AreaItemOpen({ publishNonce={editor.publishNonce} onDraftSaved={editor.onDraftSaved} onHeldEditChange={editor.onHeldEditChange} - onSurfaceLabelChange={editor.onSurfaceLabelChange} />
); @@ -252,7 +247,6 @@ function AreaItemOpen({ readOnly={host.readOnly} publishNonce={editor.publishNonce} onDraftSaved={editor.onDraftSaved ? () => editor.onDraftSaved?.({ type, name }) : undefined} - onSurfaceLabelChange={editor.onSurfaceLabelChange} /> ); } @@ -419,13 +413,6 @@ export interface StudioMetadataAreaProps { * (`studioScope.ts`), so its host is read-only to the list's create. */ orgScope?: boolean; - /** - * objectstack#36905, objectstack#36904, objectstack#36903 — told the open - * designer page's item label (the permission set's, the object's, the - * flow's), for the copilot's chip, as a - * pillar tells it. - */ - onSurfaceLabelChange?: (surface: StudioSurfaceLabel | null) => void; /** objectstack#36904, objectstack#36903 — handed to the object and flow designers (`AreaEditorProps`). */ onHeldEditChange?: (clause: string | null) => void; onReviewChanges?: () => void; @@ -439,7 +426,6 @@ export function StudioMetadataArea({ publishRefusalFor, orgScope = false, onHeldEditChange, - onSurfaceLabelChange, onReviewChanges, }: StudioMetadataAreaProps): React.ReactElement { const { pathname, search } = useLocation(); @@ -480,7 +466,6 @@ export function StudioMetadataArea({ publishRefusalFor, orgScope, onHeldEditChange, - onSurfaceLabelChange, onReviewChanges, }; diff --git a/ui/packages/app-shell/src/views/studio-design/StudioPackageMenu-37139.test.tsx b/ui/packages/app-shell/src/views/studio-design/StudioPackageMenu-37139.test.tsx index 2c6a18471f2..1fcc0f6e937 100644 --- a/ui/packages/app-shell/src/views/studio-design/StudioPackageMenu-37139.test.tsx +++ b/ui/packages/app-shell/src/views/studio-design/StudioPackageMenu-37139.test.tsx @@ -64,7 +64,6 @@ vi.mock('sonner', () => ({ })); vi.mock('../../components/SuggestedBindingsPanel', () => ({ SuggestedBindingsPanel: () => null })); vi.mock('../metadata-admin/AccessExplainPanel', () => ({ AccessExplainPanel: () => null })); -vi.mock('./StudioAiCopilot', () => ({ StudioChatDock: () => null })); vi.mock('../../preview/DraftChangesPanel', () => ({ DraftChangesPanel: () => null })); import { toast } from 'sonner'; diff --git a/ui/packages/app-shell/src/views/studio-design/StudioPackageOverview-37454.test.tsx b/ui/packages/app-shell/src/views/studio-design/StudioPackageOverview-37454.test.tsx index fcf8a569d74..f2de9ea6492 100644 --- a/ui/packages/app-shell/src/views/studio-design/StudioPackageOverview-37454.test.tsx +++ b/ui/packages/app-shell/src/views/studio-design/StudioPackageOverview-37454.test.tsx @@ -59,7 +59,6 @@ vi.mock('sonner', () => ({ })); vi.mock('../../components/SuggestedBindingsPanel', () => ({ SuggestedBindingsPanel: () => null })); vi.mock('../metadata-admin/AccessExplainPanel', () => ({ AccessExplainPanel: () => null })); -vi.mock('./StudioAiCopilot', () => ({ StudioChatDock: () => null })); /** Each mounted panel's latest props: the top bar's sheet, and the Pending tab's (`embedded`). */ const panels: { sheet: Record | null; embedded: Record | null } = { sheet: null, embedded: null }; diff --git a/ui/packages/app-shell/src/views/studio-design/StudioPermissionSetPage.tsx b/ui/packages/app-shell/src/views/studio-design/StudioPermissionSetPage.tsx index 3ac18e32a8c..a90b1dd3fd8 100644 --- a/ui/packages/app-shell/src/views/studio-design/StudioPermissionSetPage.tsx +++ b/ui/packages/app-shell/src/views/studio-design/StudioPermissionSetPage.tsx @@ -60,7 +60,6 @@ import { StudioReadOnlyLink } from './StudioPillarKit.js'; import { StudioAiDraftNotice } from './StudioAiDraftNotice.js'; import { isAgentDraftSurface } from './StudioDraftMark.js'; import type { StudioItemStatus } from './StudioItemHeader.js'; -import type { StudioSurfaceLabel } from './StudioAiCopilot.js'; import { customizationPairBaseOf } from './StudioRailCustomizations.js'; import { fetchListedPackageManifests } from './packages-io.js'; import { useMetadataRefreshNonce } from './useMetadataRefreshNonce.js'; @@ -87,8 +86,6 @@ export interface StudioPermissionSetPageProps { publishNonce?: number; /** Told when a save left a draft, so the top bar's pending count follows it. */ onDraftSaved?: () => void; - /** objectstack#35018 — the set's label for the copilot's chip: 「正在看:权限 · 组织成员」. */ - onSurfaceLabelChange?: (surface: StudioSurfaceLabel | null) => void; } /** What the page reads of the package's sets: their labels, which are published, which hold a draft. */ @@ -104,7 +101,6 @@ export function StudioPermissionSetPage({ readOnly = false, publishNonce = 0, onDraftSaved, - onSurfaceLabelChange, }: StudioPermissionSetPageProps): React.ReactElement { const client = useMetadataClient(); const locale = useMetadataLocale(); @@ -150,25 +146,6 @@ export function StudioPermissionSetPage({ }; }, [client, packageId, publishNonce, metadataRefreshNonce, readNonce]); - // objectstack#35018 — the copilot's chip reads the pillar's word and the - // set's label, never the type word or the machine name. Keyed on primitives, - // the callback read through a ref; cleared on unmount. - const reportLabelRef = React.useRef(onSurfaceLabelChange); - React.useEffect(() => { - reportLabelRef.current = onSurfaceLabelChange; - }); - const setLabel = read?.sets.find((p) => p.name === name)?.label; - const chipLabel = setLabel ? `${t('engine.studio.copilot.subject.access', locale)} · ${setLabel}` : null; - React.useEffect(() => { - reportLabelRef.current?.(chipLabel ? { type: 'permission', name, label: chipLabel } : null); - }, [name, chipLabel]); - React.useEffect( - () => () => { - reportLabelRef.current?.(null); - }, - [], - ); - // Bumped by a discard and a rollback: the matrix re-reads as it does after a // publish, since in each what it holds is gone. const [rereadNonce, setRereadNonce] = React.useState(0); diff --git a/ui/packages/app-shell/src/views/studio-design/StudioRightSlot.tsx b/ui/packages/app-shell/src/views/studio-design/StudioRightSlot.tsx index 6aa88bb917a..8b0333ae8ef 100644 --- a/ui/packages/app-shell/src/views/studio-design/StudioRightSlot.tsx +++ b/ui/packages/app-shell/src/views/studio-design/StudioRightSlot.tsx @@ -2,82 +2,41 @@ /** * StudioRightSlot — the one right-hand slot of the Studio design surface - * (objectui#12725, the maintainer's 「按「右栏二选一」定稿」): it shows EITHER the - * open item's properties OR the AI copilot, never both, and never beside a + * (objectui#12725): it shows the open item's properties, never beside a * second right-hand panel. * - * - objectstack#34725 — ONE header row, the console drawer's: on the left a - * segmented 属性 | AI 助手 switch (`⌘.` / `Ctrl+.` does the same, - * `matchStudioSlotShortcut`); on the right, while the copilot shows, - * History, the in-place widen (objectstack#34610) and Close. The top bar's - * robot opens and closes the slot as the console's robot opens its drawer. - * - Its width is resizable from the left edge within 320–560 px, and each - * pane keeps its own (objectstack#35061: properties 360, copilot 420 by default, - * `useStudioSlotWidth`); under `md` it overlays the page at its own width. + * - objectstack#34725 — ONE header row: the title on the left, Close on the + * right. The title row's panel icon (and `⌘.` / `Ctrl+.`, + * `matchStudioSlotShortcut`) opens and closes it. + * - Its width is resizable from the left edge within 320–560 px (360 by + * default, `useStudioSlotWidth`); under `md` it overlays the page at its own + * width. * - Properties are a portal target: a pillar that hosts its inspector here * claims the slot through `useStudioRightSlot` (`studioRightSlotState.ts`) - * and renders into - * `propsTarget`. A pillar that claims nothing keeps its own aside, and the - * slot shows the copilot alone (the header reads as a title, not a switch). - * - objectstack#35018 — while the properties show, the header's 属性 | AI 助手 - * switch is the one way back to the conversation: the 40 px 「AI 助手 / - * 回到对话 →」 strip that also stood at the slot's foot is gone. - * - The copilot segment says how many items the copilot proposed await the - * author's confirmation (「N 项待确认」, objectstack#25943). - * - Both bodies stay MOUNTED and are hidden by mode: a turn the copilot is - * streaming survives a look at the properties, and a pillar's portal target - * never disappears under an open editor. - * - * The copilot itself (`StudioChatDock`) is passed in as `copilot`, so its agent, - * conversation and requests are untouched by the move; it reports whether the - * agent catalog serves one (`copilotAvailable`) and the slot draws nothing for - * a copilot that is not there. + * and renders into `propsTarget`. A pillar that claims nothing keeps its own + * aside, and the slot draws nothing. + * - The body stays MOUNTED and is hidden with the slot, so a pillar's portal + * target never disappears under an open editor. */ import * as React from 'react'; -import { History, Maximize2, Minimize2, SlidersHorizontal, Sparkles, X } from 'lucide-react'; +import { SlidersHorizontal, X } from 'lucide-react'; import { Button, cn } from '@object-ui/components'; -import { useObjectTranslation } from '@object-ui/i18n'; -import { t, tFormat } from '../metadata-admin/i18n.js'; +import { t } from '../metadata-admin/i18n.js'; import { STUDIO_SLOT_MAX_WIDTH, STUDIO_SLOT_MIN_WIDTH, useStudioSlotWidth, - type StudioSlotMode, } from './studioRightSlotState.js'; export interface StudioRightSlotProps { - /** Whether the slot is shown (the top bar's toggle). */ + /** Whether the slot is shown (the title row's toggle). */ open: boolean; - /** The mode the slot shows; the caller has already folded in what exists. */ - mode: StudioSlotMode; - onModeChange: (mode: StudioSlotMode) => void; - /** A pillar has claimed the properties half. */ + /** A pillar has claimed the properties. */ hasProps: boolean; - /** The agent catalog serves a copilot (reported by `copilot`). */ - copilotAvailable: boolean; - /** - * objectui#11666 / objectstack#25943 — how many items the copilot proposed - * await the author's confirmation; 0 when none. - */ - planPendingCount: number; - /** The copilot body (`StudioChatDock`). Always mounted, hidden by mode. */ - copilot: React.ReactNode; /** Callback ref for the properties portal target. */ propsTargetRef: (el: HTMLElement | null) => void; - /** A width in px while the copilot is widened in place (objectstack#34610); `undefined` otherwise. */ - wideWidth?: number; - /** - * objectstack#34610 / objectstack#34725 — whether the copilot is widened in - * place, and the header control that widens and narrows it (absent: no - * control). Drawn while the copilot shows, never in the phone overlay. - */ - wide?: boolean; - onWideChange?: (wide: boolean) => void; - /** objectstack#34725 — the copilot's conversation history is open over it; the header's History button toggles it. */ - historyOpen?: boolean; - onHistoryOpenChange?: (open: boolean) => void; - /** objectstack#34725 — the header's Close: hides the slot, as the top bar's robot does. */ + /** objectstack#34725 — the header's Close: hides the slot, as the title row's toggle does. */ onClose?: () => void; /** Under `md`: the slot overlays the page instead of reflowing it. */ overlay?: boolean; @@ -87,54 +46,16 @@ export interface StudioRightSlotProps { export function StudioRightSlot({ open, - mode, - onModeChange, hasProps, - copilotAvailable, - planPendingCount, - copilot, propsTargetRef, - wideWidth, - wide = false, - onWideChange, - historyOpen = false, - onHistoryOpenChange, onClose, overlay = false, onOverlayDismiss, locale, }: StudioRightSlotProps): React.ReactElement { - const { t: tc } = useObjectTranslation(); - const slotWidth = useStudioSlotWidth(mode); - const shown = open && (hasProps || copilotAvailable); - const showsProps = mode === 'props'; - const switchable = hasProps && copilotAvailable; - const planPending = planPendingCount > 0; - const planMarkerId = React.useId(); - const pendingText = planPending - ? tFormat('engine.studio.slot.pendingCount', locale, { count: planPendingCount }) - : ''; - const planMarker = planPending ? ( - - ) : null; - const copilotShown = !showsProps && copilotAvailable; - const widened = Boolean(wideWidth) && !showsProps; - const wideLabel = wide - ? tc('console.ai.dock.restore', { defaultValue: 'Restore side panel' }) - : tc('console.ai.dock.expand', { defaultValue: 'Expand' }); - const historyLabel = t('engine.studio.slot.history', locale); + const slotWidth = useStudioSlotWidth(); + const shown = open && hasProps; const headerButton = 'h-7 w-7 text-muted-foreground hover:text-foreground'; - const segment = (value: StudioSlotMode) => - cn( - 'inline-flex h-7 items-center justify-center gap-1.5 rounded-md px-3 text-[13px] transition-colors', - mode === value ? 'bg-background font-medium text-foreground shadow-sm' : 'text-muted-foreground hover:text-foreground', - ); return ( <> {overlay && shown && ( @@ -142,10 +63,9 @@ export function StudioRightSlot({ )} ); diff --git a/ui/packages/app-shell/src/views/studio-design/__tests__/studioCopilotSlotBody-12725.test.tsx b/ui/packages/app-shell/src/views/studio-design/__tests__/studioCopilotSlotBody-12725.test.tsx deleted file mode 100644 index 31f69d0b116..00000000000 --- a/ui/packages/app-shell/src/views/studio-design/__tests__/studioCopilotSlotBody-12725.test.tsx +++ /dev/null @@ -1,209 +0,0 @@ -/** - * ObjectUI - * Copyright (c) 2024-present ObjectStack Inc. - * - * ADR-0057 P3c follow-up — issue #2477 item 2: the Studio copilot's collapse is - * remembered under a key SCOPED to Studio, so it never fights the console - * dock's own state. - * - * objectui#12725 re-points this file. The copilot moved from the shared dock - * chrome (`useChatDockState` with Studio's own keys, which this file pinned) - * into the surface's right slot: the slot owns showing, hiding and the width, - * and keeps its shown state under the same Studio key (pinned in - * `StudioDesignSurface.rightSlot-12725.test.tsx`, beside the console key it - * must not touch). What stays here is the copilot's side of that move: - * - it no longer drives the dock state hook at all, so the console dock's - * remembered expanded state and width are the console's alone; - * - it reports to the slot whether the catalog serves it, and nothing on unmount; - * - an empty catalog renders nothing. - * - * objectstack#34725 — the copilot draws no title bar of its own (the slot's one - * header row holds History, widen and Close); behind History it lays the - * conversation list, Share and the usage reading over the chat. - * - * objectstack#36969 — the copilot is the build agent, so it is available only - * where the catalog serves `build` (alias-aware). Where in-app building is - * closed the catalog keeps `ask`: the copilot renders nothing and reports no - * copilot, so the slot shows the properties alone, as for an empty catalog. - */ -import '@testing-library/jest-dom/vitest'; -import { describe, it, expect, beforeEach, vi } from 'vitest'; -import { fireEvent, render, screen } from '@testing-library/react'; -import { MemoryRouter } from 'react-router-dom'; -import type { ChatDockOptions } from '../../../layout/ChatDock'; -import { - DOCK_EXPANDED_STORAGE_KEY, - DOCK_STUDIO_EXPANDED_STORAGE_KEY, - DOCK_WIDTH_STORAGE_KEY, -} from '../../../layout/chatDockState'; - -// Every option object anything hands to useChatDockState, in order. -const dockOptions: Array = []; - -vi.mock('../../../layout/ChatDock', async (importOriginal) => { - const actual = await importOriginal>(); - return { - ...actual, - useChatDockState: (options?: ChatDockOptions) => { - dockOptions.push(options); - return (actual.useChatDockState as (o?: ChatDockOptions) => unknown)(options); - }, - }; -}); - -const catalog = vi.hoisted(() => ({ agents: [{ name: 'build' }] as Array<{ name: string }> })); -vi.mock('@object-ui/plugin-chatbot/core', async (importOriginal) => ({ - ...(await importOriginal()), - useAgents: () => ({ agents: catalog.agents, isLoading: false, error: null }), -})); -// Partial — the module also feeds the metadata client factory, which imports -// `createAuthenticatedFetch` from it at load time. -vi.mock('@object-ui/auth', async (importOriginal) => ({ - ...(await importOriginal>()), - useAuth: () => ({ user: { id: 'u1' } }), -})); -// The usage probe reads the network; it is the console's, unchanged here. -vi.mock('../../../layout/AiUsageIndicator', () => ({ AiUsageIndicator: () => null })); -vi.mock('../../../console/ai/AiChatPage', () => ({ - ChatPane: () => null, - resolveApiBase: () => '/api/v1', -})); -// Every option object the copilot hands the conversation hook, in order. -const conversationArgs = vi.hoisted(() => [] as Array>); -vi.mock('../../../hooks/useChatConversation', () => ({ - useChatConversation: (args: Record) => { - conversationArgs.push(args); - return { conversationId: (args.activeId as string | undefined) ?? 'c1', initialMessages: [] }; - }, -})); -// The list reads the network; a stub stands for its two callbacks. -const sidebarProps = vi.hoisted(() => ({ last: null as null | Record })); -vi.mock('../../../console/ai/ConversationsSidebar', () => ({ - ConversationsSidebar: (props: { - activeConversationId?: string; - onSelectConversation?: (c: { id: string }) => void; - onNewConversation?: () => void; - }) => { - sidebarProps.last = props as Record; - return ( -
-
- ); - }, -})); - -import { StudioChatDock, type StudioCopilotStatus } from '../StudioAiCopilot'; - -beforeEach(() => { - dockOptions.length = 0; - conversationArgs.length = 0; - sidebarProps.last = null; - catalog.agents = [{ name: 'build' }]; - window.sessionStorage.clear(); - window.localStorage.clear(); -}); - -function mountCopilot(onStatusChange: (s: StudioCopilotStatus) => void) { - return render( - - - , - ); -} - -describe('StudioChatDock as the right slot\'s copilot (#2477 item 2, objectui#12725)', () => { - it('drives no dock state: the console dock\'s remembered state and width stay the console\'s', () => { - window.sessionStorage.setItem(DOCK_EXPANDED_STORAGE_KEY, '0'); - window.localStorage.setItem(DOCK_WIDTH_STORAGE_KEY, '512'); - mountCopilot(() => {}); - expect(dockOptions).toEqual([]); - expect(window.sessionStorage.getItem(DOCK_EXPANDED_STORAGE_KEY)).toBe('0'); - expect(window.localStorage.getItem(DOCK_WIDTH_STORAGE_KEY)).toBe('512'); - expect(window.sessionStorage.getItem(DOCK_STUDIO_EXPANDED_STORAGE_KEY)).toBeNull(); - }); - - it('reports itself available to the slot, and unavailable on unmount', () => { - const reports: StudioCopilotStatus[] = []; - const { unmount } = mountCopilot((s) => reports.push(s)); - expect(reports.at(-1)).toEqual({ available: true, planPendingCount: 0 }); - // objectstack#34725 — the widen control is the slot header's, not the copilot's. - expect(screen.queryByTestId('studio-copilot-maximize')).toBeNull(); - expect(screen.queryByTestId('studio-copilot-history')).toBeNull(); - unmount(); - expect(reports.at(-1)).toEqual({ available: false, planPendingCount: 0 }); - }); - - it('an empty catalog renders nothing and reports no copilot', () => { - catalog.agents = []; - const reports: StudioCopilotStatus[] = []; - const { container } = mountCopilot((s) => reports.push(s)); - expect(container).toBeEmptyDOMElement(); - expect(reports.at(-1)).toEqual({ available: false, planPendingCount: 0 }); - }); -}); - -describe('StudioChatDock is available only where the catalog serves build (objectstack#36969)', () => { - it.each([ - ['in-app building closed: `ask` served, `build` not', [{ name: 'ask' }]], - ['another agent only', [{ name: 'custom_helper' }]], - ])('%s: renders nothing and reports no copilot', (_case, agents) => { - catalog.agents = agents; - const reports: StudioCopilotStatus[] = []; - const { container } = mountCopilot((s) => reports.push(s)); - expect(container).toBeEmptyDOMElement(); - expect(reports.at(-1)).toEqual({ available: false, planPendingCount: 0 }); - expect(conversationArgs).toEqual([]); - }); - - it.each([ - ['build', [{ name: 'build' }, { name: 'ask' }]], - ['its legacy id', [{ name: 'metadata_assistant' }, { name: 'data_chat' }]], - ])('regression: with %s served it reports itself available and opens the build thread', (_served, agents) => { - catalog.agents = agents; - const reports: StudioCopilotStatus[] = []; - mountCopilot((s) => reports.push(s)); - expect(reports.at(-1)).toEqual({ available: true, planPendingCount: 0 }); - expect(conversationArgs.at(-1)).toMatchObject({ scope: 'app:app.crm:build' }); - }); -}); - -describe('StudioChatDock history (objectstack#34725)', () => { - function mountWithHistory(onHistoryOpenChange = vi.fn(), historyOpen = true) { - const view = render( - - - , - ); - return { ...view, onHistoryOpenChange }; - } - - it('lays the list, Share and the usage reading over the chat while open', () => { - mountWithHistory(); - const history = screen.getByTestId('studio-copilot-history'); - expect(history).toContainElement(screen.getByTestId('stub-history-list')); - expect(screen.getByTestId('studio-copilot-share')).toBeEnabled(); - expect(screen.getByTestId('stub-history-list')).toHaveAttribute('data-active', 'c1'); - }); - - it('picking a row opens that conversation and closes the list', () => { - const { onHistoryOpenChange } = mountWithHistory(); - fireEvent.click(screen.getByTestId('stub-pick-c2')); - expect(onHistoryOpenChange).toHaveBeenLastCalledWith(false); - expect(conversationArgs.at(-1)).toMatchObject({ activeId: 'c2', forceNew: false }); - }); - - it('New chat asks for a fresh conversation and closes the list', () => { - const { onHistoryOpenChange } = mountWithHistory(); - fireEvent.click(screen.getByTestId('stub-new')); - expect(onHistoryOpenChange).toHaveBeenLastCalledWith(false); - expect(conversationArgs.at(-1)).toMatchObject({ forceNew: true }); - }); - - it('closed, the chat is all there is', () => { - mountWithHistory(vi.fn(), false); - expect(screen.queryByTestId('studio-copilot-history')).toBeNull(); - expect(screen.queryByTestId('studio-copilot-share')).toBeNull(); - }); -}); diff --git a/ui/packages/app-shell/src/views/studio-design/__tests__/studioCopilotWidenInPlace-34610.test.tsx b/ui/packages/app-shell/src/views/studio-design/__tests__/studioCopilotWidenInPlace-34610.test.tsx deleted file mode 100644 index 44ac4680e7b..00000000000 --- a/ui/packages/app-shell/src/views/studio-design/__tests__/studioCopilotWidenInPlace-34610.test.tsx +++ /dev/null @@ -1,97 +0,0 @@ -/** - * ObjectUI - * Copyright (c) 2024-present ObjectStack Inc. - * - * objectstack#34610 (ui ADR-0057 Amendment A3) — the Studio copilot's expand - * control widens its slot IN PLACE and the same control narrows it again; the - * Studio page stays where it is. objectstack#34725 moved the control into the - * slot's one header row, so the pin mounts the slot around the copilot. - * - * It used to open `/ai/build?package=PKG` (objectui#12842). After - * objectstack#34608 that address opens the console's drawer full window over - * Home, so pressing it lost the Studio page. - */ -import '@testing-library/jest-dom/vitest'; -import { describe, it, expect, beforeEach, vi } from 'vitest'; -import { fireEvent, render, screen } from '@testing-library/react'; -import { useState } from 'react'; -import { MemoryRouter, Route, Routes, useLocation } from 'react-router-dom'; - -vi.mock('@object-ui/plugin-chatbot/core', async (importOriginal) => ({ - ...(await importOriginal()), - useAgents: () => ({ agents: [{ name: 'build' }], isLoading: false, error: null }), -})); -// Partial — the module also feeds the metadata client factory, which imports -// `createAuthenticatedFetch` from it at load time. -vi.mock('@object-ui/auth', async (importOriginal) => ({ - ...(await importOriginal>()), - useAuth: () => ({ user: { id: 'u1' } }), -})); -// The usage probe reads the network; it is the console's, unchanged here. -vi.mock('../../../layout/AiUsageIndicator', () => ({ AiUsageIndicator: () => null })); -vi.mock('../../../console/ai/AiChatPage', () => ({ - ChatPane: () => null, - resolveApiBase: () => '/api/v1', -})); -vi.mock('../../../hooks/useChatConversation', () => ({ - useChatConversation: () => ({ conversationId: 'c1', initialMessages: [] }), -})); - -import { StudioChatDock } from '../StudioAiCopilot'; -import { StudioRightSlot } from '../StudioRightSlot'; - -function Where() { - const location = useLocation(); - return
{`${location.pathname}${location.search}`}
; -} - -function Slot() { - const [wide, setWide] = useState(false); - return ( - <> -
{String(wide)}
- {}} - hasProps={false} - copilotAvailable - planPendingCount={0} - propsTargetRef={() => {}} - wideWidth={wide ? 900 : undefined} - wide={wide} - onWideChange={setWide} - locale="en" - copilot={} - /> - - - ); -} - -beforeEach(() => { - window.sessionStorage.clear(); -}); - -describe("the Studio copilot's expand control (objectstack#34610)", () => { - it('widens the slot in place and narrows it again, never leaving the Studio page', () => { - render( - - - } /> - } /> - - , - ); - const button = screen.getByTestId('studio-copilot-maximize'); - expect(button).toHaveAttribute('aria-pressed', 'false'); - fireEvent.click(button); - expect(screen.getByTestId('slot-wide')).toHaveTextContent('true'); - expect(screen.getByTestId('studio-right-slot')).toHaveStyle({ width: '900px' }); - expect(screen.getByTestId('studio-copilot-maximize')).toHaveAttribute('aria-pressed', 'true'); - expect(screen.getByTestId('where')).toHaveTextContent('/studio/app.crm/interfaces?surface=nav_dash'); - expect(screen.queryByTestId('left-studio')).not.toBeInTheDocument(); - fireEvent.click(screen.getByTestId('studio-copilot-maximize')); - expect(screen.getByTestId('slot-wide')).toHaveTextContent('false'); - }); -}); diff --git a/ui/packages/app-shell/src/views/studio-design/__tests__/studioRightSlot-12725.test.tsx b/ui/packages/app-shell/src/views/studio-design/__tests__/studioRightSlot-12725.test.tsx index f15487d4f1b..097ef9895de 100644 --- a/ui/packages/app-shell/src/views/studio-design/__tests__/studioRightSlot-12725.test.tsx +++ b/ui/packages/app-shell/src/views/studio-design/__tests__/studioRightSlot-12725.test.tsx @@ -3,32 +3,28 @@ * Copyright (c) 2024-present ObjectStack Inc. * * objectui#12725 — the right slot's own rules, without mounting the surface: - * its width (objectstack#34725: the console drawer's 420 px, resizable), its `⌘.` chord, which Escape keydowns - * are not the canvas's, and the chrome's three shapes (a switch when both - * halves exist, a title when one does, nothing when none does). The surface's - * wiring is pinned in `StudioDesignSurface.rightSlot-12725.test.tsx`. + * its width (360 px by default, resizable), its `⌘.` chord, which Escape + * keydowns are not the canvas's, and its chrome (the properties' title and + * Close; nothing while no pillar claims it). The surface's wiring is pinned in + * `StudioDesignSurface.pillarsClaimSlot-12725.test.tsx`. */ import '@testing-library/jest-dom/vitest'; import * as React from 'react'; import { afterEach, describe, expect, it, vi } from 'vitest'; -import { cleanup, fireEvent, render, screen, within } from '@testing-library/react'; +import { cleanup, fireEvent, render, screen } from '@testing-library/react'; import { StudioRightSlot } from '../StudioRightSlot'; import { - STUDIO_SLOT_DEFAULT_WIDTHS, + STUDIO_SLOT_DEFAULT_WIDTH, STUDIO_SLOT_MAX_WIDTH, STUDIO_SLOT_MIN_WIDTH, - STUDIO_SLOT_SHARED_WIDTH_STORAGE_KEY, - STUDIO_SLOT_WIDTH_STORAGE_KEYS, + STUDIO_SLOT_RETIRED_WIDTH_STORAGE_KEYS, + STUDIO_SLOT_WIDTH_STORAGE_KEY, clampStudioSlotWidth, isSlotEscapeExempt, matchStudioSlotShortcut, } from '../studioRightSlotState'; -import { DOCK_DEFAULT_WIDTH, DOCK_KEYBOARD_STEP, DOCK_WIDTH_STORAGE_KEY } from '../../../layout/chatDockState'; +import { DOCK_KEYBOARD_STEP, DOCK_WIDTH_STORAGE_KEY } from '../../../layout/chatDockState'; import { t } from '../../metadata-admin/i18n'; -import { loadStudioCatalogue } from '@object-ui/i18n/namespaces/studio'; - -// The zh studio catalogue loads on demand; the zh case below reads it. -await loadStudioCatalogue('zh'); afterEach(() => { cleanup(); @@ -66,170 +62,71 @@ describe('isSlotEscapeExempt', () => { }); function renderSlot(props: Partial> = {}) { - const onModeChange = vi.fn(); - render( - } - propsTargetRef={() => {}} - locale="en" - {...props} - />, - ); - return { onModeChange, slot: screen.getByTestId('studio-right-slot') }; + render( {}} locale="en" {...props} />); + return { slot: screen.getByTestId('studio-right-slot') }; } describe('StudioRightSlot', () => { - // objectstack#34725 — the console drawer's default width, dragged or keyed - // wider from its left edge, remembered under the slot's own key. - it('is 420 px wide by default and resizes from its left edge, under its own key', () => { + it('is 360 px wide by default and resizes from its left edge, under its own key', () => { Object.defineProperty(window, 'innerWidth', { configurable: true, value: 1600 }); const { slot } = renderSlot(); - expect(DOCK_DEFAULT_WIDTH).toBe(420); - expect(slot).toHaveStyle({ width: '420px' }); + expect(STUDIO_SLOT_DEFAULT_WIDTH).toBe(360); + expect(slot).toHaveStyle({ width: '360px' }); const handle = screen.getByTestId('studio-slot-resize'); expect(handle).toHaveAttribute('role', 'separator'); + expect(handle).toHaveAttribute('aria-valuemin', '320'); + expect(handle).toHaveAttribute('aria-valuemax', '560'); fireEvent.keyDown(handle, { key: 'ArrowLeft' }); - expect(slot).toHaveStyle({ width: `${420 + DOCK_KEYBOARD_STEP}px` }); - expect(window.localStorage.getItem(STUDIO_SLOT_WIDTH_STORAGE_KEYS.copilot)).toBe(String(420 + DOCK_KEYBOARD_STEP)); + expect(slot).toHaveStyle({ width: `${360 + DOCK_KEYBOARD_STEP}px` }); + expect(window.localStorage.getItem(STUDIO_SLOT_WIDTH_STORAGE_KEY)).toBe(String(360 + DOCK_KEYBOARD_STEP)); expect(window.localStorage.getItem(DOCK_WIDTH_STORAGE_KEY)).toBeNull(); fireEvent.pointerDown(handle, { clientX: 1000 }); fireEvent.pointerMove(window, { clientX: 900 }); fireEvent.pointerUp(window, { clientX: 900 }); - expect(slot).toHaveStyle({ width: `${420 + DOCK_KEYBOARD_STEP + 100}px` }); + expect(slot).toHaveStyle({ width: `${360 + DOCK_KEYBOARD_STEP + 100}px` }); cleanup(); // Read back on the next mount; never so wide the canvas drops under 520 px. renderSlot(); - expect(screen.getByTestId('studio-right-slot')).toHaveStyle({ width: `${420 + DOCK_KEYBOARD_STEP + 100}px` }); + expect(screen.getByTestId('studio-right-slot')).toHaveStyle({ width: `${360 + DOCK_KEYBOARD_STEP + 100}px` }); cleanup(); Object.defineProperty(window, 'innerWidth', { configurable: true, value: 1000 }); - window.localStorage.setItem(STUDIO_SLOT_WIDTH_STORAGE_KEYS.copilot, '2000'); + window.localStorage.setItem(STUDIO_SLOT_WIDTH_STORAGE_KEY, '2000'); renderSlot(); expect(screen.getByTestId('studio-right-slot')).toHaveStyle({ width: `${1000 - 520}px` }); }); - it('switches with its segmented header when both halves exist', () => { - const { onModeChange, slot } = renderSlot(); - const [props, chat] = within(slot).getAllByRole('tab'); - expect(chat).toHaveAttribute('aria-selected', 'true'); - fireEvent.click(props); - expect(onModeChange).toHaveBeenLastCalledWith('props'); - }); - - it('hides the copilot while the properties show; the header switch leads back, with no strip at the foot', () => { - const { onModeChange } = renderSlot({ mode: 'props' }); - expect(screen.getByTestId('studio-slot-props')).toBeVisible(); - expect(screen.getByTestId('studio-slot-copilot')).not.toBeVisible(); - // Still mounted: a turn in flight survives a look at the properties. - expect(screen.getByTestId('copilot-body')).toBeInTheDocument(); - // objectstack#35018 — the 「AI 助手 / 回到对话 →」 strip repeated the switch; it is gone. - expect(screen.queryByTestId('studio-slot-copilot-strip')).toBeNull(); - expect(screen.queryByText(t('engine.studio.slot.backToChat', 'en'))).toBeNull(); - fireEvent.click(screen.getByTestId('studio-slot-tab-copilot')); - expect(onModeChange).toHaveBeenLastCalledWith('copilot'); - }); - - it('with one half, a title and no switch, no strip; with none, nothing shows', () => { - renderSlot({ hasProps: false }); - expect(screen.queryAllByRole('tab')).toHaveLength(0); - expect(screen.getByTestId('studio-slot-title')).toHaveTextContent(t('engine.studio.aiCopilot', 'en')); - cleanup(); - - renderSlot({ mode: 'props', copilotAvailable: false }); + it('shows the properties under their title, with Close; with nothing claimed, nothing shows', () => { + const onClose = vi.fn(); + const { slot } = renderSlot({ onClose }); + expect(slot).toBeVisible(); expect(screen.getByTestId('studio-slot-title')).toHaveTextContent(t('engine.studio.inspector.props', 'en')); - expect(screen.queryByTestId('studio-slot-copilot-strip')).toBeNull(); + expect(screen.queryAllByRole('tab')).toHaveLength(0); + fireEvent.click(screen.getByTestId('studio-slot-close')); + expect(onClose).toHaveBeenCalledTimes(1); cleanup(); - const { slot } = renderSlot({ hasProps: false, copilotAvailable: false }); - expect(slot).not.toBeVisible(); + expect(renderSlot({ hasProps: false }).slot).not.toBeVisible(); }); - it('hidden from the top bar, it keeps both halves mounted', () => { + it('hidden from the title row, it keeps the properties target mounted', () => { const { slot } = renderSlot({ open: false }); expect(slot).not.toBeVisible(); - expect(screen.getByTestId('copilot-body')).toBeInTheDocument(); + expect(screen.getByTestId('studio-slot-props')).toBeInTheDocument(); }); - it('on a phone it overlays the page, and a tap beside it dismisses it', () => { + it('on a phone it overlays the page outside the width range, and a tap beside it dismisses it', () => { const onOverlayDismiss = vi.fn(); const { slot } = renderSlot({ overlay: true, onOverlayDismiss }); expect(slot).toHaveClass('fixed', 'w-[min(420px,100vw)]'); + expect(slot.getAttribute('style')).toBeNull(); expect(screen.queryByTestId('studio-slot-resize')).toBeNull(); fireEvent.click(slot.previousElementSibling as HTMLElement); expect(onOverlayDismiss).toHaveBeenCalledTimes(1); }); - - // objectstack#25943 — 「N 项待确认」 on the copilot tab (objectstack#34725 named - // the panel 「AI 助手」; objectstack#35018 dropped the strip that repeated it). - it('zh: while the properties show, the copilot tab carries the 3 and no strip repeats it', () => { - renderSlot({ mode: 'props', planPendingCount: 3, locale: 'zh-CN' }); - expect(screen.queryByTestId('studio-slot-copilot-strip')).toBeNull(); - const copilotTab = screen.getAllByRole('tab')[1]; - expect(within(copilotTab).getByTestId('studio-slot-plan-pending')).toHaveTextContent('3'); - expect(copilotTab).toHaveAccessibleDescription('3 项待确认'); - }); }); -// objectstack#34725 — one header row, the console drawer's: the switch on the -// left; History, widen and Close on the right while the AI assistant shows. -describe('StudioRightSlot header (objectstack#34725)', () => { - it('zh: one row — 属性 | AI 助手, then 历史, widen and close', () => { - const onHistoryOpenChange = vi.fn(); - const onWideChange = vi.fn(); - const onClose = vi.fn(); - renderSlot({ locale: 'zh-CN', onHistoryOpenChange, onWideChange, onClose }); - const header = screen.getByTestId('studio-slot-header'); - const [props, chat] = within(header).getAllByRole('tab'); - expect(props).toHaveTextContent('属性'); - expect(chat).toHaveTextContent('AI 助手'); - const history = within(header).getByTestId('studio-slot-history'); - expect(history).toHaveTextContent('历史'); - expect(history).toHaveAttribute('aria-pressed', 'false'); - fireEvent.click(history); - expect(onHistoryOpenChange).toHaveBeenLastCalledWith(true); - fireEvent.click(within(header).getByTestId('studio-copilot-maximize')); - expect(onWideChange).toHaveBeenLastCalledWith(true); - const close = within(header).getByTestId('studio-slot-close'); - expect(close).toHaveAccessibleName(t('engine.studio.slot.collapse', 'zh-CN')); - fireEvent.click(close); - expect(onClose).toHaveBeenCalledTimes(1); - }); - - it('an open history reads as pressed and leads back to the chat', () => { - renderSlot({ historyOpen: true, onHistoryOpenChange: vi.fn() }); - const history = screen.getByTestId('studio-slot-history'); - expect(history).toHaveAttribute('aria-pressed', 'true'); - expect(history).toHaveAccessibleName(t('engine.studio.slot.backToChat', 'en')); - }); - - it('while the properties show, only Close; on a phone, no widen', () => { - renderSlot({ mode: 'props', onHistoryOpenChange: vi.fn(), onWideChange: vi.fn(), onClose: vi.fn() }); - expect(screen.queryByTestId('studio-slot-history')).toBeNull(); - expect(screen.queryByTestId('studio-copilot-maximize')).toBeNull(); - expect(screen.getByTestId('studio-slot-close')).toBeInTheDocument(); - cleanup(); - - renderSlot({ overlay: true, onHistoryOpenChange: vi.fn(), onWideChange: vi.fn() }); - expect(screen.getByTestId('studio-slot-history')).toBeInTheDocument(); - expect(screen.queryByTestId('studio-copilot-maximize')).toBeNull(); - }); - - it('widened, it takes the wide width and drops the resize handle', () => { - const { slot } = renderSlot({ wide: true, wideWidth: 900, onWideChange: vi.fn() }); - expect(slot).toHaveStyle({ width: '900px' }); - expect(screen.queryByTestId('studio-slot-resize')).toBeNull(); - expect(screen.getByTestId('studio-copilot-maximize')).toHaveAttribute('aria-pressed', 'true'); - }); -}); - -// objectstack#35061 item 4 — each pane keeps its own width, within 320–560. -describe('StudioRightSlot pane widths (objectstack#35061)', () => { +describe('StudioRightSlot width (objectstack#35061)', () => { it('clamps into 320–560 and keeps the canvas at least 520 px wide', () => { expect(STUDIO_SLOT_MIN_WIDTH).toBe(320); expect(STUDIO_SLOT_MAX_WIDTH).toBe(560); @@ -241,69 +138,11 @@ describe('StudioRightSlot pane widths (objectstack#35061)', () => { expect(clampStudioSlotWidth(900, 0)).toBe(560); }); - it('defaults the properties to 360 px and the copilot to 420 px', () => { - Object.defineProperty(window, 'innerWidth', { configurable: true, value: 1600 }); - expect(STUDIO_SLOT_DEFAULT_WIDTHS).toEqual({ props: 360, copilot: 420 }); - renderSlot({ mode: 'props' }); - expect(screen.getByTestId('studio-right-slot')).toHaveStyle({ width: '360px' }); - cleanup(); - renderSlot({ mode: 'copilot' }); - expect(screen.getByTestId('studio-right-slot')).toHaveStyle({ width: '420px' }); - }); - - it('remembers each pane apart across a remount, and a switch shows the other pane’s width', () => { + it('drops the width keys it used before it held the properties alone', () => { Object.defineProperty(window, 'innerWidth', { configurable: true, value: 1600 }); - const view = render( - } propsTargetRef={() => {}} locale="en" />, - ); - const slot = () => screen.getByTestId('studio-right-slot'); - const handle = screen.getByTestId('studio-slot-resize'); - expect(handle).toHaveAttribute('aria-valuemin', '320'); - expect(handle).toHaveAttribute('aria-valuemax', '560'); - fireEvent.pointerDown(handle, { clientX: 1000 }); - fireEvent.pointerMove(window, { clientX: 900 }); - fireEvent.pointerUp(window, { clientX: 900 }); - expect(slot()).toHaveStyle({ width: '460px' }); - expect(window.localStorage.getItem(STUDIO_SLOT_WIDTH_STORAGE_KEYS.props)).toBe('460'); - expect(window.localStorage.getItem(STUDIO_SLOT_WIDTH_STORAGE_KEYS.copilot)).toBeNull(); - - // The copilot keeps its own width; dragging it far right stops at 320. - view.rerender( - } propsTargetRef={() => {}} locale="en" />, - ); - expect(slot()).toHaveStyle({ width: '420px' }); - fireEvent.pointerDown(screen.getByTestId('studio-slot-resize'), { clientX: 1000 }); - fireEvent.pointerUp(window, { clientX: 1400 }); - expect(slot()).toHaveStyle({ width: '320px' }); - expect(window.localStorage.getItem(STUDIO_SLOT_WIDTH_STORAGE_KEYS.copilot)).toBe('320'); - cleanup(); - - // A reload reads both back. - renderSlot({ mode: 'props' }); - expect(slot()).toHaveStyle({ width: '460px' }); - cleanup(); - renderSlot({ mode: 'copilot' }); - expect(slot()).toHaveStyle({ width: '320px' }); - }); - - it('drops the width both panes used to share', () => { - Object.defineProperty(window, 'innerWidth', { configurable: true, value: 1600 }); - window.localStorage.setItem(STUDIO_SLOT_SHARED_WIDTH_STORAGE_KEY, '500'); - renderSlot({ mode: 'props' }); + for (const retired of STUDIO_SLOT_RETIRED_WIDTH_STORAGE_KEYS) window.localStorage.setItem(retired, '500'); + renderSlot(); expect(screen.getByTestId('studio-right-slot')).toHaveStyle({ width: '360px' }); - expect(window.localStorage.getItem(STUDIO_SLOT_SHARED_WIDTH_STORAGE_KEY)).toBeNull(); - }); - - it('leaves the in-place widen and the phone overlay outside the range', () => { - Object.defineProperty(window, 'innerWidth', { configurable: true, value: 1600 }); - renderSlot({ mode: 'copilot', wide: true, wideWidth: 900, onWideChange: vi.fn() }); - expect(screen.getByTestId('studio-right-slot')).toHaveStyle({ width: '900px' }); - expect(screen.queryByTestId('studio-slot-resize')).toBeNull(); - cleanup(); - renderSlot({ mode: 'props', overlay: true }); - expect(screen.getByTestId('studio-right-slot').getAttribute('style')).toBeNull(); - expect(screen.queryByTestId('studio-slot-resize')).toBeNull(); + for (const retired of STUDIO_SLOT_RETIRED_WIDTH_STORAGE_KEYS) expect(window.localStorage.getItem(retired)).toBeNull(); }); }); diff --git a/ui/packages/app-shell/src/views/studio-design/__tests__/studioSurfaceContext.test.tsx b/ui/packages/app-shell/src/views/studio-design/__tests__/studioSurfaceContext.test.tsx deleted file mode 100644 index ec7f5e630e6..00000000000 --- a/ui/packages/app-shell/src/views/studio-design/__tests__/studioSurfaceContext.test.tsx +++ /dev/null @@ -1,202 +0,0 @@ -// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. - -/** - * cloud#1610 (send half) — the Studio copilot derives WHAT the user is - * discussing from the URL alone: the `:tab` route segment is the pillar, the - * `?surface=type:name` deep-link (which every pillar already mirrors) is the - * artifact WITH its type discriminator. Pinned by rendering the real - * StudioCopilotConversation and asserting the surfaceContext it hands the - * ChatPane — the URL is the single source of truth, so this contract is - * exactly "route in → context out". - */ -import '@testing-library/jest-dom/vitest'; -import * as React from 'react'; -import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; -import { cleanup, render } from '@testing-library/react'; -import { MemoryRouter, Route, Routes } from 'react-router-dom'; - -let capturedProps: Record = {}; - -vi.mock('../../../console/ai/AiChatPage.js', async (importOriginal) => { - const mod = await importOriginal>(); - return { - ...mod, - ChatPane: (props: Record) => { - capturedProps = props; - return
; - }, - }; -}); -vi.mock('@object-ui/auth', async (importOriginal) => { - const actual = await importOriginal>(); - return { ...actual, useAuth: () => ({ user: { id: 'u1' } }) }; -}); -vi.mock('@object-ui/plugin-chatbot/core', async (importOriginal) => { - const actual = await importOriginal>(); - return { - ...actual, - useAgents: () => ({ - agents: [{ name: 'metadata_assistant', label: 'Build', capabilities: ['build'] }], - isLoading: false, - loading: false, - error: undefined, - refetch: vi.fn(), - }), - }; -}); - -import { StudioCopilotConversation } from '../StudioAiCopilot'; - -/* ── The `ai/conversations` double (objectui#7307) ──────────────────── - * Every `renderAt` below mounts the real `StudioCopilotConversation`, whose - * `useChatConversation` resolve effect mints a thread for the signed-in user on - * mount: `POST /api/v1/ai/conversations` through the GLOBAL `fetch` - * (`hooks/useChatConversation.ts:609`, no `apiFetch` seam on the path). Under - * happy-dom that global is a real HTTP client and the document URL defaults to - * `http://localhost:3000`, so the relative path resolved to a live socket — once - * per case, four in the file. The resolve's `catch` is deliberately conservative - * (it keeps the surface as it was), which is why these cases stayed green while - * the mint always failed. - * - * Answered from a RECORDING double — the shape objectui#5225 settled on, carried - * by `packages/plugin-report/src/__tests__/DatasetReportRenderer.test.tsx` and by - * this burn-down's earlier batches. Deliberately NOT a blanket network stub: it - * records every URL it is handed and `afterEach` fails on any URL outside the - * routes it serves. - * - * TWO routes, because a mint that SUCCEEDS is resumable and the hook resumes it. - * `useChatConversation` caches the minted id in `localStorage` - * (`writeCache` → `readCache`), and happy-dom keeps that store for the whole - * file — so case 1 mints and cases 2-4 resume, reading - * `GET /api/v1/ai/conversations/{THE_MINTED_ID}` instead. That second route was - * MEASURED, not assumed: serving only the mint made this file's own - * router assertion red naming that exact URL. Both answer the same empty - * `ServerConversation` (`{ id, messages: [] }` — the shape `createConversation` - * and `fetchConversation` both cast their body to), so the fake server is - * self-consistent: one thread, minted once, resumed thereafter. - * - * Why an empty thread changes no assertion here: this file asserts ONE thing per - * case — the `surfaceContext` prop the pane receives, derived from the URL alone. - * `ChatPane` is a capture stub, the conversation never reaches an assertion, and - * the resolve settles in a microtask AFTER each synchronous case body has already - * read `capturedProps`. A SEEDED thread would hydrate `initialMessages` into that - * same stub for no assertion's benefit. Routes are matched on the PATHNAME; the - * full URL is what gets recorded. - * ─────────────────────────────────────────────────── */ - -/** The one thread this fake server owns: minted by case 1, resumed by 2-4. */ -const CONVERSATION = { id: 'conv_studio_copilot', messages: [] as unknown[] }; - -/** `POST` here mints; `GET .../{id}` resumes. Nothing else is served. */ -const MINT_ROUTE = '/api/v1/ai/conversations'; -const RESUME_ROUTE = `${MINT_ROUTE}/${CONVERSATION.id}`; -const SERVED_ROUTES = new Set([MINT_ROUTE, RESUME_ROUTE]); - -/** Every URL this file's renders handed the global `fetch`, in request order. */ -let aiCalls: string[] = []; - -/** The route key of a recorded URL: its pathname, without any query. */ -const routeOf = (url: string) => url.split('?')[0]; - -/** Serve the two conversation routes as one empty thread; record everything. */ -function installConversationsDouble() { - aiCalls = []; - vi.stubGlobal( - 'fetch', - vi.fn(async (input: unknown) => { - const url = String( - input && typeof input === 'object' && 'url' in input ? (input as { url: unknown }).url : input, - ); - aiCalls.push(url); - if (!SERVED_ROUTES.has(routeOf(url))) { - return { ok: false, status: 404, headers: new Headers(), json: async () => ({}) }; - } - return { ok: true, status: 200, headers: new Headers(), json: async () => CONVERSATION }; - }), - ); -} - -beforeEach(installConversationsDouble); - -afterEach(() => { - // The double is a router, not a sink: an escape to any OTHER endpoint fails - // here instead of vanishing into the resolve effect's `catch`. - expect(aiCalls.filter((url) => !SERVED_ROUTES.has(routeOf(url)))).toEqual([]); - // Unmount BEFORE restoring the real `fetch`. Vitest runs `afterEach` hooks in - // reverse registration order, so this file's teardown runs before the root - // setup's RTL cleanup: unstubbing first would leave the tree mounted with the - // real global back in place, and a mount effect settling in that window - // escapes again (objectui#7439). - cleanup(); - vi.unstubAllGlobals(); - capturedProps = {}; -}); - -function renderAt(url: string) { - render( - - - {/* objectstack#36904 — the area's routes carry no :tab; a designer page names its item in the path. */} - } /> - } - /> - - , - ); -} - -describe('Studio copilot surfaceContext (cloud#1610 send half)', () => { - it('pillar + typed artifact come straight from the URL', () => { - renderAt('/studio/app.k9/interfaces?surface=dashboard:sales_overview'); - expect(capturedProps.surfaceContext).toEqual({ - pillar: 'interfaces', - artifact: { type: 'dashboard', name: 'sales_overview' }, - }); - }); - - it('a pillar with no selected artifact still names the pillar', () => { - renderAt('/studio/app.k9/data'); - expect(capturedProps.surfaceContext).toEqual({ pillar: 'data' }); - }); - - it('an artifact name containing colons keeps everything after the FIRST one', () => { - renderAt('/studio/app.k9/interfaces?surface=object:k9_task.member_list'); - expect(capturedProps.surfaceContext).toEqual({ - pillar: 'interfaces', - artifact: { type: 'object', name: 'k9_task.member_list' }, - }); - }); - - it('a malformed surface param degrades to pillar-only, never a broken artifact', () => { - renderAt('/studio/app.k9/access?surface=nonsense'); - expect(capturedProps.surfaceContext).toEqual({ pillar: 'access' }); - }); -}); - -/* - * objectstack#36904 — the object designer opens full-screen on the object's - * metadata address, which carries no `?surface=`: the copilot reads the item - * off the path (`areaDesignerItemOf`), under the area's segment. - */ -describe('Studio copilot surfaceContext on a designer\'s metadata address (objectstack#36904)', () => { - it('the object designer\'s address names the area and the object', () => { - renderAt('/studio/app.k9/metadata/object/k9_task?tab=fields'); - expect(capturedProps.surfaceContext).toEqual({ pillar: 'metadata', artifact: { type: 'object', name: 'k9_task' } }); - }); - - it('its history address names the same object, decoded', () => { - renderAt('/studio/app.k9/metadata/object/k9%20task/history'); - expect(capturedProps.surfaceContext).toEqual({ pillar: 'metadata', artifact: { type: 'object', name: 'k9 task' } }); - }); - - // CONTROLS: the create page, a list and a type with no designer page name no item. - it('the create page, the object list and a generic item page name nothing', () => { - for (const url of ['/studio/app.k9/metadata/object/new', '/studio/app.k9/metadata/object', '/studio/app.k9/metadata/dashboard/sales']) { - cleanup(); - renderAt(url); - expect(capturedProps.surfaceContext, url).toBeUndefined(); - } - }); -}); diff --git a/ui/packages/app-shell/src/views/studio-design/__tests__/studioSurfaceLabel-8219.test.tsx b/ui/packages/app-shell/src/views/studio-design/__tests__/studioSurfaceLabel-8219.test.tsx deleted file mode 100644 index 11cc5e8ca09..00000000000 --- a/ui/packages/app-shell/src/views/studio-design/__tests__/studioSurfaceLabel-8219.test.tsx +++ /dev/null @@ -1,178 +0,0 @@ -// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. - -/** - * objectui#8219 item 3 — the Studio copilot hands the chat pane the display - * label of what the user is discussing, as a SEPARATE optional prop. - * - * The label lives only in the Interfaces pillar (its open leaf), which reports - * it up to the surface that mounts the dock. The conversation passes it on only - * when it names the SAME artifact the URL does — the URL stays the single - * source of the surface context (cloud#1610), so a label that lags or leads the - * `?surface=` deep-link is dropped rather than shown against the wrong item. - * - * The other half is the invariant seat answer A rests on: `surfaceContext`, the - * `context.surface` data the agent receives, is identical with and without a - * label. The conversations double below is the one `studioSurfaceContext.test.tsx` - * carries, for the same reason (objectui#7307). - */ -import '@testing-library/jest-dom/vitest'; -import * as React from 'react'; -import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; -import { cleanup, render } from '@testing-library/react'; -import { MemoryRouter, Route, Routes } from 'react-router-dom'; - -let capturedProps: Record = {}; - -vi.mock('../../../console/ai/AiChatPage.js', async (importOriginal) => { - const mod = await importOriginal>(); - return { - ...mod, - ChatPane: (props: Record) => { - capturedProps = props; - return
; - }, - }; -}); -vi.mock('@object-ui/auth', async (importOriginal) => { - const actual = await importOriginal>(); - return { ...actual, useAuth: () => ({ user: { id: 'u1' } }) }; -}); -vi.mock('@object-ui/plugin-chatbot/core', async (importOriginal) => { - const actual = await importOriginal>(); - return { - ...actual, - useAgents: () => ({ - agents: [{ name: 'metadata_assistant', label: 'Build', capabilities: ['build'] }], - isLoading: false, - loading: false, - error: undefined, - refetch: vi.fn(), - }), - }; -}); - -import { StudioCopilotConversation } from '../StudioAiCopilot'; - -/* ── The `ai/conversations` double (objectui#7307) ──────────────────── - * Copied from `studioSurfaceContext.test.tsx`, whose header explains it: the - * real conversation mints (POST) and then resumes (GET) one thread through the - * global `fetch`, so both routes are served and any other URL fails the case. - * ─────────────────────────────────────────────────── */ - -/** The one thread this fake server owns: minted once, resumed thereafter. */ -const CONVERSATION = { id: 'conv_studio_copilot', messages: [] as unknown[] }; - -/** `POST` here mints; `GET .../{id}` resumes. Nothing else is served. */ -const MINT_ROUTE = '/api/v1/ai/conversations'; -const RESUME_ROUTE = `${MINT_ROUTE}/${CONVERSATION.id}`; -const SERVED_ROUTES = new Set([MINT_ROUTE, RESUME_ROUTE]); - -/** Every URL this file's renders handed the global `fetch`, in request order. */ -let aiCalls: string[] = []; - -/** The route key of a recorded URL: its pathname, without any query. */ -const routeOf = (url: string) => url.split('?')[0]; - -/** Serve the two conversation routes as one empty thread; record everything. */ -function installConversationsDouble() { - aiCalls = []; - vi.stubGlobal( - 'fetch', - vi.fn(async (input: unknown) => { - const url = String( - input && typeof input === 'object' && 'url' in input ? (input as { url: unknown }).url : input, - ); - aiCalls.push(url); - if (!SERVED_ROUTES.has(routeOf(url))) { - return { ok: false, status: 404, headers: new Headers(), json: async () => ({}) }; - } - return { ok: true, status: 200, headers: new Headers(), json: async () => CONVERSATION }; - }), - ); -} - -beforeEach(installConversationsDouble); - -afterEach(() => { - // The double is a router, not a sink: an escape to any OTHER endpoint fails - // here instead of vanishing into the resolve effect's `catch`. - expect(aiCalls.filter((url) => !SERVED_ROUTES.has(routeOf(url)))).toEqual([]); - // Unmount BEFORE restoring the real `fetch`. Vitest runs `afterEach` hooks in - // reverse registration order, so this file's teardown runs before the root - // setup's RTL cleanup: unstubbing first would leave the tree mounted with the - // real global back in place, and a mount effect settling in that window - // escapes again (objectui#7439). - cleanup(); - vi.unstubAllGlobals(); - capturedProps = {}; -}); - -const DASH = { type: 'dashboard', name: 'customer_dashboard', label: '客户仪表盘' }; - -function renderAt(url: string, surfaceLabel?: { type: string; name: string; label: string }) { - // Spread so the file compiles against a conversation that does not declare - // the prop yet (the red half). - const labelProp = (surfaceLabel ? { surfaceLabel } : {}) as Record; - render( - - - {/* objectstack#36904 — the area's routes: a designer page names its item in the path. */} - } /> - } - /> - - , - ); -} - -const URL_DASH = '/studio/app.k9/interfaces?surface=dashboard:customer_dashboard'; - -describe('Studio copilot display label (objectui#8219 item 3)', () => { - it('a label for the artifact the URL names reaches the pane as its own prop', () => { - renderAt(URL_DASH, DASH); - expect(capturedProps.surfaceArtifactLabel).toBe('客户仪表盘'); - }); - - it('surfaceContext is byte-identical with and without the label', () => { - renderAt(URL_DASH); - const without = JSON.stringify(capturedProps.surfaceContext); - expect(capturedProps.surfaceArtifactLabel).toBeUndefined(); - cleanup(); - renderAt(URL_DASH, DASH); - expect(JSON.stringify(capturedProps.surfaceContext)).toBe(without); - expect(without).toBe( - JSON.stringify({ pillar: 'interfaces', artifact: { type: 'dashboard', name: 'customer_dashboard' } }), - ); - }); - - it('a label for a DIFFERENT artifact than the URL names is not shown', () => { - renderAt('/studio/app.k9/interfaces?surface=object:b2r4_customer', DASH); - expect(capturedProps.surfaceArtifactLabel).toBeUndefined(); - }); - - it('no artifact in the URL: no label, whatever was reported', () => { - renderAt('/studio/app.k9/data', DASH); - expect(capturedProps.surfaceArtifactLabel).toBeUndefined(); - }); -}); - -/* - * objectstack#36904 — the object designer on its metadata address reports its - * label as the pillar did; the chip shows it when it labels the object the - * path names, and only then. - */ -describe('Studio copilot display label on a designer\'s metadata address (objectstack#36904)', () => { - const TASK = { type: 'object', name: 'k9_task', label: '任务' }; - - it('a label for the object the address names reaches the pane', () => { - renderAt('/studio/app.k9/metadata/object/k9_task', TASK); - expect(capturedProps.surfaceArtifactLabel).toBe('任务'); - }); - - it('a label for another object than the address names is not shown', () => { - renderAt('/studio/app.k9/metadata/object/k9_note', TASK); - expect(capturedProps.surfaceArtifactLabel).toBeUndefined(); - }); -}); diff --git a/ui/packages/app-shell/src/views/studio-design/packages-io.bearerSession.test.ts b/ui/packages/app-shell/src/views/studio-design/packages-io.bearerSession.test.ts index 26ea44a2ed9..4c979d73b92 100644 --- a/ui/packages/app-shell/src/views/studio-design/packages-io.bearerSession.test.ts +++ b/ui/packages/app-shell/src/views/studio-design/packages-io.bearerSession.test.ts @@ -23,7 +23,6 @@ import { TokenStorage } from '@object-ui/auth'; import { duplicatePackage, fetchListedPackageIds, fetchPackages, forgetPackageListReads } from './packages-io'; import { fetchCommits, revertCommit } from '../../preview/commitHistory'; import { listSuggestedBindings } from '../../services/suggestedBindingsApi'; -import { fetchBuildDebug } from '../../console/ai/buildDebugApi'; const TOKEN = 'stored-session-token'; @@ -44,7 +43,6 @@ function answer(path: string, method: string): Response { if (path.endsWith('/commits') && method === 'GET') return reply({ success: true, data: { commits: [] } }); if (path.endsWith('/revert') && method === 'POST') return reply({ success: true, data: { success: true } }); if (path.startsWith('/api/v1/security/suggested-bindings')) return reply({ success: true, data: { suggestions: [] } }); - if (path.endsWith('/debug')) return reply({ conversationId: 'c1', findings: [] }); return reply({ success: false, error: { code: 'NOT_FOUND', message: `no route ${method} ${path}` } }, 404); } @@ -101,7 +99,6 @@ const CALLS: Array<[string, () => Promise]> = [ ['timeline: commit history', () => fetchCommits('com.example.crm')], ['timeline: revert a commit', () => revertCommit('com.example.crm', 'c-1')], ['access: suggested bindings', () => listSuggestedBindings()], - ['ai: build debug report', () => fetchBuildDebug('/api/v1/ai', 'c1')], ]; describe('the converted doors send the stored bearer token', () => { diff --git a/ui/packages/app-shell/src/views/studio-design/studioRightSlotState.ts b/ui/packages/app-shell/src/views/studio-design/studioRightSlotState.ts index d4928f31b6f..b21e449187c 100644 --- a/ui/packages/app-shell/src/views/studio-design/studioRightSlotState.ts +++ b/ui/packages/app-shell/src/views/studio-design/studioRightSlotState.ts @@ -11,37 +11,31 @@ import * as React from 'react'; import { DOCK_CONTENT_MIN_WIDTH, DOCK_KEYBOARD_STEP } from '../../layout/chatDockState.js'; -export type StudioSlotMode = 'props' | 'copilot'; - /** * objectstack#34725 — the slot's width, resizable from its left edge and - * remembered per browser under the slot's own keys, so a width dragged here - * never moves the console drawer's. objectstack#35061 — each pane keeps its - * own width (properties 360 px, the copilot 420 px by default, `STUDIO_SLOT_DEFAULT_WIDTHS`), - * within the slot's range (`clampStudioSlotWidth`), never so wide that the - * canvas drops under `DOCK_CONTENT_MIN_WIDTH`. The widened copilot is the one - * other width (`wideWidth`), outside that range. + * remembered per browser under the slot's own key, so a width dragged here + * never moves the console drawer's. objectstack#35061 — 360 px by default + * (`STUDIO_SLOT_DEFAULT_WIDTH`), within the slot's range + * (`clampStudioSlotWidth`), never so wide that the canvas drops under + * `DOCK_CONTENT_MIN_WIDTH`. */ -export const STUDIO_SLOT_WIDTH_STORAGE_KEYS: Readonly> = { - props: 'studio-right-slot-width-props', - copilot: 'studio-right-slot-width-copilot', -}; +export const STUDIO_SLOT_WIDTH_STORAGE_KEY = 'studio-right-slot-width-props'; /** - * The one width both panes shared before each kept its own. Not read: it is - * removed on first use, and each pane starts from its default. + * The width keys the slot used before it held the properties alone. Not read: + * each is removed on first use. */ -export const STUDIO_SLOT_SHARED_WIDTH_STORAGE_KEY = 'studio-right-slot-width'; +export const STUDIO_SLOT_RETIRED_WIDTH_STORAGE_KEYS: readonly string[] = [ + 'studio-right-slot-width', + 'studio-right-slot-width-copilot', +]; -/** objectstack#35061 — each pane's width until the author drags it. */ -export const STUDIO_SLOT_DEFAULT_WIDTHS: Readonly> = { - props: 360, - copilot: 420, -}; +/** objectstack#35061 — the slot's width until the author drags it. */ +export const STUDIO_SLOT_DEFAULT_WIDTH = 360; /** objectstack#35061 — the slot is never narrower than this. */ export const STUDIO_SLOT_MIN_WIDTH = 320; -/** objectstack#35061 — the slot is never wider than this (the in-place widen aside). */ +/** objectstack#35061 — the slot is never wider than this. */ export const STUDIO_SLOT_MAX_WIDTH = 560; /** @@ -57,53 +51,41 @@ export function clampStudioSlotWidth(desired: number, viewportWidth: number): nu return Math.min(Math.max(desired, STUDIO_SLOT_MIN_WIDTH), upper); } -type StudioSlotWidths = Record; - -function readStoredSlotWidth(mode: StudioSlotMode): number { +function readStoredSlotWidth(): number { try { - const raw = window.localStorage.getItem(STUDIO_SLOT_WIDTH_STORAGE_KEYS[mode]); + for (const key of STUDIO_SLOT_RETIRED_WIDTH_STORAGE_KEYS) window.localStorage.removeItem(key); + const raw = window.localStorage.getItem(STUDIO_SLOT_WIDTH_STORAGE_KEY); const n = raw ? Number.parseInt(raw, 10) : NaN; - return Number.isFinite(n) && n > 0 ? n : STUDIO_SLOT_DEFAULT_WIDTHS[mode]; - } catch { - return STUDIO_SLOT_DEFAULT_WIDTHS[mode]; - } -} - -function readStoredSlotWidths(): StudioSlotWidths { - try { - window.localStorage.removeItem(STUDIO_SLOT_SHARED_WIDTH_STORAGE_KEY); + return Number.isFinite(n) && n > 0 ? n : STUDIO_SLOT_DEFAULT_WIDTH; } catch { - /* private mode: nothing was stored */ + return STUDIO_SLOT_DEFAULT_WIDTH; } - return { props: readStoredSlotWidth('props'), copilot: readStoredSlotWidth('copilot') }; } -function writeStoredSlotWidth(mode: StudioSlotMode, width: number): void { +function writeStoredSlotWidth(width: number): void { try { - window.localStorage.setItem(STUDIO_SLOT_WIDTH_STORAGE_KEYS[mode], String(Math.round(width))); + window.localStorage.setItem(STUDIO_SLOT_WIDTH_STORAGE_KEY, String(Math.round(width))); } catch { /* private mode: the width just is not remembered */ } } export interface StudioSlotWidth { - /** The shown pane's width to draw, already clamped to the window. */ + /** The slot's width to draw, already clamped to the window. */ width: number; dragging: boolean; - /** Pointer-down on the left-edge handle: dragging left widens the shown pane. */ + /** Pointer-down on the left-edge handle: dragging left widens the slot. */ onResizePointerDown: (e: React.PointerEvent) => void; /** Arrow keys on the focused handle: Left widens, Right narrows. */ onResizeKeyDown: (e: React.KeyboardEvent) => void; } /** - * The slot's resizable width for the pane it shows; see - * {@link STUDIO_SLOT_WIDTH_STORAGE_KEYS}. A resize moves only that pane's width. + * The slot's resizable width; see {@link STUDIO_SLOT_WIDTH_STORAGE_KEY}. */ -export function useStudioSlotWidth(mode: StudioSlotMode): StudioSlotWidth { - const [stored, setStored] = React.useState(readStoredSlotWidths); +export function useStudioSlotWidth(): StudioSlotWidth { + const [current, setCurrent] = React.useState(readStoredSlotWidth); const [dragging, setDragging] = React.useState(false); - const current = stored[mode]; const onResizePointerDown = React.useCallback( (e: React.PointerEvent) => { e.preventDefault(); @@ -112,13 +94,12 @@ export function useStudioSlotWidth(mode: StudioSlotMode): StudioSlotWidth { const widthAt = (x: number) => clampStudioSlotWidth(startWidth + (startX - x), window.innerWidth); setDragging(true); const onMove = (ev: PointerEvent) => { - const next = widthAt(ev.clientX); - setStored((prev) => ({ ...prev, [mode]: next })); + setCurrent(widthAt(ev.clientX)); }; const onUp = (ev: PointerEvent) => { const final = widthAt(ev.clientX); - setStored((prev) => ({ ...prev, [mode]: final })); - writeStoredSlotWidth(mode, final); + setCurrent(final); + writeStoredSlotWidth(final); setDragging(false); window.removeEventListener('pointermove', onMove); window.removeEventListener('pointerup', onUp); @@ -126,7 +107,7 @@ export function useStudioSlotWidth(mode: StudioSlotMode): StudioSlotWidth { window.addEventListener('pointermove', onMove); window.addEventListener('pointerup', onUp); }, - [current, mode], + [current], ); const onResizeKeyDown = React.useCallback( (e: React.KeyboardEvent) => { @@ -134,10 +115,10 @@ export function useStudioSlotWidth(mode: StudioSlotMode): StudioSlotWidth { e.preventDefault(); const step = e.key === 'ArrowLeft' ? DOCK_KEYBOARD_STEP : -DOCK_KEYBOARD_STEP; const next = clampStudioSlotWidth(clampStudioSlotWidth(current, window.innerWidth) + step, window.innerWidth); - setStored((prev) => ({ ...prev, [mode]: next })); - writeStoredSlotWidth(mode, next); + setCurrent(next); + writeStoredSlotWidth(next); }, - [current, mode], + [current], ); const width = typeof window === 'undefined' ? current : clampStudioSlotWidth(current, window.innerWidth); return { width, dragging, onResizePointerDown, onResizeKeyDown }; @@ -146,9 +127,7 @@ export function useStudioSlotWidth(mode: StudioSlotMode): StudioSlotWidth { export interface StudioRightSlotHandle { /** The element a pillar portals its properties into; `null` until mounted. */ propsTarget: HTMLElement | null; - /** The mode the slot SHOWS (a missing copilot reads as `props`). */ - mode: StudioSlotMode; - /** Claim the properties half of the slot; returns the release. */ + /** Claim the slot for the properties; returns the release. */ claimProps: () => () => void; /** An element was selected: show its properties. */ showProps: () => void; @@ -162,7 +141,7 @@ export function useStudioRightSlot(): StudioRightSlotHandle | null { } /** - * Match a keydown to the slot's mode toggle — `⌘.` (macOS) / `Ctrl+.`, no Shift, + * Match a keydown to the slot's toggle — `⌘.` (macOS) / `Ctrl+.`, no Shift, * no Alt. Measured free in the console at objectui `4b3d6ed`: the bound chords * are ⌘K, ⌘B, ⌘⇧H, ⌘⇧I, ⌘⇧M, ⌘⇧O, ⌘⇧S, ⌘S and `?`. Pure + exported for tests. */ diff --git a/ui/packages/app-shell/src/views/studio-design/useSurfaceDeepLink.ts b/ui/packages/app-shell/src/views/studio-design/useSurfaceDeepLink.ts index 25e489bda66..a0f46cce0c0 100644 --- a/ui/packages/app-shell/src/views/studio-design/useSurfaceDeepLink.ts +++ b/ui/packages/app-shell/src/views/studio-design/useSurfaceDeepLink.ts @@ -29,8 +29,8 @@ import { useSearchParams } from 'react-router-dom'; * entries that open one object (data slices, named views), so the Interfaces * pillar adds the entry beside it. A KEY OF ITS OWN, not a `nav:` value of * `?surface=`: every reader of that param parses it as `:` (each - * pillar's restore, the app→Studio bridge in `utils/appRoute.ts`, the - * copilot's surface context in `StudioAiCopilot`), and a second value grammar + * pillar's restore, the app→Studio bridge in `utils/appRoute.ts`), and a + * second value grammar * would hand each of them a `nav` "type". With a separate key, `?surface=` * keeps meaning what it meant to all of them, and a link without `nav` — every * link produced before this key existed — resolves exactly as it did. diff --git a/ui/packages/core/src/utils/__tests__/column-identity.ratchet.test.ts b/ui/packages/core/src/utils/__tests__/column-identity.ratchet.test.ts index d6d5c0b3fa2..7866f6613df 100644 --- a/ui/packages/core/src/utils/__tests__/column-identity.ratchet.test.ts +++ b/ui/packages/core/src/utils/__tests__/column-identity.ratchet.test.ts @@ -168,11 +168,6 @@ const INVENTORY: Record = { verdict: 'unrelated', why: '`fields.find(f => f.name === r.field)` — a join between a field list and a rule\'s field reference, matched only because both keys share a line.', }, - 'plugin-chatbot/src/ChatbotEnhanced.tsx': { - count: 1, - verdict: 'unrelated', - why: '`c.object ?? c.name` — a citation label fallback that happens to sit on a line mentioning `c.field`.', - }, 'app-shell/src/views/metadata-admin/SchemaForm.tsx': { count: 1, verdict: 'unrelated', @@ -266,8 +261,10 @@ describe('column identity dual-read ratchet (#3104)', () => { // objectui#10404 mirrored its param-name reader there too; 12 since // objectui#10475 deleted `ObjectForm.tsx`'s section-entry join; 11 since // objectui#12105 retired plugin-grid's hand-mapped `toBulkParam`, whose - // param-name read now comes from the shared resolver's `paramName`. - expect(sum(() => true)).toBe(11); + // param-name read now comes from the shared resolver's `paramName`; 10 + // since objectstack#37682 deleted the chat's change card, whose row-name + // fallback was the `unrelated` entry in `ChatbotEnhanced.tsx`. + expect(sum(() => true)).toBe(10); }); it('records a precedence for every read left in the family', () => { diff --git a/ui/packages/core/src/utils/affordanceGrants.ts b/ui/packages/core/src/utils/affordanceGrants.ts index 7bfd5c3fc63..e4cd625ad79 100644 --- a/ui/packages/core/src/utils/affordanceGrants.ts +++ b/ui/packages/core/src/utils/affordanceGrants.ts @@ -145,12 +145,7 @@ export const AFFORDANCE_GRANTS = { * "+", and the `object-view` node's toolbar button (`@object-ui/plugin-view`). */ listNew: { crud: 'create', grant: 'create' }, - /** - * An object list's Import, and the import wizard's writable target fields — - * and the AI build panel's spreadsheet import (`ExcelImportBar` in - * `@object-ui/app-shell`), the wizard's second mount, asked of the object it - * imports into. - */ + /** An object list's Import, and the import wizard's writable target fields. */ listImport: { crud: 'import', grant: 'create', field: 'create' }, /** The import wizard's template download — its endpoint answers 403 without the create grant. */ importTemplate: { crud: null, grant: 'create' }, diff --git a/ui/packages/i18n/scripts/zh-hant.d.mts b/ui/packages/i18n/scripts/zh-hant.d.mts index 6dbf10e2d0d..b3ed97ab6c3 100644 --- a/ui/packages/i18n/scripts/zh-hant.d.mts +++ b/ui/packages/i18n/scripts/zh-hant.d.mts @@ -29,9 +29,6 @@ export declare const CONVERSION_CASES: ReadonlyArray; /** The pinned cases the converter does not answer as pinned. */ export declare function conversionFailures(): Array<{ input: string; expected: string; actual: string }>; -/** The `console.ai.*` outbound leaves the generated pack does not carry. */ -export declare const GATE_ONLY_KEYS: ReadonlyArray; - /** The header the generated pack opens with. */ export declare const GENERATED_HEADER: string; diff --git a/ui/packages/i18n/scripts/zh-hant.mjs b/ui/packages/i18n/scripts/zh-hant.mjs index c4f83a7b5e8..1986df8164f 100644 --- a/ui/packages/i18n/scripts/zh-hant.mjs +++ b/ui/packages/i18n/scripts/zh-hant.mjs @@ -307,49 +307,6 @@ function indexOnce(text, anchor) { return at; } -/** - * The `console.ai.*` leaves the generated pack does NOT carry: text the console - * SENDS to the agent rather than shows (objectui#3896). They are read from the - * `en` and `zh-Hans` packs only, by the conversation's language, and the cloud - * confirm gate recognises exactly those two spellings, so a Traditional copy - * would be unreachable text that reads as a third gate language. - * `src/__tests__/outbound-agent-messages.test.ts` owns that invariant over - * every pack; this list is how the generated pack keeps it. Each is a - * one-line property in zh-Hans.ts, replaced line for line by a comment, so the - * two packs' line numbers stay aligned. - */ -export const GATE_ONLY_KEYS = Object.freeze([ - 'planApproveMessage', - 'planApproveDefaultsMessage', - 'planAnswerMessage', - 'planExtendExistingMessage', - 'planBuildNewAppMessage', - 'changesConfirmMessage', -]); - -/** - * The zh-Hans pack body with each {@link GATE_ONLY_KEYS} property line replaced - * by a comment. Throws unless each key is exactly one single-line property. - * - * @param {string} body - * @returns {string} - */ -function withoutGateOnlyKeys(body) { - let out = body; - for (const name of GATE_ONLY_KEYS) { - const line = new RegExp(`^([ \\t]+)${name}: '[^'\\n]*',$`, 'gm'); - const hits = out.match(line) ?? []; - if (hits.length !== 1 || out.split(`${name}:`).length !== 2) { - throw new Error( - `gen-zh-hant: expected ${name} exactly once in zh-Hans.ts, as a one-line property. ` + - 'The pack source changed shape; update GATE_ONLY_KEYS in scripts/zh-hant.mjs.', - ); - } - out = out.replace(line, `$1// ${name}: gate-only, read from zh-Hans (GATE_ONLY_KEYS, scripts/zh-hant.mjs).`); - } - return out; -} - /** * The catalogue's own declaration in the source, at the start of a line (a doc * comment may name it in prose), and the name the generated catalogue takes. @@ -390,21 +347,19 @@ function convertCatalogue(zhHansSource, header, prepare) { * Text in, text out, so the generated module keeps the source's shape exactly: * the same keys in the same order, the same comments (converted), the same * `as const`. Only the pack's doc comment and its own name change (`zh` → - * `zhHant`), the {@link GATE_ONLY_KEYS} lines become comments, and the header - * says the file is generated. + * `zhHant`) and the header says the file is generated. * * @param {string} zhHansSource the text of `src/locales/zh-Hans.ts` * @returns {string} the text of `src/locales/zh-Hant.ts` */ export function generateZhHantPack(zhHansSource) { - return convertCatalogue(zhHansSource, GENERATED_HEADER, withoutGateOnlyKeys); + return convertCatalogue(zhHansSource, GENERATED_HEADER, (body) => body); } /** * A pack-shaped namespace's zh-Hant catalogue (`src/namespaces//zh-Hant.ts`), * generated from its zh-Hans catalogue the way {@link generateZhHantPack} - * generates the pack: same keys, same order, converted text. A namespace holds - * none of the {@link GATE_ONLY_KEYS}, so nothing is dropped. + * generates the pack: same keys, same order, converted text. * * @param {string} zhHansSource the text of `src/namespaces//zh-Hans.ts` * @returns {string} the text of `src/namespaces//zh-Hant.ts` diff --git a/ui/packages/i18n/src/__tests__/all-locales-key-parity.test.ts b/ui/packages/i18n/src/__tests__/all-locales-key-parity.test.ts index ef147fe0dcd..6ad7f62f3da 100644 --- a/ui/packages/i18n/src/__tests__/all-locales-key-parity.test.ts +++ b/ui/packages/i18n/src/__tests__/all-locales-key-parity.test.ts @@ -39,9 +39,9 @@ * a key set or a placeholder. Trying to make it red on those would be asking * a key-set test to judge meaning. * - * That gate skips any key a pack does not define — including the four - * `OUTBOUND_KEYS` below — precisely because their key sets are this file's - * business, so the two cannot contradict each other on the same fact. + * That gate skips any key a pack does not define, precisely because key sets + * are this file's business, so the two cannot contradict each other on the + * same fact. * * ## The second invariant here: a plural family carries a base key (objectui#3863) * @@ -106,24 +106,6 @@ import { describe, it, expect } from 'vitest'; import { PLATFORM_LOCALE_TAGS } from '@objectstack/spec/system'; import { builtInLocales } from '../locales'; -/** - * Text the console SENDS to the agent rather than displays. These are absent - * from every non-gate pack ON PURPOSE: the console resolves them from the - * `en`/`zh-Hans` packs by the CONVERSATION's language (objectui#3896), so a value in - * any other pack is unreachable, and the cloud confirm gate only recognises - * those two languages anyway — see `outbound-agent-messages.test.ts`, which owns - * that invariant and asserts it in both directions. Excluded here so the two - * guards cannot contradict each other. - */ -const OUTBOUND_KEYS = new Set([ - 'console.ai.planApproveMessage', - 'console.ai.planApproveDefaultsMessage', - 'console.ai.planAnswerMessage', - 'console.ai.planExtendExistingMessage', - 'console.ai.planBuildNewAppMessage', - 'console.ai.changesConfirmMessage', -]); - function keyPaths(node: unknown, prefix = ''): string[] { return node !== null && typeof node === 'object' ? Object.entries(node as Record).flatMap(([k, v]) => @@ -132,7 +114,7 @@ function keyPaths(node: unknown, prefix = ''): string[] { : [prefix]; } -const keysOf = (pack: unknown) => new Set(keyPaths(pack).filter((k) => !OUTBOUND_KEYS.has(k))); +const keysOf = (pack: unknown) => new Set(keyPaths(pack)); /** * `Object.keys` erases which keys it enumerated, so `builtInLocales[lang]` on a @@ -152,8 +134,7 @@ type LocaleCode = keyof typeof builtInLocales; */ const PLURAL_SUFFIXES = ['_zero', '_one', '_two', '_few', '_many', '_other'] as const; -/** Every leaf path of a pack — no `OUTBOUND_KEYS` subtraction: a base key must be a - * real leaf of the SAME pack, whatever the parity exemptions are. */ +/** Every leaf path of a pack: a base key must be a real leaf of the SAME pack. */ const leavesOf = (pack: unknown) => new Set(keyPaths(pack)); /** diff --git a/ui/packages/i18n/src/__tests__/console-namespace-3546.test.tsx b/ui/packages/i18n/src/__tests__/console-namespace-3546.test.tsx index 7fbd19a5df3..033bea4a8a6 100644 --- a/ui/packages/i18n/src/__tests__/console-namespace-3546.test.tsx +++ b/ui/packages/i18n/src/__tests__/console-namespace-3546.test.tsx @@ -79,7 +79,12 @@ const REPO_ROOT = decodeURIComponent(new URL(import.meta.url).pathname) .join('/'); -/** The 46 keys this slice backfilled, grouped as the packs group them. */ +/** + * The keys this slice backfilled that are still live, grouped as the packs + * group them. It backfilled 46; objectstack#37682 retired the 18 that only the + * build chat read (the app switcher, the plan-design wait and its hints, and + * the plan / publish card), so 26 remain. + */ const KEYS = [ // console.shortcuts — the AI group of the ?-shortcuts dialog (3) 'console.shortcuts.groups.aiChat', @@ -89,33 +94,11 @@ const KEYS = [ 'console.notFound.title', 'console.notFound.description', 'console.notFound.back', - // console.ai — the /ai chat page chrome (9) + // console.ai — the /ai chat page chrome (4) 'console.ai.collapseToDock', - 'console.ai.switchApp', - 'console.ai.switchAppLabel', - 'console.ai.newApp', 'console.ai.connectionWaiting', 'console.ai.connectionStalled', 'console.ai.connectionOffline', - 'console.ai.designingPlan', - 'console.ai.planReady', - // console.ai.designingPlanHint — the rotating propose_blueprint hints (10) - 'console.ai.designingPlanHint.data', - 'console.ai.designingPlanHint.objects', - 'console.ai.designingPlanHint.relations', - 'console.ai.designingPlanHint.lookups', - 'console.ai.designingPlanHint.views', - 'console.ai.designingPlanHint.forms', - 'console.ai.designingPlanHint.defaults', - 'console.ai.designingPlanHint.dashboard', - 'console.ai.designingPlanHint.review', - 'console.ai.designingPlanHint.finalize', - // console.ai — the plan / publish confirm-gate card (5) - 'console.ai.planBuilding', - 'console.ai.planBuilt', - 'console.ai.planDeferred', - 'console.ai.published', - 'console.ai.publishFailed', // console.ai — the "no AI in this deployment" dead end (5) 'console.ai.unavailableTitle', 'console.ai.unavailableDescription', @@ -137,7 +120,7 @@ const KEYS = [ 'console.ai.group.older', ] as const; -/** The 41 of those that the guard measured; the other 5 are the prefix family. */ +/** The 21 of those that the guard measured; the other 5 are the prefix family. */ const MEASURED_KEYS = KEYS.filter((k) => !k.startsWith('console.ai.group.')); // Derived from the map rather than left as `string[]`: `Object.keys` erases @@ -191,19 +174,19 @@ beforeEach(() => { }); describe('objectui#3546 slice four — the console namespace', () => { - it('covers all ten packs and all forty-six keys (guards the loops from emptying)', () => { + it('covers all ten packs and all twenty-six live keys (guards the loops from emptying)', () => { expect(LANGS).toHaveLength(PLATFORM_LOCALE_TAGS.length); - expect(KEYS).toHaveLength(46); - expect(new Set(KEYS).size).toBe(46); - // 41 measured missing keys + 5 that came from the prefix family. Splitting the - // two apart here is what stops a later reader reading "46" off the ratchet. - expect(MEASURED_KEYS).toHaveLength(41); + expect(KEYS).toHaveLength(26); + expect(new Set(KEYS).size).toBe(26); + // 21 live measured keys + 5 that came from the prefix family. Splitting the + // two apart here is what stops a later reader reading "26" off the ratchet. + expect(MEASURED_KEYS).toHaveLength(21); const perArea = KEYS.reduce>((acc, k) => { const area = k.startsWith('console.ai.') ? 'console.ai' : k.split('.').slice(0, 2).join('.'); acc[area] = (acc[area] ?? 0) + 1; return acc; }, {}); - expect(perArea).toEqual({ 'console.shortcuts': 3, 'console.notFound': 3, 'console.ai': 40 }); + expect(perArea).toEqual({ 'console.shortcuts': 3, 'console.notFound': 3, 'console.ai': 20 }); }); it.each(LANGS)('%s defines every console key as a non-empty string', (lang) => { @@ -237,7 +220,7 @@ describe('objectui#3546 slice four — the console namespace', () => { }); it('no key in this slice interpolates — so no pack may invent a placeholder', () => { - // Unlike slice three, not one of these 46 strings takes an option: every + // Unlike slice three, not one of these 26 strings takes an option: every // measured call site passes `defaultValue` and nothing else. A translator // adding `{{name}}` would render the braces to the user verbatim, and a // single-brace `{seconds}`-style hole would be read by nothing at all. @@ -252,12 +235,11 @@ describe('objectui#3546 slice four — the console namespace', () => { it('the ellipsis character follows en in every pack', () => { // The packs mirror `en`'s ellipsis byte rather than picking their own: where // en writes U+2026 they write U+2026, where en writes "..." they write "...". - // 15 of these keys end in an ellipsis (the three connection banners, the - // designingPlan lead-in plus its ten hints, and planBuilding), and a pack that + // 3 of these keys end in an ellipsis (the three connection banners), and a pack that // swapped in three dots would read as a different typographic register on the // same card as its neighbours. const ellipsised = KEYS.filter((k) => (at(builtInLocales.en, k) as string).endsWith('…')); - expect(ellipsised).toHaveLength(15); + expect(ellipsised).toHaveLength(3); for (const lang of LANGS) { for (const key of ellipsised) { const value = at(builtInLocales[lang], key) as string; @@ -322,69 +304,6 @@ describe('objectui#3546 slice four — the console namespace', () => { }); }); - it('zh planBuilding is REACHABLE — no conversation-language gate shadows the pack (#3837)', () => { - // Slice four measured `planBuildingLabel` in `AiChatPage.tsx` gated on - // `convZh` (the CONVERSATION's language, #772/#2884) handing back a literal - // '正在搭建…' instead of the pack, which made the zh value below DEAD for every - // Chinese conversation — the pack could be re-worded and no zh reader would - // see it. That was filed as #3837 and fixed there; this assertion used to pin - // the literal and the pack byte-identical (the containment measure while the - // defect stood) and now pins its removal, which is the state that makes the - // pack the single source of the badge's text. - const src = sourceOf('packages/app-shell/src/console/ai/AiChatPage.tsx'); - expect( - src, - 'the convZh gate is back over planBuildingLabel — the zh pack value is dead again (#3837)', - ).not.toMatch(/convZh \? '[^']*' : t\('console\.ai\.planBuilding'/); - expect(src, 'planBuildingLabel no longer reads the pack directly (#3837)').toMatch( - /planBuildingLabel=\{t\('console\.ai\.planBuilding'/, - ); - // Same invariant one step wider, so the next label to drift in is caught too: - // `convZh` may gate OUTBOUND message text only — the cloud confirm gate reads - // those two languages (see outbound-agent-messages.test.ts) — never anything - // RENDERED. Whole-line comments are stripped first so prose naming the - // identifier (there is some, right above it) can't be counted as a read. - // - // Shape as of #3896: the four outbound messages no longer inline - // `convZh ? '' : t(key)` — they go through - // `resolveOutboundAgentText`, which reads the `zh`/`en` packs by conversation - // language. So `convZh` now has exactly ONE consumer, and that consumer is - // the resolver bridge; anything else reading it is a label drifting back in. - const code = src.replace(/^\s*\/\/.*$/gm, ''); - const convZhLines = code.split('\n').filter((line) => /\bconvZh\b/.test(line)); - expect( - convZhLines, - 'a convZh read appeared outside the outbound-text resolver — if it feeds anything rendered, it follows the UI locale instead (#3837/#3896)', - ).toHaveLength(3); - expect(convZhLines[0], 'the convZh memo itself').toMatch(/const convZh = useMemo\(/); - expect(convZhLines[1], 'its only consumer is the outbound-text resolver').toMatch( - /resolveOutboundAgentText\(\s*convZh\s*,/, - ); - expect(convZhLines[2], "the bridge's dep array").toMatch(/^\s*\[convZh\],\s*$/); - // And the resolver is asked for outbound MESSAGES only — the same list the - // i18n guard owns (`outbound-agent-messages.test.ts` OUTBOUND_KEYS). A - // `*Label` appearing here would be #3837 all over again, one indirection out. - const resolved = [...code.matchAll(/outboundText\('(\w+)'/g)].map((m) => m[1]).sort(); - expect(resolved).toEqual([ - 'changesConfirmMessage', - 'planAnswerMessage', - 'planApproveDefaultsMessage', - 'planApproveMessage', - 'planBuildNewAppMessage', - 'planExtendExistingMessage', - ]); - // #3896's headline defect in one line: an outbound message read through - // `t()` is read from the UI pack, which is how a zh console sent Chinese - // into an English thread. No outbound `*Message` key may go through `t()`. - expect( - code, - 'an outbound *Message is being read from the UI pack again (#3896)', - ).not.toMatch(/t\('console\.ai\.\w*Message'/); - // And zh still spells the badge the way the deleted literal did, so the fix - // changed WHICH source answers a zh-UI reader, not what they read. - expect(at(builtInLocales['zh-Hans'], 'console.ai.planBuilding')).toBe('正在搭建…'); - }); - it('the ratchet actually shrank — no console key is still baselined', () => { // `scripts/i18n-call-site-key-baseline.json` fails the build both ways: an // unfixed key missing from it, AND a fixed key still listed. Pinning the @@ -417,7 +336,6 @@ describe('objectui#3546 slice four — the console namespace', () => { /** One key per component that owns a group of these keys. */ const SAMPLE: Array<[key: string, owner: string]> = [ ['console.ai.collapseToDock', 'AiChatPage'], - ['console.ai.designingPlanHint.objects', 'AiChatPage (propose_blueprint wait)'], ['console.ai.unavailableTitle', 'AiChatPage (AiUnavailable)'], ['console.ai.dock.maximize', 'ChatDock'], ['console.notFound.title', 'AppContent RouteNotFound'], @@ -446,13 +364,13 @@ describe('objectui#3546 slice four — the console namespace', () => { it.each([ ['fr', 'console.ai.unavailableRetry', 'Réessayer'], - ['de', 'console.ai.planDeferred', 'Noch nicht erstellt'], + ['de', 'console.ai.unavailableHome', 'Zurück zur Startseite'], ['es', 'console.notFound.description', 'La URL que siguió no coincide con ninguna vista de esta aplicación.'], ['pt', 'console.ai.dock.collapse', 'Recolher a conversa'], ['ru', 'console.ai.connectionStalled', 'Всё ещё выполняется…'], - ['ja', 'console.ai.designingPlanHint.finalize', 'プランをまとめています…'], + ['ja', 'console.ai.connectionWaiting', 'サーバーを待っています…'], ['ko', 'console.shortcuts.groups.aiChat', 'AI 어시스턴트'], - ['ar', 'console.ai.published', 'تم النشر'], + ['ar', 'console.ai.unavailableRetry', 'إعادة المحاولة'], ])('%s renders a user-visible console string from the pack', (lang, key, expected) => { // One pinned surface per remaining pack, across four writing systems, so a // pack that silently reverts to English is caught by name and not only by @@ -466,7 +384,7 @@ describe('objectui#3546 slice four — the console namespace', () => { // spells ё rather than collapsing it to е, and these two strings are where // a backfill would most easily have dropped it. const { result } = renderHook(() => useObjectTranslation(), { wrapper: wrapperFor('ru') }); - expect(result.current.t('console.ai.planDeferred')).toContain('Ещё'); + expect(result.current.t('console.ai.connectionStalled')).toContain('Всё ещё'); expect(result.current.t('console.ai.unavailableDescription')).toContain('включён'); }); diff --git a/ui/packages/i18n/src/__tests__/count-families-11445.test.ts b/ui/packages/i18n/src/__tests__/count-families-11445.test.ts index adc4ca4f626..1ad6ba87320 100644 --- a/ui/packages/i18n/src/__tests__/count-families-11445.test.ts +++ b/ui/packages/i18n/src/__tests__/count-families-11445.test.ts @@ -125,7 +125,6 @@ const COUNT_NEUTRAL = { 'calendar.unscheduled', 'view.moreViews', 'detail.showDiscussion', - 'console.ai.buildDoctorDrawer.timeline', 'marketplace.installedCount', 'approvalsInbox.approveN', 'approvalsInbox.rejectN', @@ -151,16 +150,9 @@ const COUNT_NEUTRAL = { 'grid.import.imported', 'grid.import.skippedCount', 'console.ai.pendingDrafts.count', - 'console.ai.buildDoctorDrawer.allLive', - 'console.ai.buildDoctorDrawer.discrepancies', - 'console.ai.buildDoctorDrawer.issueCount', - 'console.ai.buildDoctorDrawer.platformNoise', 'home.pendingDrafts.publishedVerified', 'home.pendingDrafts.capabilityWarn', 'preview.history.items', - // objectstack#32984 — the build card's "N to fix" chip: the number stands - // before an infinitive or after a label, or takes a counter, in every pack. - 'chatbot.build.issuesCount', ], /** A relative time whose unit is abbreviated in every pack (`5m ago`, * `vor 5 Min.`, `5 мин назад`, `منذ 5 د`); an abbreviation does not inflect. */ diff --git a/ui/packages/i18n/src/__tests__/de-quote-pairing-3876.test.ts b/ui/packages/i18n/src/__tests__/de-quote-pairing-3876.test.ts index 21f12f8c8e8..8f90670a330 100644 --- a/ui/packages/i18n/src/__tests__/de-quote-pairing-3876.test.ts +++ b/ui/packages/i18n/src/__tests__/de-quote-pairing-3876.test.ts @@ -493,7 +493,11 @@ describe('objectui#3876 — de pack closes „ with “ and not with a straight // 133 once objectstack-ai/objectstack#36999 added `console.ai.focus.switchPrompt`, // the offer to ask about the record in view instead („{{target}}“) — one // interpolated span. - expect(okSpans, 'correctly paired spans').toBe(133); + // 127 once objectstack-ai/objectstack#37682 retired the build chat's keys: + // `console.ai.empty.editApp.title`, `chatbot.plan.iterateOrNew.question` and + // `.extend`, `chatbot.plan.suggestedFieldLegend`, `chatbot.build.nextStepQuote` + // and `chatbot.build.draftPosture` — six spans fewer. + expect(okSpans, 'correctly paired spans').toBe(127); }); it('keeps the count identity that replaces the card’s count(„) === count(“)', () => { @@ -636,7 +640,9 @@ describe('objectui#3876 — de pack closes „ with “ and not with a straight // 132 / 132 / 0 after objectstack-ai/objectstack#36739 removed the // checklist's `organizationName.todo` and `timezone.todo`, two pairs fewer. // 133 / 133 / 0 after objectstack-ai/objectstack#36999 added `console.ai.focus.switchPrompt`. - expect({ open, close, rdq }).toEqual({ open: 133, close: 133, rdq: 0 }); + // 127 / 127 / 0 after objectstack-ai/objectstack#37682 retired six build-chat + // keys, one matched pair each. + expect({ open, close, rdq }).toEqual({ open: 127, close: 127, rdq: 0 }); // The durable shape: every „ closed by a “, every surplus “ an English // opener answered by a ”. Survived translating the two English values. expect(close).toBe(open + rdq); diff --git a/ui/packages/i18n/src/__tests__/i18n.test.ts b/ui/packages/i18n/src/__tests__/i18n.test.ts index 5c2aa49d549..da4721becc2 100644 --- a/ui/packages/i18n/src/__tests__/i18n.test.ts +++ b/ui/packages/i18n/src/__tests__/i18n.test.ts @@ -102,59 +102,16 @@ describe('@object-ui/i18n', () => { expect(i18n.t('console.objectView.toolbarEnabledCount', { count: 3, total: 5 })).toBe('已启用 3/5 项'); }); - it('translates the AI "Proposed plan" card keys in Chinese (not English fallback)', () => { - const i18n = createI18n({ defaultLanguage: 'zh', detectBrowserLanguage: false }); - expect(i18n.t('console.ai.planTitle')).toBe('方案预览'); - expect(i18n.t('console.ai.planQuestions')).toBe('搭建前请确认'); - expect(i18n.t('console.ai.planAssumptions')).toBe('假设'); - expect(i18n.t('console.ai.planApproveHint')).toBe('回复以确认或调整该方案。'); - expect(i18n.t('console.ai.planApprove')).toBe('开始搭建'); - expect(i18n.t('console.ai.planAdjust')).toBe('调整方案'); - expect(i18n.t('console.ai.planApproveMessage')).toBe('确认,开始搭建。'); - expect(i18n.t('console.ai.planApproveDefaultsMessage')).toBe('确认搭建,未决问题按你的合理假设和默认处理。'); - expect(i18n.t('console.ai.nextSteps')).toBe('下一步'); - }); - - // Regression guard: the plan card's "Build it" and the change card's - // "Confirm" buttons SEND these messages to the agent, and the cloud confirm - // gate (service-ai-studio confirm-gate.ts APPROVAL_RE) decides whether the - // text counts as approval. Text the gate does not recognise fails SILENTLY: - // the agent re-proposes instead of acting and the button just looks inert. + // Regression guard: text the console SENDS into a thread is read by the + // cloud confirm gate (service-ai-studio confirm-gate.ts APPROVAL_RE), which + // decides whether the text counts as approval. // // `GATE` below is a verbatim mirror of that regex. It is duplicated across // repo boundaries on purpose — objectui cannot import from cloud — so when // APPROVAL_RE changes there, update this copy in the same breath. - // - // How this guard earned its keep: it originally mirrored only the CHINESE - // clause, and the English half was reduced to "starts with Confirm, contains - // apply" because nothing here could see the real pattern. That weaker check - // passed while the shipped English string ("…apply what you just proposed") - // did NOT match the gate — every English conversation's Confirm button was - // dead, and so were all eight locales that fall back to English. const GATE = /直接搭建|直接建|直接帮我(建|搭)|不用再?问我?|别再?问我?|无需确认|不用确认|确认[,,、]?\s*(开始|可以|并|要)?\s*(搭建|创建|生成|构建|修改|应用|执行|继续)|应用(你|您|刚才|这个?|那个?|该|上述|提议|建议)+的?\s*(改动|修改|变更|更改)|^\s*确[认定][。.!!\s]*$|just build it|go ahead and build|start building|build it now|don'?t ask|without confirmation|build it as proposed|build it with your best|apply (this|the) change/i; - // Only the APPROVAL messages. `planAnswerMessage` is deliberately absent: it - // answers a structure question so the agent can continue, and must NOT read - // as blanket approval. - const APPROVAL_KEYS = [ - 'console.ai.planApproveMessage', - 'console.ai.planApproveDefaultsMessage', - 'console.ai.changesConfirmMessage', - ] as const; - - it.each(['zh', 'en'])( - 'every outbound approval message the %s console sends satisfies the cloud confirm gate', - (lang) => { - const i18n = createI18n({ defaultLanguage: lang, detectBrowserLanguage: false }); - for (const key of APPROVAL_KEYS) { - const msg = i18n.t(key); - expect(msg, `${key} must not fall through to its raw key`).not.toBe(key); - expect(msg, `${lang} ${key} does not match the cloud APPROVAL_RE`).toMatch(GATE); - } - }, - ); - it('the gate stays narrow — a plain build request is not approval', () => { // If these ever match, the preview-first gate has been widened into // uselessness and the mirror above is no longer worth trusting. @@ -163,30 +120,6 @@ describe('@object-ui/i18n', () => { expect('我不确定这样对不对').not.toMatch(GATE); }); - it('planAnswerMessage answers a question without reading as approval', () => { - const i18n = createI18n({ defaultLanguage: 'en', detectBrowserLanguage: false }); - const msg = i18n.t('console.ai.planAnswerMessage', { - question: 'One shelf or many?', - option: 'many', - }); - expect(msg).not.toMatch(GATE); - }); - - it('the extend-or-new answers answer a question without reading as approval (objectstack#27480)', () => { - // An `iterate_or_new` plan overlaps an app that already exists, and its - // two answers tell the agent which way to go. Read as approval, either - // one would let the gate build the overlapping plan exactly as proposed — - // the one-click duplicate the question exists to prevent. - for (const lang of ['zh', 'en']) { - const i18n = createI18n({ defaultLanguage: lang, detectBrowserLanguage: false }); - for (const key of ['console.ai.planExtendExistingMessage', 'console.ai.planBuildNewAppMessage']) { - const msg = i18n.t(key, { app: 'Library' }); - expect(msg, `${lang} ${key} must not fall through to its raw key`).not.toBe(key); - expect(msg, `${lang} ${key} reads as approval to the cloud APPROVAL_RE`).not.toMatch(GATE); - } - } - }); - it('the inline HITL deny reason never reads as approval, in any pack (objectui#11667)', () => { // `console.ai.toolDenyReason` is a label — it follows the UI locale, so // all ten packs define it — but it does not stay on screen: the reject diff --git a/ui/packages/i18n/src/__tests__/makerEditChips-v1-scope-7709.test.ts b/ui/packages/i18n/src/__tests__/makerEditChips-v1-scope-7709.test.ts deleted file mode 100644 index 1fa884da450..00000000000 --- a/ui/packages/i18n/src/__tests__/makerEditChips-v1-scope-7709.test.ts +++ /dev/null @@ -1,160 +0,0 @@ -/** - * ObjectUI - * Copyright (c) 2024-present ObjectStack Inc. - * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. - */ - -/** - * objectui#7709 — the maker's EDIT-mode start chips, the sibling family of the - * five guarded by `makerStartChips-v1-scope-1984.test.ts`. - * - * `editAppSuggestions()` renders four starters when the build surface is bound - * to an EXISTING app (`?package=`). Three of them ask for structure — a field, - * an object, a dashboard — and all three are inside ADR-0112 v1's whitelist. - * The fourth was `addAutomation`: 「加一个自动化 —— 审批、状态流转或通知」, - * and approval / status flow / notification are ALL refused by v1 (cloud#1956 / - * PR #1970). Worse than a refusal, measured on the sibling chips: the model - * silently DEGRADES such a request into a view, so the chip promised an - * automation and delivered a page. - * - * The product ruling (epic cloud#1955, 2026-09-05) replaced it rather than - * dropping it: the three surviving chips all add STRUCTURE, and what an - * existing app most often lacks is DATA — `seed` is on v1's whitelist - * (`V1_METADATA_TYPES` in cloud `service-ai-studio/src/authoring-whitelist.ts`, - * commented "sample data"), so the fourth chip now asks for sample records. - * - * Same three-part shape as the 1984 suite, and the third part is what keeps the - * other two honest: - * - * 1. Every shipped pack carries all four chips, non-empty, and no fifth. - * 2. No chip in any pack uses vocabulary that promises autonomous behaviour or - * an approval, scanned with that pack's OWN banned list — an English-only - * scan would have declared the five non-Latin packs clean without reading a - * character of them (AGENTS.md i18n forensics rule). - * 3. A NON-VACUITY control: each pack's banned list is re-run against the - * `addAutomation` wording that pack actually shipped before this card, and - * must flag it. - * - * REVERT the wording (and relax this suite) when ADR-0112 v2 re-adds flows and - * actions — the note beside the keys in every pack says so, and RETIRED below - * is where that pack's automation sentence is kept. - */ -import { describe, it, expect } from 'vitest'; -import { PLATFORM_LOCALE_TAGS } from '@objectstack/spec/system'; -import { builtInLocales } from '../locales'; - -type LocaleCode = keyof typeof builtInLocales; -const LANGS = Object.keys(builtInLocales) as LocaleCode[]; - -/** The four chips `editAppSuggestions()` renders, in order. */ -const CHIP_KEYS = ['addField', 'addObject', 'addDashboard', 'addSampleData'] as const; - -/** The pack's edit-mode chip block, reached through the shape the call site reads. */ -const chipsOf = (lang: LocaleCode) => - ( - builtInLocales[lang] as { - console?: { ai?: { suggestions?: { editApp?: Record } } }; - } - ).console?.ai?.suggestions?.editApp; - -/** - * Vocabulary that promises the product will ACT on its own — an automation, an - * approval, a status workflow, an alert, a reminder, a notification, a trigger, - * a schedule. Per locale, because the whole point is that the check reads each - * pack in its own script; substring matching with no ASCII word classes, since - * five of the ten packs are non-Latin and CJK has no word boundaries. - * - * The automation half is the `makerStartChips-v1-scope-1984` list verbatim (one - * v1 boundary, two families reading it). The approval half is added here: this - * chip's retired wording led with 审批 / approval, which that list did not name. - * - * Stems, not whole words: `automat` covers automate/automatic/automation and - * their Romance cognates, `notifi` covers notify/notification/notificación, - * `aprob` covers aprobación/aprobar. - */ -const BANNED: Record = { - en: ['alert', 'remind', 'notif', 'automat', 'workflow', 'trigger', 'schedule', 'approv'], - 'zh-Hans': ['提醒', '预警', '警报', '自动', '流转', '通知', '触发', '定时', '审批'], - 'zh-Hant': ['提醒', '預警', '警報', '自動', '流轉', '通知', '觸發', '定時', '審批'], - de: ['automat', 'erinner', 'warnung', 'alarm', 'benachrichtig', 'workflow', 'auslös', 'ablauf', 'freigabe', 'genehmig'], - fr: ['automat', 'alerte', 'rappel', 'notifi', 'workflow', 'flux', 'déclench', 'approbation', 'approuv'], - es: ['automat', 'alerta', 'recordar', 'recordatorio', 'notifi', 'flujo', 'disparador', 'aprob'], - 'pt-BR': ['automa', 'alerta', 'lembr', 'notifi', 'fluxo', 'gatilho', 'aprova'], - ru: ['автомат', 'оповещ', 'уведомл', 'напомин', 'триггер', 'процесс', 'поток', 'согласован', 'утвержд'], - ja: ['自動', '通知', 'アラート', 'リマイン', 'ワークフロー', 'フロー', 'トリガー', '承認'], - ko: ['자동', '알림', '알람', '워크플로', '흐름', '트리거', '승인'], - ar: ['أتمتة', 'مؤتمت', 'تنبيه', 'إشعار', 'تذكير', 'سير عمل', 'موافقة', 'اعتماد'], -}; - -/** Every banned term this text hits, lower-cased for the case-insensitive scripts. */ -function bannedHits(lang: LocaleCode, text: string): string[] { - const haystack = text.toLocaleLowerCase(lang === 'zh-Hans' || lang === 'zh-Hant' ? lang : undefined); - return BANNED[lang].filter((term) => haystack.includes(term.toLocaleLowerCase())); -} - -/** - * The `addAutomation` sentence each pack shipped BEFORE this card. Kept as the - * control sample AND as the record of what ADR-0112 v2 restores — not as a - * fixture to revert to today. - */ -const RETIRED: Record = { - en: 'Add an automation — an approval, a status flow, or a notification.', - 'zh-Hans': '加一个自动化 —— 审批、状态流转或通知。', - 'zh-Hant': '加一個自動化 —— 審批、狀態流轉或通知。', - de: 'Füge eine Automatisierung hinzu — eine Freigabe, einen Statusablauf oder eine Benachrichtigung.', - fr: 'Ajoute une automatisation — une approbation, un flux de statuts ou une notification.', - es: 'Añade una automatización — una aprobación, un flujo de estados o una notificación.', - 'pt-BR': 'Adicione uma automação — uma aprovação, um fluxo de status ou uma notificação.', - ru: 'Добавь автоматизацию — согласование, процесс статусов или уведомление.', - ja: '自動化を追加してください — 承認、ステータスフロー、または通知。', - ko: '자동화를 추가해 주세요 — 승인, 상태 흐름 또는 알림.', - ar: 'أضف أتمتة — موافقة أو سير حالات أو إشعارًا.', -}; - -describe('maker edit-mode chips — every shipped pack carries all four (objectui#7709)', () => { - it('covers all ten built-in packs', () => { - expect(LANGS).toHaveLength(PLATFORM_LOCALE_TAGS.length); - }); - - it.each(LANGS)('%s defines a non-empty string for every chip', (lang) => { - const block = chipsOf(lang); - expect(block, `${lang} has no console.ai.suggestions.editApp block`).toBeTruthy(); - for (const key of CHIP_KEYS) { - expect(typeof block![key], `${lang}.${key}`).toBe('string'); - expect(block![key].trim().length, `${lang}.${key} is empty`).toBeGreaterThan(0); - } - // No chip beyond the four the call site renders, and — the half that - // matters here — no `addAutomation` left behind in any pack. - expect(Object.keys(block!).sort()).toEqual([...CHIP_KEYS].sort()); - }); - - it.each(LANGS)('%s: the four chips are four DIFFERENT asks', (lang) => { - // The replacement had to avoid duplicating the three chips beside it — - // that is precisely why "reword it like the other five" was not available - // and this became its own product call. - const block = chipsOf(lang)!; - const values = CHIP_KEYS.map((k) => block[k].trim()); - expect(new Set(values).size, `${lang}: ${values.join(' | ')}`).toBe(CHIP_KEYS.length); - }); -}); - -describe('maker edit-mode chips — none promises autonomous behaviour (objectui#7709)', () => { - it.each(LANGS)('%s: no chip uses that pack`s automation/approval vocabulary', (lang) => { - const block = chipsOf(lang)!; - for (const key of CHIP_KEYS) { - expect(bannedHits(lang, block[key]), `${lang}.${key}: "${block[key]}"`).toEqual([]); - } - }); - - it.each(LANGS)('%s: the banned list still flags the wording this pack retired', (lang) => { - // Non-vacuity. A green run above means nothing unless this is green too. - expect(bannedHits(lang, RETIRED[lang]).length, `${lang} control: "${RETIRED[lang]}"`).toBeGreaterThan(0); - }); - - it('the replaced chip asks for DATA, in the two languages the card quoted', () => { - expect(chipsOf('en')!.addSampleData).toContain('sample records'); - expect(chipsOf('zh-Hans')!.addSampleData).toContain('示例数据'); - }); -}); diff --git a/ui/packages/i18n/src/__tests__/makerEmptyState-v1-scope-8329.test.ts b/ui/packages/i18n/src/__tests__/makerEmptyState-v1-scope-8329.test.ts deleted file mode 100644 index c4419b8d31e..00000000000 --- a/ui/packages/i18n/src/__tests__/makerEmptyState-v1-scope-8329.test.ts +++ /dev/null @@ -1,236 +0,0 @@ -/** - * ObjectUI - * Copyright (c) 2024-present ObjectStack Inc. - * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. - */ - -/** - * objectui#8329 — the maker's EMPTY-STATE prose, third and last member of the - * ADR-0112 v1 boundary family on the build surface: - * - * 1. the five from-scratch start chips — cloud#1984 / objectui#7710 - * 2. the four edit-mode start chips — objectui#7709 - * 3. the model's own closing suggestions— cloud#2020 / cloud#2022 - * 4. ⬅ THIS: the two sentences ABOVE all of them - * - * `agentEmptyState()` renders a title and a description under the build - * surface's heading. The description is the FIRST sentence a new user reads on - * that page, and both variants were promising capabilities v1 refuses: - * - * build.description 'Describe an app or workflow in plain language — I draft - * the objects, screens and automations, …' - * editApp.description '… add a field, object, view or automation, …' - * - * v1 has no flows, actions or schedules (`V1_METADATA_TYPES` in cloud - * `service-ai-studio/src/authoring-whitelist.ts`), so a user who took either - * sentence at its word was refused outright — and unlike a chip, this one is - * read before anything else on the screen. Both now name only what v1 builds. - * - * Same three-part shape as the 1984 / 7709 suites, and part 3 is what keeps the - * other two honest: - * - * 1. Every shipped pack defines both descriptions, non-empty. - * 2. Neither description in any pack uses vocabulary that promises autonomous - * behaviour, scanned with that pack's OWN banned list — an English-only - * scan would have declared the five non-Latin packs clean without reading a - * character of them (AGENTS.md i18n forensics rule). This is not - * hypothetical here: all ten packs shipped a translated violation, so the - * issue's premise that "only en and zh have this key" was wrong. - * 3. A NON-VACUITY control: each pack's banned list is re-run against the two - * sentences that pack actually shipped before this card, and must flag both. - * - * ⚠️ Scope note — this suite guards the AI-AUTHORING promise, not the word - * "automation". The platform's manual automation surfaces are real and are - * deliberately NOT covered: `home.build.subtitle` (its card opens Studio, which - * genuinely authors flows), `packagedAutomation.*`, the marketplace - * `automation` category, and the approvals / flow-runner groups. - * - * REVERT the wording (and relax this suite) when ADR-0112 v2 re-adds flows and - * actions — same line of the roadmap as the chips. RETIRED below is where each - * pack's automation sentence is kept. - */ -import { describe, it, expect } from 'vitest'; -import { PLATFORM_LOCALE_TAGS } from '@objectstack/spec/system'; -import { builtInLocales } from '../locales'; - -type LocaleCode = keyof typeof builtInLocales; -const LANGS = Object.keys(builtInLocales) as LocaleCode[]; - -/** The two descriptions `agentEmptyState()` can render on the build surface. */ -const VARIANTS = ['build', 'editApp'] as const; -type Variant = (typeof VARIANTS)[number]; - -/** The pack's empty-state block, reached through the shape the call site reads. */ -const emptyOf = (lang: LocaleCode) => - ( - builtInLocales[lang] as { - console?: { - ai?: { empty?: Record }; - }; - } - ).console?.ai?.empty; - -const descriptionOf = (lang: LocaleCode, v: Variant) => emptyOf(lang)?.[v]?.description; - -/** - * Vocabulary that promises the product will ACT on its own. The automation half - * is the `makerStartChips-v1-scope-1984` / `makerEditChips-v1-scope-7709` list - * verbatim — one v1 boundary, three families reading it. Added here: the - * "workflow" noun each pack used in the RETIRED build sentence, which the chip - * lists did not all need (`流程` for zh, whose chip wording said `流转`). - * - * Stems, not whole words, and substring matching with no ASCII word classes — - * five of the ten packs are non-Latin and CJK has no word boundaries. - */ -const BANNED: Record = { - en: ['alert', 'remind', 'notif', 'automat', 'workflow', 'trigger', 'schedule', 'approv'], - 'zh-Hans': ['提醒', '预警', '警报', '自动', '流转', '流程', '工作流', '通知', '触发', '定时', '审批'], - 'zh-Hant': ['提醒', '預警', '警報', '自動', '流轉', '流程', '工作流', '通知', '觸發', '定時', '審批'], - de: ['automat', 'erinner', 'warnung', 'alarm', 'benachrichtig', 'workflow', 'auslös', 'ablauf', 'freigabe', 'genehmig'], - fr: ['automat', 'alerte', 'rappel', 'notifi', 'workflow', 'flux', 'déclench', 'approbation', 'approuv'], - es: ['automat', 'alerta', 'recordar', 'recordatorio', 'notifi', 'flujo', 'disparador', 'aprob'], - 'pt-BR': ['automa', 'alerta', 'lembr', 'notifi', 'fluxo', 'gatilho', 'aprova'], - ru: ['автомат', 'оповещ', 'уведомл', 'напомин', 'триггер', 'процесс', 'поток', 'согласован', 'утвержд'], - ja: ['自動', '通知', 'アラート', 'リマイン', 'ワークフロー', 'フロー', 'トリガー', '承認'], - ko: ['자동', '알림', '알람', '워크플로', '흐름', '트리거', '승인'], - ar: ['أتمتة', 'مؤتمت', 'تنبيه', 'إشعار', 'تذكير', 'سير عمل', 'موافقة', 'اعتماد'], -}; - -/** Every banned term this text hits, lower-cased for the case-insensitive scripts. */ -function bannedHits(lang: LocaleCode, text: string): string[] { - const haystack = text.toLocaleLowerCase(lang === 'zh-Hans' || lang === 'zh-Hant' ? lang : undefined); - return BANNED[lang].filter((term) => haystack.includes(term.toLocaleLowerCase())); -} - -/** - * The two sentences each pack shipped BEFORE this card. Kept as the control - * sample AND as the record of what ADR-0112 v2 restores — not as a fixture to - * revert to today. - */ -const RETIRED: Record> = { - en: { - build: 'Describe an app or workflow in plain language — I draft the objects, screens and automations, then you review and publish.', - editApp: 'What would you like to change? I’ll modify this app in place — add a field, object, view or automation, or adjust what’s already there.', - }, - 'zh-Hans': { - build: '用自然语言描述一个应用或流程 —— 我会起草对象、界面和自动化,随后你审阅并发布。', - editApp: '想改点什么?我会就地修改这个应用 —— 加字段、对象、视图或自动化,或调整已有内容。', - }, - 'zh-Hant': { - build: '用自然語言描述一個應用或流程 —— 我會起草物件、介面和自動化,隨後你審閱並發布。', - editApp: '想改點什麼?我會就地修改這個應用 —— 加欄位、物件、檢視或自動化,或調整已有內容。', - }, - de: { - build: 'Beschreiben Sie eine App oder einen Workflow in einfachen Worten — ich entwerfe die Objekte, Bildschirme und Automatisierungen, dann prüfen und veröffentlichen Sie.', - editApp: 'Was möchten Sie ändern? Ich passe diese App direkt an — ein Feld, Objekt, eine Ansicht oder Automatisierung hinzufügen oder Vorhandenes anpassen.', - }, - fr: { - build: 'Décrivez une application ou un flux de travail en langage courant — je rédige les objets, les écrans et les automatisations, puis vous vérifiez et publiez.', - editApp: "Que souhaitez-vous changer ? Je modifie cette application sur place — ajouter un champ, un objet, une vue ou une automatisation, ou ajuster l'existant.", - }, - es: { - build: 'Describa una aplicación o un flujo de trabajo en lenguaje natural — yo redacto los objetos, las pantallas y las automatizaciones, y luego usted revisa y publica.', - editApp: '¿Qué desea cambiar? Modifico esta aplicación sobre la marcha — añadir un campo, un objeto, una vista o una automatización, o ajustar lo que ya existe.', - }, - 'pt-BR': { - build: 'Descreva um aplicativo ou fluxo de trabalho em linguagem simples — eu rascunho os objetos, telas e automações, e então você revisa e publica.', - editApp: 'O que você quer mudar? Eu altero este aplicativo no lugar — adicionar um campo, objeto, visão ou automação, ou ajustar o que já existe.', - }, - ru: { - build: 'Опишите приложение или процесс обычными словами — я подготовлю объекты, экраны и автоматизации, а вы проверите и опубликуете.', - editApp: 'Что нужно изменить? Я изменю это приложение на месте — добавлю поле, объект, представление или автоматизацию либо скорректирую существующее.', - }, - ja: { - build: 'アプリやワークフローを普通の言葉で説明してください — オブジェクト、画面、自動化を下書きしますので、確認して公開してください。', - editApp: '何を変更しますか?このアプリをその場で変更します — 項目、オブジェクト、ビュー、自動化の追加や、既存部分の調整ができます。', - }, - ko: { - build: '앱이나 워크플로를 일상 언어로 설명해 주세요 — 객체, 화면, 자동화를 초안으로 만들어 드리면 검토 후 게시하시면 됩니다.', - editApp: '무엇을 바꿀까요? 이 앱을 그 자리에서 수정합니다 — 필드, 객체, 뷰, 자동화를 추가하거나 기존 내용을 조정할 수 있습니다.', - }, - ar: { - build: 'صف تطبيقًا أو سير عمل بلغة بسيطة — سأعدّ مسودة الكائنات والشاشات والأتمتة، ثم تراجعها وتنشرها.', - editApp: 'ما الذي تريد تغييره؟ سأعدّل هذا التطبيق في مكانه — إضافة حقل أو كائن أو عرض أو أتمتة، أو تعديل ما هو موجود.', - }, -}; - -describe('maker empty state — every shipped pack carries both descriptions (objectui#8329)', () => { - it('covers all ten built-in packs', () => { - expect(LANGS).toHaveLength(PLATFORM_LOCALE_TAGS.length); - }); - - it.each(LANGS)('%s defines a non-empty description for both variants', (lang) => { - const block = emptyOf(lang); - expect(block, `${lang} has no console.ai.empty block`).toBeTruthy(); - for (const v of VARIANTS) { - const d = descriptionOf(lang, v); - expect(typeof d, `${lang}.empty.${v}.description`).toBe('string'); - expect(d!.trim().length, `${lang}.empty.${v}.description is empty`).toBeGreaterThan(0); - } - }); - - it.each(LANGS)('%s still carries the titles the two variants render', (lang) => { - // The fix touched descriptions only; a pack that lost a title would fall - // back to the English defaultValue without any test noticing. - const block = emptyOf(lang)!; - expect(block.build?.title?.trim()).toBeTruthy(); - expect(block.editApp?.title?.trim()).toBeTruthy(); - }); -}); - -describe('maker empty state — neither description promises autonomous behaviour (objectui#8329)', () => { - it.each(LANGS)("%s: neither description uses that pack's automation vocabulary", (lang) => { - for (const v of VARIANTS) { - const d = descriptionOf(lang, v)!; - expect(bannedHits(lang, d), `${lang}.empty.${v}.description: "${d}"`).toEqual([]); - } - }); - - it.each(LANGS)('%s: the banned list still flags BOTH sentences this pack retired', (lang) => { - // Non-vacuity. A green run above means nothing unless this is green too — - // and it must flag both variants, not just the louder `build` one. - for (const v of VARIANTS) { - const retired = RETIRED[lang][v]; - expect( - bannedHits(lang, retired).length, - `${lang} control (${v}): "${retired}"`, - ).toBeGreaterThan(0); - } - }); - - it.each(LANGS)('%s: the description actually changed from what it retired', (lang) => { - // Guards the reverse mistake of a pack being "fixed" by copying its own old - // string back in during a merge. - for (const v of VARIANTS) { - expect(descriptionOf(lang, v), `${lang}.${v}`).not.toBe(RETIRED[lang][v]); - } - }); -}); - -describe('maker empty state — the replacement names v1 capabilities (objectui#8329)', () => { - it('en/zh build: offers an app (not a workflow) and sample data', () => { - const en = descriptionOf('en', 'build')!; - expect(en).toMatch(/describe an app/i); - expect(en).toContain('sample data'); - - const zh = descriptionOf('zh-Hans', 'build')!; - expect(zh).toContain('示例数据'); - expect(zh).not.toContain('或流程'); - }); - - it('en/zh editApp: offers a dashboard in the slot automation used to hold', () => { - expect(descriptionOf('en', 'editApp')!).toContain('dashboard'); - expect(descriptionOf('zh-Hans', 'editApp')!).toContain('仪表盘'); - }); - - it('en editApp keeps the in-place framing its own unit test asserts', () => { - // `packages/app-shell/src/console/ai/__tests__/editModeEmptyState.test.ts` - // matches /change/i and /in place/i against the defaultValue; the pack and - // that fallback must not drift apart. - const en = descriptionOf('en', 'editApp')!; - expect(en).toMatch(/change/i); - expect(en).toMatch(/in place/i); - }); -}); diff --git a/ui/packages/i18n/src/__tests__/makerStartChips-v1-scope-1984.test.ts b/ui/packages/i18n/src/__tests__/makerStartChips-v1-scope-1984.test.ts deleted file mode 100644 index 3d4fda5b79c..00000000000 --- a/ui/packages/i18n/src/__tests__/makerStartChips-v1-scope-1984.test.ts +++ /dev/null @@ -1,148 +0,0 @@ -/** - * ObjectUI - * Copyright (c) 2024-present ObjectStack Inc. - * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. - */ - -/** - * cloud#1984 — the maker's five start chips are the PRODUCT's own - * recommendations, so what they ask for has to be what the product builds. - * - * ADR-0112 v1 (cloud#1956 / PR #1970) authors objects, fields, views, pages, - * dashboards and sample data; it has no flows, actions or schedules. The - * measured behaviour of the two chips that asked for automation was NOT a - * refusal — the model silently degraded 「状态流转」 into a status board and - * 「低库存预警」 into a filtered view — so the user was promised an alert and - * handed a page. This suite is the standing guard on that gap. - * - * Three things, and the third is what keeps the other two honest: - * - * 1. Every shipped pack carries all five chips, non-empty. (`all-locales-key- - * parity` already enforces en ↔ pack KEY parity generically; the value side - * is what matters here.) - * 2. No chip in any pack uses vocabulary that promises autonomous behaviour, - * scanned with that pack's OWN banned list — an English-only scan would - * have declared the five non-Latin packs clean without reading a character - * of them (AGENTS.md i18n forensics rule). - * 3. A NON-VACUITY control: each pack's banned list is re-run against the - * RETIRED wording that pack actually shipped before this card, and must - * flag it. Without this, deleting a term from a banned list (or getting a - * locale's spelling wrong) would leave every assertion green while - * checking nothing. - * - * REVERT the wording (and relax this suite) when ADR-0112 v2 re-adds flows and - * actions — see the note beside the keys in every pack. - */ -import { describe, it, expect } from 'vitest'; -import { PLATFORM_LOCALE_TAGS } from '@objectstack/spec/system'; -import { builtInLocales } from '../locales'; - -type LocaleCode = keyof typeof builtInLocales; -const LANGS = Object.keys(builtInLocales) as LocaleCode[]; - -/** The five chips `metadataAssistantSuggestions()` renders, in order. */ -const CHIP_KEYS = ['buildCrm', 'buildApp', 'buildFlow', 'buildInventory', 'buildRecruiting'] as const; - -/** The pack's chip block, reached through the one shape the call site reads. */ -const chipsOf = (lang: LocaleCode) => - ( - builtInLocales[lang] as { - console?: { ai?: { suggestions?: { metadataAssistant?: Record } } }; - } - ).console?.ai?.suggestions?.metadataAssistant; - -/** - * Vocabulary that promises the product will ACT on its own — an alert, a - * reminder, a notification, an automation, a status workflow, a trigger, a - * schedule. Per locale, because the whole point is that the check reads each - * pack in its own script; `u` + substring matching (never ASCII `\w`), since - * five of the ten packs are non-Latin and CJK has no word boundaries. - * - * Stems, not whole words: `automat` covers automate/automatic/automation and - * their Romance cognates, `notifi` covers notify/notification/notificación. - */ -const BANNED: Record = { - en: ['alert', 'remind', 'notif', 'automat', 'workflow', 'trigger', 'schedule'], - 'zh-Hans': ['提醒', '预警', '警报', '自动', '流转', '通知', '触发', '定时'], - 'zh-Hant': ['提醒', '預警', '警報', '自動', '流轉', '通知', '觸發', '定時'], - de: ['automat', 'erinner', 'warnung', 'alarm', 'benachrichtig', 'workflow', 'auslös', 'ablauf'], - fr: ['automat', 'alerte', 'rappel', 'notifi', 'workflow', 'flux', 'déclench'], - es: ['automat', 'alerta', 'recordar', 'recordatorio', 'notifi', 'flujo', 'disparador'], - 'pt-BR': ['automa', 'alerta', 'lembr', 'notifi', 'fluxo', 'gatilho'], - ru: ['автомат', 'оповещ', 'уведомл', 'напомин', 'триггер', 'процесс', 'поток'], - ja: ['自動', '通知', 'アラート', 'リマイン', 'ワークフロー', 'フロー', 'トリガー'], - ko: ['자동', '알림', '알람', '워크플로', '흐름', '트리거'], - ar: ['أتمتة', 'مؤتمت', 'تنبيه', 'إشعار', 'تذكير', 'سير عمل'], -}; - -/** Every banned term this text hits, lower-cased for the case-insensitive scripts. */ -function bannedHits(lang: LocaleCode, text: string): string[] { - const haystack = text.toLocaleLowerCase(lang === 'zh-Hans' || lang === 'zh-Hant' ? lang : undefined); - return BANNED[lang].filter((term) => haystack.includes(term.toLocaleLowerCase())); -} - -/** - * The wording each pack shipped BEFORE cloud#1984 — the ticket chip's status - * workflow, plus the two the card quoted verbatim (zh's 低库存预警, ar's - * تنبيه لانخفاض المخزون). Kept as the control sample, NOT as a fixture to - * revert to: it is here only so a banned list that has stopped working fails - * loudly instead of passing silently. - */ -const RETIRED: Record = { - en: ['Design a support desk — tickets with priority, a status workflow, and customer links.'], - 'zh-Hans': ['设计一个工单系统:工单、优先级、状态流转。', '做一个库存管理应用:商品、库存量、供应商,以及低库存预警。'], - 'zh-Hant': ['設計一個工單系統:工單、優先順序、狀態流轉。', '做一個庫存管理應用:商品、庫存量、供應商,以及低庫存預警。'], - de: ['Entwirf einen Support-Desk — Tickets mit Priorität, einen Status-Workflow und Kundenverknüpfungen.'], - fr: ["Conçois un service d'assistance — tickets avec priorité, un flux de statuts et des liens vers les clients."], - es: ['Diseña una mesa de ayuda — tickets con prioridad, un flujo de estados y vínculos con los clientes.'], - 'pt-BR': ['Projete uma central de suporte — chamados com prioridade, um fluxo de status e vínculos com clientes.'], - ru: ['Спроектируй службу поддержки — заявки с приоритетом, процесс статусов и связи с клиентами.'], - ja: ['サポートデスクを設計して — 優先度つきチケット、ステータスのワークフロー、顧客との紐付け。'], - ko: ['고객 지원 데스크를 설계해 줘 — 우선순위가 있는 티켓, 상태 워크플로, 고객 연결.'], - ar: ['صمّم مكتب دعم — تذاكر بأولوية وسير عمل للحالات وروابط بالعملاء.', 'أنشئ تطبيق مخزون — منتجات ومستويات مخزون وموردين وتنبيه لانخفاض المخزون.'], -}; - -describe('maker start chips — every shipped pack carries all five (cloud#1984)', () => { - it('covers all ten built-in packs', () => { - expect(LANGS).toHaveLength(PLATFORM_LOCALE_TAGS.length); - }); - - it.each(LANGS)('%s defines a non-empty string for every chip', (lang) => { - const block = chipsOf(lang); - expect(block, `${lang} has no console.ai.suggestions.metadataAssistant block`).toBeTruthy(); - for (const key of CHIP_KEYS) { - expect(typeof block![key], `${lang}.${key}`).toBe('string'); - expect(block![key].trim().length, `${lang}.${key} is empty`).toBeGreaterThan(0); - } - // No chip beyond the five the call site renders — an extra key is a chip - // nobody sees, and a sixth chip means the call site changed without this. - expect(Object.keys(block!).sort()).toEqual([...CHIP_KEYS].sort()); - }); -}); - -describe('maker start chips — none promises autonomous behaviour (cloud#1984)', () => { - it.each(LANGS)('%s: no chip uses that pack`s automation vocabulary', (lang) => { - const block = chipsOf(lang)!; - for (const key of CHIP_KEYS) { - expect(bannedHits(lang, block[key]), `${lang}.${key}: "${block[key]}"`).toEqual([]); - } - }); - - it.each(LANGS)('%s: the banned list still flags the wording this pack retired', (lang) => { - // Non-vacuity. A green run above means nothing unless this is green too. - for (const retired of RETIRED[lang]) { - expect(bannedHits(lang, retired).length, `${lang} control: "${retired}"`).toBeGreaterThan(0); - } - }); - - it('the two chips the card named read as UI, not as automation', () => { - const zh = chipsOf('zh-Hans')!; - // 「状态流转」 → a board grouped by status; 「低库存预警」 → a filtered view. - expect(zh.buildFlow).toContain('看板'); - expect(zh.buildFlow).not.toContain('流转'); - expect(zh.buildInventory).toContain('视图'); - expect(zh.buildInventory).not.toContain('预警'); - }); -}); diff --git a/ui/packages/i18n/src/__tests__/outbound-agent-messages.test.ts b/ui/packages/i18n/src/__tests__/outbound-agent-messages.test.ts deleted file mode 100644 index 08bd19b9827..00000000000 --- a/ui/packages/i18n/src/__tests__/outbound-agent-messages.test.ts +++ /dev/null @@ -1,110 +0,0 @@ -// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license. - -/** - * Guard: the strings the console SENDS to the AI agent must not be translated - * into arbitrary locales. - * - * Most `console.ai.*` keys are labels and should be localized everywhere. The - * ones in `OUTBOUND_KEYS` below are not labels — they are the message text a - * button transmits to the agent, - * and the cloud confirm gate (`service-ai-studio` `confirm-gate.ts` - * `APPROVAL_RE`) decides whether that text counts as approval. It recognises - * Chinese and English. Nothing else. - * - * So `AiChatPage` picks them by the language of the CONVERSATION, not the UI — - * since objectui#3896 through one resolver - * (`packages/app-shell/src/console/ai/outboundAgentText.ts`) that reads the two - * gate packs directly and never calls `t()` for these keys: - * - * zh conversation -> the `zh-Hans` pack's value // matches the gate - * anything else -> the `en` pack's value // matches the gate - * - * ## What this test guarantees, stated as what it asserts - * - * Exactly two packs define these keys: `en` and `zh-Hans` (the Simplified pack, - * exported as `zh`). That is the whole claim. Every other pack is judged — the - * population is `builtInLocales`, typed on the platform locale table, so a pack - * the table gains is judged on the run that first sees it (objectstack#30511). - * The generated `zh-Hant` pack is one of them: `scripts/zh-hant.mjs` drops these - * lines from it (`GATE_ONLY_KEYS`), since a Traditional copy would be a third - * spelling the gate does not recognise. - * It is NOT "a `t()` lookup MISSes in every non-Chinese pack" — the wording this - * header carried until #3896, which was false for `zh` and was the premise the - * bug hid behind: `zh` defines all four, so the `t()` fallback HIT and a zh - * console sent `确认,开始搭建。` into an English thread. - * - * ## Why the claim still earns its keep after #3896 - * - * A translation added to a ninth pack is now DEAD rather than dangerous — the - * resolver never reads that pack, so the value can never be sent, and an - * unreachable pack value is its own defect class (objectui#3837). Before #3896 - * it was actively harmful: the value WAS sent, the gate stopped matching, the - * agent re-proposed instead of building, and the button merely looked inert - * while nothing visibly errored. objectui#2900 shipped exactly that for - * `changesConfirmMessage`. - * - * If the gate ever learns more languages, teach the resolver in the same change - * that deletes the offending entry here — not before. - */ -import { describe, it, expect } from 'vitest'; -import { builtInLocales, en, zh } from '../locales'; - -const OUTBOUND_KEYS = [ - 'console.ai.planApproveMessage', - 'console.ai.planApproveDefaultsMessage', - 'console.ai.planAnswerMessage', - 'console.ai.planExtendExistingMessage', - 'console.ai.planBuildNewAppMessage', - 'console.ai.changesConfirmMessage', -] as const; - -const GATE_LOCALES: Record = { en, 'zh-Hans': zh }; -const NON_GATE_LOCALES: Record = Object.fromEntries( - Object.entries(builtInLocales).filter(([tag]) => !Object.prototype.hasOwnProperty.call(GATE_LOCALES, tag)), -); - -function lookup(pack: unknown, dotted: string): unknown { - return dotted - .split('.') - .reduce((node, part) => (node as Record)?.[part], pack); -} - -describe('outbound agent messages stay on gate-recognised languages', () => { - it('judges every non-gate pack, the generated zh-Hant one included', () => { - expect(Object.keys(NON_GATE_LOCALES)).toContain('zh-Hant'); - expect(Object.keys(NON_GATE_LOCALES)).toHaveLength(Object.keys(builtInLocales).length - 2); - }); - - it.each(Object.keys(NON_GATE_LOCALES))( - 'the %s pack defines none of them — a value there could never be sent', - (lang) => { - const offenders = OUTBOUND_KEYS.filter( - (k) => lookup(NON_GATE_LOCALES[lang], k) !== undefined, - ); - expect(offenders).toEqual([]); - }, - ); - - it.each(Object.keys(GATE_LOCALES))('the %s pack defines all of them', (lang) => { - // Both halves are load-bearing since #3896: the resolver reads `zh-Hans` for a - // Chinese conversation and `en` for every other one, so a key missing from - // either pack drops that language onto the resolver's fallback table. - for (const k of OUTBOUND_KEYS) { - expect(typeof lookup(GATE_LOCALES[lang], k)).toBe('string'); - } - }); - - it('every OTHER console.ai key IS localized — this guard is narrow on purpose', () => { - // Guards against over-correcting: the fix for the outbound keys must not - // become a reason to leave the surrounding labels untranslated. - const aiLabels = Object.keys((en as any).console.ai).filter( - (k) => typeof (en as any).console.ai[k] === 'string', - ); - const outboundLeaf = new Set(OUTBOUND_KEYS.map((k) => k.split('.').pop())); - const labels = aiLabels.filter((k) => !outboundLeaf.has(k)); - expect(labels.length).toBeGreaterThan(20); - for (const k of labels) { - expect((builtInLocales.de as any).console.ai[k], `de is missing console.ai.${k}`).toBeTypeOf('string'); - } - }); -}); diff --git a/ui/packages/i18n/src/__tests__/perm-home-namespace-3546.test.tsx b/ui/packages/i18n/src/__tests__/perm-home-namespace-3546.test.tsx index b59d67eb6b8..b294707f4e6 100644 --- a/ui/packages/i18n/src/__tests__/perm-home-namespace-3546.test.tsx +++ b/ui/packages/i18n/src/__tests__/perm-home-namespace-3546.test.tsx @@ -210,27 +210,6 @@ describe('objectui#3546 slice six — the home namespace', () => { } }); - it('reused strings are the neighbours own translations, not second renderings', () => { - // Where this slice's `en` string already existed verbatim elsewhere, the - // existing row is reused rather than re-translated, so one English string - // never renders as two different sentences in the same language. A drift on - // either side fails here. - const REUSED: Array<[newKey: string, neighbour: string]> = [ - ['home.pendingDrafts.seedWarn', 'console.ai.seedWarn'], - ]; - for (const [newKey, neighbour] of REUSED) { - // the premise: the two really are the same English string - expect(at(builtInLocales.en, newKey), `en ${newKey} vs ${neighbour}`).toBe( - at(builtInLocales.en, neighbour), - ); - for (const lang of LANGS) { - expect(at(builtInLocales[lang], newKey), `${lang} ${newKey} diverged from ${neighbour}`).toBe( - at(builtInLocales[lang], neighbour), - ); - } - } - }); - it('the two counting home strings follow their own family on the (s) marker', () => { // `home.pendingDrafts.title` (the drafts row's count since objectui#12602, // `home.pendingDrafts.message` before it) is the same family, the same row and the diff --git a/ui/packages/i18n/src/__tests__/untranslated-identity-4376.test.ts b/ui/packages/i18n/src/__tests__/untranslated-identity-4376.test.ts index 684411081b1..fcda11f6c36 100644 --- a/ui/packages/i18n/src/__tests__/untranslated-identity-4376.test.ts +++ b/ui/packages/i18n/src/__tests__/untranslated-identity-4376.test.ts @@ -152,7 +152,6 @@ const LEGITIMATE_IDENTITIES: Record = { 'marketplace.versionBadge': 'v{{version}} — version prefix plus the hole.', 'appManagement.toast.bulkFailureEntry': '{{name}} ({{reason}}) — holes and parentheses only.', 'collaboration.userStatusTitle': '{{name}} ({{status}}) — holes and parentheses only.', - 'chatbot.build.nextStepQuote': '“{{step}}” — a hole in quote marks; ko quotes with the same curly marks as en (objectui#12724).', 'console.assignedWork.row': '{{object}} · {{field}} — two holes and a middle dot, no prose (objectstack#30205).', 'approvalsInbox.bulkFailureLine': '{{title}}: {{reason}} — holes and a colon; zh/ja set a fullwidth colon, ko/ru/ar keep `: `.', 'listConditions.chips.pattern': '{{field}}: {{value}} — holes and a colon; zh/ja set a fullwidth colon, ko/ru/ar keep `: `.', diff --git a/ui/packages/i18n/src/__tests__/zh-hant-generated.test.ts b/ui/packages/i18n/src/__tests__/zh-hant-generated.test.ts index 8f22a1718ab..0a2bc42bb7c 100644 --- a/ui/packages/i18n/src/__tests__/zh-hant-generated.test.ts +++ b/ui/packages/i18n/src/__tests__/zh-hant-generated.test.ts @@ -32,7 +32,6 @@ import { describe, expect, it } from 'vitest'; import * as converter from '../../scripts/zh-hant.mjs'; import { CONVERSION_CASES, - GATE_ONLY_KEYS, GENERATED_HEADER, NAMESPACE_GENERATED_HEADER, ZH_HANT_TARGETS, @@ -101,15 +100,6 @@ describe('every zh-Hant catalogue is generated, and current', () => { // Placeholders are not Han text, so the converter leaves them alone. expect(s2t('已选择 {{count}} 条记录')).toContain('{{count}}'); }); - - it('carries none of the gate-only outbound keys, and drops nothing else', () => { - const ai = zhHant.console.ai as Record; - for (const key of GATE_ONLY_KEYS) expect(ai[key], key).toBeUndefined(); - const hansAi = zhHans.console.ai as Record; - for (const key of GATE_ONLY_KEYS) expect(typeof hansAi[key], key).toBe('string'); - const dropped = Object.keys(hansAi).filter((key) => !(key in ai)); - expect(dropped.sort()).toEqual([...GATE_ONLY_KEYS].sort()); - }); }); describe('the converter is typed by its declaration twin', () => { diff --git a/ui/packages/i18n/src/locales/ar.ts b/ui/packages/i18n/src/locales/ar.ts index a3eea273fc0..da9e49f217c 100644 --- a/ui/packages/i18n/src/locales/ar.ts +++ b/ui/packages/i18n/src/locales/ar.ts @@ -2447,29 +2447,7 @@ const ar = { }, ai: { pendingDrafts: { - // objectstack#34610 — the line points to the shell's draft bar and shows a publish receipt. - publishFromBar: '{{count}} تغيير غير منشور. انشرها من شريط المسودة في الأعلى.', - publishFromBar_zero: '{{count}} تغيير غير منشور. انشرها من شريط المسودة في الأعلى.', - publishFromBar_one: 'تغيير واحد غير منشور ({{count}}). انشره من شريط المسودة في الأعلى.', - publishFromBar_two: 'تغييران غير منشورين ({{count}}). انشرها من شريط المسودة في الأعلى.', - publishFromBar_few: '{{count}} تغييرات غير منشورة. انشرها من شريط المسودة في الأعلى.', - publishFromBar_many: '{{count}} تغييرًا غير منشور. انشرها من شريط المسودة في الأعلى.', - publishFromBar_other: '{{count}} تغيير غير منشور. انشرها من شريط المسودة في الأعلى.', - showDraftToPublish: '{{count}} تغيير غير منشور. اعرض المسودة لمراجعتها ونشرها.', - showDraftToPublish_zero: '{{count}} تغيير غير منشور. اعرض المسودة لمراجعتها ونشرها.', - showDraftToPublish_one: 'تغيير واحد غير منشور ({{count}}). اعرض المسودة لمراجعته ونشره.', - showDraftToPublish_two: 'تغييران غير منشورين ({{count}}). اعرض المسودة لمراجعتها ونشرها.', - showDraftToPublish_few: '{{count}} تغييرات غير منشورة. اعرض المسودة لمراجعتها ونشرها.', - showDraftToPublish_many: '{{count}} تغييرًا غير منشور. اعرض المسودة لمراجعتها ونشرها.', - showDraftToPublish_other: '{{count}} تغيير غير منشور. اعرض المسودة لمراجعتها ونشرها.', - showDraft: 'عرض المسودة', - receipt: 'تم النشر. تغييراتك أصبحت مباشرة.', - dismissReceipt: 'إغلاق', count: "هناك {{count}} من التغييرات لم تُنشر بعد — لا يمكن للمستخدمين رؤيتها.", - publish: "نشر", - published: "جميع التغييرات المعلّقة فعّالة الآن.", - failed: "فشل النشر.", - publishedWithFindings: "تم النشر، لكن مجسّات وقت التشغيل أبلغت عن مشكلات: {{detail}}", }, usage: { title: "استخدام الذكاء الاصطناعي", @@ -2503,31 +2481,6 @@ const ar = { share: "مشاركة", shareTitle: "مشاركة هذه المحادثة", shareDisabledTitle: "ابدأ المحادثة لتفعيل المشاركة", - buildDoctor: "تشخيص البناء", - buildDoctorTitle: "تشخيص البناء — ما الذي طُبِّق فعلًا؟", - buildDoctorDisabledTitle: "أرسل رسالة أولًا", - buildDoctorDrawer: { - description: 'ما ادّعاه الوكيل مقابل ما هو فعّال فعلًا. تشخيص للقراءة فقط.', - reconciling: 'جارٍ المطابقة…', - notAvailable: 'غير متاح — لم يتم العثور على المحادثة أو ليست لديك صلاحية.', - untitled: '(بدون عنوان)', - summary: 'الجولات: {{turns}} · الرسائل: {{messages}} · الرموز: {{tokens}} · LLM: {{seconds}} ث', - allLive: 'جميع التغييرات التي جرت محاولتها ({{count}}) فعّالة — لم يُفقد شيء.', - discrepancies: 'عدد التناقضات: {{count}} — ما قالته المحادثة لا يطابق ما هو فعّال.', - orphanedTitle: 'مقترح ولكن لم يُطبَّق أبدًا', - orphanedHint: 'بطاقة تأكيد اقترحها الوكيل ولكن لم تطبّقها أي جولة لاحقة — فُقد التغيير بصمت.', - missingTitle: 'مُدّعى ولكنه مفقود', - missingHint: 'ذكرت نتيجة أداة أنه تم التطبيق، لكن العنصر غير فعّال في sys_metadata.', - toolErrorsTitle: 'أخطاء الأدوات', - toolErrorsHint: 'استدعاءات الأدوات التي أعادت خطأً أثناء البناء.', - verifyTitle: 'فحص البناء (verify_build)', - yourApp: 'تطبيقك:', - noIssues: 'عدد المشكلات: 0', - issueCount: 'عدد المشكلات: {{count}}', - platformNoise: 'تم إخفاء {{count}} من نتائج المنصة sys_*', - pendingActions: 'الإجراءات المعلّقة', - timeline: 'المخطط الزمني ({{count}})', - }, newChat: "جديدة", searchChats: "البحث في المحادثات…", noChatsYet: "لا توجد محادثات بعد", @@ -2549,29 +2502,15 @@ const ar = { liveCanvasLive: "تطبيق حي — {{app}}", loadingAgents: "جارٍ تحميل الوكلاء…", askAnything: "اسأل عن أي شيء…", - askOrChangeApp: "اسأل عن بياناتك، أو اطلب مني تعديل هذا التطبيق…", - describeAppToBuild: "صِف التطبيق الذي تريد إنشاءه، أو ما تريد تغييره…", emptyTitle: "ابدأ محادثة", emptyDescription: "اسأل عن أي شيء — يمكن للمساعد الاطلاع على سياق تطبيقك الحالي.", switchAssistant: "تبديل المساعد", chooseAgent: "اختر مساعدًا…", empty: { - build: { - title: "الإنشاء بالذكاء الاصطناعي", - description: "صف تطبيقًا بلغة بسيطة — سأعدّ مسودة الكائنات والشاشات والبيانات النموذجية، ثم تراجعها وتنشرها.", - }, ask: { title: "اسأل بياناتك", description: "اطرح أسئلة عن سجلاتك — أعداد وقوائم وملخصات للبيانات التي يمكنك الوصول إليها.", }, - editApp: { - title: "تحرير «{{app}}»", - titleGeneric: "تحرير هذا التطبيق", - description: "ما الذي تريد تغييره؟ سأعدّل هذا التطبيق في مكانه — إضافة حقل أو كائن أو عرض أو لوحة معلومات، أو تعديل ما هو موجود.", - // objectstack#34608 — the builder's empty state names both halves: data questions and changes. - askOrChangeDescription: - "اسأل عن بيانات هذا التطبيق — الأعداد والقوائم والملخصات — أو أخبرني بما تريد تغييره، وسأعدّل التطبيق في مكانه: حقل أو كائن أو عرض أو لوحة معلومات.", - }, }, clearConversation: "مسح", sendHint: "للإرسال", @@ -2583,9 +2522,6 @@ const ar = { toolFailed: "فشل", toolDetailsHidden: "مدخلات الأدوات والنتائج الخام مخفية في هذا العرض.", toolDenyReason: "رفضه المشغّل من المحادثة", - builderHandoffTitle: "الإنشاء في المُنشئ", - builderHandoffOpen: "فتح في المُنشئ →", - builderHandoffSuperseded: "يتوفر طلب أحدث", recordWriteCreateTitle: "{{object}} جديد", recordWriteUpdateTitle: "تغيير {{object}}", recordWriteConfirm: "تأكيد", @@ -2656,32 +2592,17 @@ const ar = { stopResponse: "إيقاف الرد", trace: "التتبّع", viewTrace: "عرض التتبّع", - nextSteps: "الخطوة التالية", - publishDrafts: "نشر", - publishOk: "تم النشر — الكائنات فعّالة الآن.", - seedWarn: "تم النشر، لكن تعذّر تحميل بعض البيانات التجريبية.", - openBuiltApp: "فتح التطبيق", - viewBuiltAppInStudio: "العرض في Studio", - previewDraft: "معاينة", previewApp: "معاينة التطبيق", resizeSplit: "تغيير حجم المحادثة والمعاينة", hideChats: "إخفاء المحادثات", showChats: "إظهار المحادثات", - planTitle: "الخطة المقترحة", - planQuestions: "التأكيد قبل الإنشاء", - planAssumptions: "الافتراضات", - planApproveHint: "أجب للموافقة على هذه الخطة أو تعديلها.", - planApprove: "ابدأ الإنشاء", - planAdjust: "تعديل", justNow: "الآن", minutesAgo: "قبل {{count}} د", hoursAgo: "قبل {{count}} س", daysAgo: "قبل {{count}} ي", agentLabels: { ask: "السؤال", - build: "الإنشاء", dataChat: "المساعد", - metadataAssistant: "مساعد البيانات الوصفية", }, suggestions: { dataChat: { @@ -2689,51 +2610,12 @@ const ar = { recentRecords: "اذكر أحدث 5 سجلات تم إنشاؤها.", recordCounts: "احسب عدد السجلات لكل كائن.", }, - // cloud#1984 — these five chips are the maker's own recommendations, so - // they may only ask for what ADR-0112 v1 BUILDS: objects, fields, views - // (grid/kanban/calendar/gallery), pages, dashboards and sample data. No - // wording that promises autonomous behaviour (alert / remind / notify / - // automate / status workflow) — v1 has no flows, actions or schedules, and - // the model silently degrades such a request into a board or a filtered - // view, so the chip would promise an alert and deliver a page. REVERT to - // the automation wording when ADR-0112 v2 re-adds flows and actions. - metadataAssistant: { - buildCrm: "أنشئ نظام إدارة علاقات عملاء للمبيعات — عملاء وجهات اتصال وصفقات بحقل للمرحلة، ولوحة معلومات تجمع قيمة الصفقات حسب المرحلة.", - buildApp: "أنشئ متتبّع مشاريع — مشاريع ومهام بمسؤولين وتواريخ استحقاق، ولوحة حسب الحالة، وتقويم لتواريخ الاستحقاق.", - buildFlow: "صمّم مكتب دعم — تذاكر بحقلي الأولوية والحالة، ولوحة حسب الحالة، وروابط بالعملاء.", - buildInventory: "أنشئ تطبيق مخزون — منتجات ومستويات مخزون وموردين، وعرض يصفّي الأصناف دون حد إعادة الطلب.", - buildRecruiting: "أنشئ متتبّع متقدمين — مرشحون ووظائف شاغرة وحقل لمرحلة المقابلة، ولوحة حسب المرحلة.", - }, generic: { help: "بماذا يمكنك مساعدتي؟", availableObjects: "اذكر كائنات البيانات المتاحة.", recentActivity: "لخّص نشاطي الأخير.", }, - // objectui#7709 — the edit-mode starters, shown when the maker is bound - // to an EXISTING app (`?package=`). Same rule as the five above: they - // may only ask for what ADR-0112 v1 BUILDS. The fourth chip used to be - // `addAutomation` ("an approval, a status flow, or a notification") and - // every capability it named is refused by v1 (cloud#1956 / PR #1970), so - // it now asks for sample data — `seed` IS on v1's whitelist, and having - // no data is what an existing app most often lacks. REVERT: when - // ADR-0112 v2 re-adds flows and actions, THIS chip's automation wording - // comes back as `addAutomation`; the retired string is pinned for every - // pack in `packages/i18n/src/__tests__/makerEditChips-v1-scope-7709.test.ts`. - editApp: { - addField: "أضف حقلًا إلى أحد الكائنات.", - addObject: "أضف كائنًا جديدًا واربطه بكائن موجود.", - addDashboard: "أضف لوحة معلومات للمؤشرات الرئيسية.", - addSampleData: "املأ الكائنات الحالية ببيانات نموذجية واقعية تصلح للعرض التوضيحي.", - }, }, - changesTitle: "تأكيد التغييرات", - changesConfirmed: "تم التأكيد", - changesConfirm: "تأكيد", - changesConfirmHint: "أجب لتأكيد هذا التغيير أو تعديله.", - changesApplying: "جارٍ التطبيق…", - changesApplied: "تم التطبيق", - changesDrafted: "حُفظ كمسودة", - changesFailed: "لم يُطبَّق", discussing: "قيد العرض: {{target}}", focus: { pin: "مواصلة السؤال عن هذا السجل", @@ -2743,47 +2625,15 @@ const ar = { switchAccept: "تبديل", switchDecline: "إبقاء", }, - changeVerb: { - createObject: "إنشاء كائن", - addField: "إضافة حقل", - modifyField: "تعديل حقل", - deleteField: "حذف حقل", - createMetadata: "إنشاء", - updateMetadata: "تعديل", - createSeed: "إنشاء بيانات تجريبية", - createPackage: "إنشاء حزمة تطبيق", - }, // objectui#3546 slice four — the AI console surfaces: the /ai chat page's app switcher, // connection banner and plan/publish cards, the ChatDock chrome, and the // conversation-list date buckets. `group.*` is the template-key family // `console.ai.group.${key}` (ConversationsSidebar), enumerated from the // ConversationGroupKey union — all five members, no wildcard. collapseToDock: "طيّ إلى اللوحة الجانبية", - switchApp: "تبديل التطبيق", - switchAppLabel: "محادثات الإنشاء حسب التطبيق", - newApp: "تطبيق جديد", connectionWaiting: "في انتظار الخادم…", connectionStalled: "لا يزال العمل جاريًا…", connectionOffline: "انقطع الاتصال — جارٍ إعادة الاتصال…", - designingPlan: "جارٍ تصميم تطبيقك…", - designingPlanHint: { - data: "جارٍ تحديد البيانات التي ستتابعها…", - objects: "جارٍ تشكيل الكائنات وحقولها…", - relations: "جارٍ ربط السجلات ذات الصلة…", - lookups: "جارٍ إعداد العلاقات وحقول البحث…", - views: "جارٍ التخطيط للشاشات والعروض…", - forms: "جارٍ تنسيق النماذج والقوائم…", - defaults: "جارٍ إضافة قيم افتراضية ومعايير تحقّق منطقية…", - dashboard: "جارٍ رسم لوحة معلومات للمتابعة…", - review: "جارٍ التحقّق من تماسك البنية…", - finalize: "جارٍ تجميع الخطة…", - }, - planBuilding: "جارٍ الإنشاء…", - planBuilt: "تم الإنشاء", - planDeferred: "لم يُنشأ بعد", - planReady: "الخطة جاهزة. ابدأ الإنشاء الآن، أو أخبرني بما تريد تعديله.", - published: "تم النشر", - publishFailed: "فشل النشر", unavailableTitle: "مساعد الذكاء الاصطناعي غير متاح", unavailableDescription: "لم يتم تمكين مساعد الذكاء الاصطناعي في هذا النشر. وكل شيء آخر يعمل كالمعتاد.", unavailableError: "تعذّر الوصول إلى خدمة الذكاء الاصطناعي. قد تكون غير متصلة مؤقتًا — أعد المحاولة أو عد إلى الرئيسية.", @@ -4894,22 +4744,6 @@ const ar = { derivedAiAccess: 'الوصول إلى الذكاء الاصطناعي مُفعَّل', }, }, - excelImport: { - noImportableFields: "لا تحتوي هذه الكائن على حقول قابلة للاستيراد.", - schemaReadFailed: "تعذّرت قراءة مخطط الكائن.", - imported: "تم استيراد {{count}} صف إلى {{object}}.", - imported_zero: "تم استيراد {{count}} صف إلى {{object}}.", - imported_one: "تم استيراد {{count}} صف إلى {{object}}.", - imported_two: "تم استيراد صفين ({{count}}) إلى {{object}}.", - imported_few: "تم استيراد {{count}} صفوف إلى {{object}}.", - imported_many: "تم استيراد {{count}} صفًا إلى {{object}}.", - imported_other: "تم استيراد {{count}} صف إلى {{object}}.", - importFrom: "استيراد الصفوف الفعلية من", - into: "إلى", - opening: "جارٍ الفتح…", - importAction: "استيراد", - dismiss: "تجاهل", - }, cloudWorkspaceTimezoneNotice: { seeded: "تم تعيين المنطقة الزمنية للبيئة إلى {{zone}} وفقًا لمتصفحك عند إنشائها. يمكنك تغييرها من الإعدادات → التوطين.", }, @@ -5134,8 +4968,6 @@ const ar = { failed: "فشل", }, phase: { - build: "الإنشاء", - design: "تصميم الخطة", stepCount: "{{count}} خطوات", stepCount_zero: "{{count}} خطوة", stepCount_one: "{{count}} خطوة", @@ -5146,158 +4978,11 @@ const ar = { expand: "إظهار الخطوات", collapse: "إخفاء الخطوات", }, - plan: { - countObjects: "{{count}} كائنات", - countObjects_zero: "{{count}} كائن", - countObjects_one: "{{count}} كائن", - countObjects_two: "كائنان ({{count}})", - countObjects_few: "{{count}} كائنات", - countObjects_many: "{{count}} كائنًا", - countObjects_other: "{{count}} كائن", - countViews: "{{count}} طرق عرض", - countViews_zero: "{{count}} طريقة عرض", - countViews_one: "{{count}} طريقة عرض", - countViews_two: "طريقتا عرض ({{count}})", - countViews_few: "{{count}} طرق عرض", - countViews_many: "{{count}} طريقة عرض", - countViews_other: "{{count}} طريقة عرض", - countDashboards: "{{count}} لوحات معلومات", - countDashboards_zero: "{{count}} لوحة معلومات", - countDashboards_one: "{{count}} لوحة معلومات", - countDashboards_two: "لوحتا معلومات ({{count}})", - countDashboards_few: "{{count}} لوحات معلومات", - countDashboards_many: "{{count}} لوحة معلومات", - countDashboards_other: "{{count}} لوحة معلومات", - countSeedData: "بيانات تجريبية", - extendTarget: "إضافة إلى التطبيق الحالي: {{app}}", - awaitingConfirm: "بانتظار التأكيد", - // objectstack#32984 — the plan card's build states. - confirmed: "تم التأكيد", - buildFailed: "لم يتم البناء — لم يُنشأ أي شيء", - iterateOrNew: { - question: "يتداخل هذا مع «{{app}}»، وهو تطبيق لديك بالفعل. هل تريد مواصلة تحسينه أم إنشاء تطبيق منفصل؟", - questionUnnamed: "يتداخل هذا مع تطبيق لديك بالفعل. هل تريد مواصلة تحسين ذلك التطبيق أم إنشاء تطبيق منفصل؟", - extend: "مواصلة تحسين «{{app}}»", - buildNew: "إنشاء تطبيق منفصل", - replyHint: "أجب لتحديد اختيارك.", - }, - objectsAndFields: "الكائنات والحقول", - views: "طرق العرض", - suggestedField: "مقترح", - suggestedFieldLegend: "الحقول المُعلَّمة بـ «{{mark}}» أضافها الذكاء الاصطناعي؛ لم تطلبها.", - nameField: "الاسم: {{field}}", - }, build: { - building: "جارٍ إنشاء {{app}}…", - built: "تم إنشاء {{app}}", - builtAndLive: "تم الإنشاء والنشر · {{app}}", - appFallback: "تطبيقك", - addingSampleData: "جارٍ إضافة بيانات تجريبية", - group: { - object: "الكائنات", - view: "طرق العرض", - dashboard: "لوحات المعلومات", - app: "التطبيق", - seed: "بيانات تجريبية", - dataset: "مجموعات البيانات", - permission: "الأذونات", - other: "أخرى", - }, - moreArtifacts: "+{{n}} أخرى", - verifying: "جارٍ التحقق من التغيير…", - verifyStep: "الخطوة {{n}}", - verified: "تم التحقق من التغيير", - // objectstack#32984 — the build card's issues line, in the customer's words. - issuesCount: "يلزم إصلاح: {{count}}", issuesSummary: "تحتاج بعض أجزاء هذا البناء إلى إصلاح قبل أن يصبح جاهزًا. أجب بـ «أصلح المشكلات» وسيقوم المساعد بإصلاحها.", - warningsSummary: "تم بناء التطبيق، مع بعض النقاط التي تستحق المراجعة. اسأل المساعد عنها إذا أردت تحسينه.", - issuesDetails: "تفاصيل تقنية", - // objectstack#32984 — the published draft badge's failed-item count, which was English in every locale. - needsAttention: "بحاجة إلى مراجعة: {{count}}", - needsAttention_zero: "بحاجة إلى مراجعة: {{count}}", - needsAttention_one: "بحاجة إلى مراجعة: {{count}}", - needsAttention_two: "بحاجة إلى مراجعة: {{count}}", - needsAttention_few: "بحاجة إلى مراجعة: {{count}}", - needsAttention_many: "بحاجة إلى مراجعة: {{count}}", - needsAttention_other: "بحاجة إلى مراجعة: {{count}}", health: { - sampleRowsLive: "صفوف بيانات نموذجية منشورة: {{count}}", - sampleRowsLive_zero: "صفوف بيانات نموذجية منشورة: {{count}}", - sampleRowsLive_one: "صفوف بيانات نموذجية منشورة: {{count}}", - sampleRowsLive_two: "صفوف بيانات نموذجية منشورة: {{count}}", - sampleRowsLive_few: "صفوف بيانات نموذجية منشورة: {{count}}", - sampleRowsLive_many: "صفوف بيانات نموذجية منشورة: {{count}}", - sampleRowsLive_other: "صفوف بيانات نموذجية منشورة: {{count}}", - views: "طرق عرض: {{count}}", - views_zero: "طرق عرض: {{count}}", - views_one: "طرق عرض: {{count}}", - views_two: "طرق عرض: {{count}}", - views_few: "طرق عرض: {{count}}", - views_many: "طرق عرض: {{count}}", - views_other: "طرق عرض: {{count}}", - widgets: "عناصر لوحة المعلومات: {{count}}", - widgets_zero: "عناصر لوحة المعلومات: {{count}}", - widgets_one: "عناصر لوحة المعلومات: {{count}}", - widgets_two: "عناصر لوحة المعلومات: {{count}}", - widgets_few: "عناصر لوحة المعلومات: {{count}}", - widgets_many: "عناصر لوحة المعلومات: {{count}}", - widgets_other: "عناصر لوحة المعلومات: {{count}}", - seeds: "مجموعات بيانات نموذجية: {{count}}", - seeds_zero: "مجموعات بيانات نموذجية: {{count}}", - seeds_one: "مجموعات بيانات نموذجية: {{count}}", - seeds_two: "مجموعات بيانات نموذجية: {{count}}", - seeds_few: "مجموعات بيانات نموذجية: {{count}}", - seeds_many: "مجموعات بيانات نموذجية: {{count}}", - seeds_other: "مجموعات بيانات نموذجية: {{count}}", - verified: "تم التحقق: {{checks}}", seedFailed: "تعذّر تحميل البيانات النموذجية.", }, - unknownPhase: "مرحلة إنشاء غير معروفة", - nextStepsLead: "بعد ذلك يمكنك أن تقول: {{steps}}", - nextStepQuote: "«{{step}}»", - draftPosture: "تُحفظ التغييرات اللاحقة كمسودات، وتنشرها بزر «نشر» هنا في المحادثة.", - checksPassed: "اجتازت الفحوصات {{passed}}/{{total}}", - }, - changes: { - planTitle: "خطة التغييرات · {{count}} تغييرات", - planTitle_zero: "خطة التغييرات · {{count}} تغيير", - planTitle_one: "خطة التغييرات · {{count}} تغيير", - planTitle_two: "خطة التغييرات · تغييران ({{count}})", - planTitle_few: "خطة التغييرات · {{count}} تغييرات", - planTitle_many: "خطة التغييرات · {{count}} تغييرًا", - planTitle_other: "خطة التغييرات · {{count}} تغيير", - saveDraft: "حفظ كمسودة", - reviewAndPublish: "مراجعة التغييرات ونشرها", - undo: "تراجع", - undoWithOthers: "تراجع (مع {{count}} مسودات أخرى)", - undoWithOthers_zero: "تراجع (مع {{count}} مسودة أخرى)", - undoWithOthers_one: "تراجع (مع {{count}} مسودة أخرى)", - undoWithOthers_two: "تراجع (مع مسودتين أخريين: {{count}})", - undoWithOthers_few: "تراجع (مع {{count}} مسودات أخرى)", - undoWithOthers_many: "تراجع (مع {{count}} مسودة أخرى)", - undoWithOthers_other: "تراجع (مع {{count}} مسودة أخرى)", - undoConfirm: "يؤدي التراجع إلى حذف جميع المسودات غير المنشورة في هذه الحزمة وعددها {{total}}، منها {{count}} لا تخص هذا التغيير.", - undoConfirm_zero: "يؤدي التراجع إلى حذف جميع المسودات غير المنشورة في هذه الحزمة وعددها {{total}}، منها {{count}} لا تخص هذا التغيير.", - undoConfirm_one: "يؤدي التراجع إلى حذف جميع المسودات غير المنشورة في هذه الحزمة وعددها {{total}}، منها {{count}} لا تخص هذا التغيير.", - undoConfirm_two: "يؤدي التراجع إلى حذف جميع المسودات غير المنشورة في هذه الحزمة وعددها {{total}}، منها {{count}} لا تخص هذا التغيير.", - undoConfirm_few: "يؤدي التراجع إلى حذف جميع المسودات غير المنشورة في هذه الحزمة وعددها {{total}}، منها {{count}} لا تخص هذا التغيير.", - undoConfirm_many: "يؤدي التراجع إلى حذف جميع المسودات غير المنشورة في هذه الحزمة وعددها {{total}}، منها {{count}} لا تخص هذا التغيير.", - undoConfirm_other: "يؤدي التراجع إلى حذف جميع المسودات غير المنشورة في هذه الحزمة وعددها {{total}}، منها {{count}} لا تخص هذا التغيير.", - undoConfirmUnknown: "يؤدي التراجع إلى حذف جميع المسودات غير المنشورة في هذه الحزمة، وليس هذا التغيير فقط.", - undoConfirmAction: "تراجع عن الكل", - undoCancel: "إلغاء", - undoing: "جارٍ التراجع…", - undone: "تم التراجع", - undoFailed: "تعذّر التراجع", - kind: { - field: "حقل", - object: "كائن", - view: "طريقة عرض", - dashboard: "لوحة معلومات", - app: "تطبيق", - seed: "بيانات تجريبية", - package: "حزمة التطبيق", - }, }, }, chatbotError: { diff --git a/ui/packages/i18n/src/locales/de.ts b/ui/packages/i18n/src/locales/de.ts index 85cb01f6d6d..bade61dc054 100644 --- a/ui/packages/i18n/src/locales/de.ts +++ b/ui/packages/i18n/src/locales/de.ts @@ -2207,21 +2207,7 @@ const de = { }, ai: { pendingDrafts: { - // objectstack#34610 — the line points to the shell's draft bar and shows a publish receipt. - publishFromBar: '{{count}} unveröffentlichte Änderungen. Veröffentlichen Sie sie über die Entwurfsleiste oben.', - publishFromBar_one: '{{count}} unveröffentlichte Änderung. Veröffentlichen Sie sie über die Entwurfsleiste oben.', - publishFromBar_other: '{{count}} unveröffentlichte Änderungen. Veröffentlichen Sie sie über die Entwurfsleiste oben.', - showDraftToPublish: '{{count}} unveröffentlichte Änderungen. Zeigen Sie den Entwurf an, um sie zu prüfen und zu veröffentlichen.', - showDraftToPublish_one: '{{count}} unveröffentlichte Änderung. Zeigen Sie den Entwurf an, um sie zu prüfen und zu veröffentlichen.', - showDraftToPublish_other: '{{count}} unveröffentlichte Änderungen. Zeigen Sie den Entwurf an, um sie zu prüfen und zu veröffentlichen.', - showDraft: 'Entwurf anzeigen', - receipt: 'Veröffentlicht. Ihre Änderungen sind live.', - dismissReceipt: 'Schließen', count: "{{count}} Änderung(en) sind noch nicht veröffentlicht — Benutzer können sie nicht sehen.", - publish: "Veröffentlichen", - published: "Alle ausstehenden Änderungen sind live.", - failed: "Veröffentlichen fehlgeschlagen.", - publishedWithFindings: "Veröffentlicht, aber die Laufzeitprüfungen haben Probleme gemeldet: {{detail}}", }, usage: { title: "KI-Nutzung", @@ -2247,31 +2233,6 @@ const de = { share: "Teilen", shareTitle: "Diese Unterhaltung teilen", shareDisabledTitle: "Beginnen Sie zu chatten, um das Teilen zu aktivieren", - buildDoctor: "Build-Diagnose", - buildDoctorTitle: "Build-Diagnose — was ist tatsächlich angekommen?", - buildDoctorDisabledTitle: "Senden Sie zuerst eine Nachricht", - buildDoctorDrawer: { - description: 'Was der Agent behauptet hat und was tatsächlich live ist. Schreibgeschützte Diagnose.', - reconciling: 'Wird abgeglichen…', - notAvailable: 'Nicht verfügbar — die Unterhaltung wurde nicht gefunden oder Sie sind nicht berechtigt.', - untitled: '(ohne Titel)', - summary: '{{turns}} Runde(n) · {{messages}} Nachr. · {{tokens}} Tok. · {{seconds}} s LLM', - allLive: 'Alle {{count}} versuchten Änderung(en) sind live — nichts ist verloren gegangen.', - discrepancies: '{{count}} Abweichung(en) — was der Chat gesagt hat, stimmt nicht mit dem überein, was live ist.', - orphanedTitle: 'Vorgeschlagen, aber nie angewendet', - orphanedHint: 'Eine Bestätigungskarte, die der Agent vorgeschlagen hat, die aber keine spätere Runde angewendet hat — die Änderung ist stillschweigend verloren gegangen.', - missingTitle: 'Behauptet, aber fehlend', - missingHint: 'Ein Tool-Ergebnis meldete die Änderung als angewendet, aber das Artefakt ist in sys_metadata nicht live.', - toolErrorsTitle: 'Tool-Fehler', - toolErrorsHint: 'Tool-Aufrufe, die während des Builds einen Fehler zurückgegeben haben.', - verifyTitle: 'Build-Prüfung (verify_build)', - yourApp: 'Ihre App:', - noIssues: '0 Probleme', - issueCount: '{{count}} Problem(e)', - platformNoise: '{{count}} Plattform-sys_*-Befund(e) ausgeblendet', - pendingActions: 'Ausstehende Aktionen', - timeline: 'Zeitleiste ({{count}})', - }, newChat: "Neu", searchChats: "Chats durchsuchen…", noChatsYet: "Noch keine Chats", @@ -2293,29 +2254,15 @@ const de = { liveCanvasLive: "Live-App — {{app}}", loadingAgents: "Agenten werden geladen…", askAnything: "Fragen Sie irgendetwas…", - askOrChangeApp: "Fragen Sie zu Ihren Daten oder lassen Sie mich diese App ändern…", - describeAppToBuild: "Beschreiben Sie die App, die Sie erstellen möchten, oder was geändert werden soll…", emptyTitle: "Unterhaltung beginnen", emptyDescription: "Fragen Sie irgendetwas — der Assistent hat Zugriff auf den Kontext Ihrer aktuellen App.", switchAssistant: "Assistenten wechseln", chooseAgent: "Assistenten wählen…", empty: { - build: { - title: "Mit KI erstellen", - description: "Beschreiben Sie eine App in einfachen Worten — ich entwerfe die Objekte, Bildschirme und Beispieldaten, dann prüfen und veröffentlichen Sie.", - }, ask: { title: "Ihre Daten fragen", description: "Stellen Sie Fragen zu Ihren Datensätzen — Anzahlen, Listen und Zusammenfassungen über die Daten, auf die Sie zugreifen können.", }, - editApp: { - title: "„{{app}}“ wird bearbeitet", - titleGeneric: "Diese App bearbeiten", - description: "Was möchten Sie ändern? Ich passe diese App direkt an — ein Feld, Objekt, eine Ansicht oder ein Dashboard hinzufügen oder Vorhandenes anpassen.", - // objectstack#34608 — the builder's empty state names both halves: data questions and changes. - askOrChangeDescription: - "Fragen Sie nach den Daten dieser App – Anzahlen, Listen und Zusammenfassungen – oder sagen Sie mir, was ich ändern soll, und ich passe die App direkt an: ein Feld, ein Objekt, eine Ansicht oder ein Dashboard.", - }, }, clearConversation: "Leeren", sendHint: "zum Senden", @@ -2327,9 +2274,6 @@ const de = { toolFailed: "Fehlgeschlagen", toolDetailsHidden: "Tool-Eingaben und Rohergebnisse sind in dieser Ansicht ausgeblendet.", toolDenyReason: "Im Chat vom Bediener abgelehnt", - builderHandoffTitle: "Im Builder erstellen", - builderHandoffOpen: "Im Builder öffnen →", - builderHandoffSuperseded: "Eine neuere Anfrage liegt vor", recordWriteCreateTitle: "Neu: {{object}}", recordWriteUpdateTitle: "{{object}} ändern", recordWriteConfirm: "Bestätigen", @@ -2376,32 +2320,17 @@ const de = { stopResponse: "Antwort stoppen", trace: "Trace", viewTrace: "Trace anzeigen", - nextSteps: "Wie geht es weiter", - publishDrafts: "Veröffentlichen", - publishOk: "Veröffentlicht — die Objekte sind jetzt live.", - seedWarn: "Veröffentlicht, aber einige Beispieldaten konnten nicht geladen werden.", - openBuiltApp: "App öffnen", - viewBuiltAppInStudio: "In Studio ansehen", - previewDraft: "Vorschau", previewApp: "App-Vorschau", resizeSplit: "Chat und Vorschau anpassen", hideChats: "Chats ausblenden", showChats: "Chats anzeigen", - planTitle: "Vorgeschlagener Plan", - planQuestions: "Vor dem Erstellen bestätigen", - planAssumptions: "Annahmen", - planApproveHint: "Antworten Sie, um diesen Plan zu genehmigen oder anzupassen.", - planApprove: "Erstellen", - planAdjust: "Anpassen", justNow: "gerade eben", minutesAgo: "vor {{count}} Min.", hoursAgo: "vor {{count}} Std.", daysAgo: "vor {{count}} T.", agentLabels: { ask: "Fragen", - build: "Erstellen", dataChat: "Assistent", - metadataAssistant: "Metadaten-Assistent", }, suggestions: { dataChat: { @@ -2409,51 +2338,12 @@ const de = { recentRecords: "Liste die 5 zuletzt erstellten Datensätze auf.", recordCounts: "Zähle die Datensätze je Objekt.", }, - // cloud#1984 — these five chips are the maker's own recommendations, so - // they may only ask for what ADR-0112 v1 BUILDS: objects, fields, views - // (grid/kanban/calendar/gallery), pages, dashboards and sample data. No - // wording that promises autonomous behaviour (alert / remind / notify / - // automate / status workflow) — v1 has no flows, actions or schedules, and - // the model silently degrades such a request into a board or a filtered - // view, so the chip would promise an alert and deliver a page. REVERT to - // the automation wording when ADR-0112 v2 re-adds flows and actions. - metadataAssistant: { - buildCrm: "Erstelle ein Vertriebs-CRM — Kunden, Kontakte und Deals mit einem Phasenfeld sowie ein Dashboard, das den Deal-Wert je Phase summiert.", - buildApp: "Erstelle einen Projekt-Tracker — Projekte, Aufgaben mit Verantwortlichen und Fälligkeitsdaten, ein Board nach Status und einen Kalender der Fälligkeiten.", - buildFlow: "Entwirf einen Support-Desk — Tickets mit Prioritäts- und Statusfeld, ein Board nach Status und Verknüpfungen zu Kunden.", - buildInventory: "Erstelle eine Bestands-App — Produkte, Lagerbestände, Lieferanten und eine Ansicht, die Artikel unter ihrem Meldebestand filtert.", - buildRecruiting: "Erstelle einen Bewerber-Tracker — Kandidaten, offene Stellen, ein Feld für die Interviewphase und ein Board nach Phase.", - }, generic: { help: "Wobei kannst du mir helfen?", availableObjects: "Liste die verfügbaren Datenobjekte auf.", recentActivity: "Fasse meine letzten Aktivitäten zusammen.", }, - // objectui#7709 — the edit-mode starters, shown when the maker is bound - // to an EXISTING app (`?package=`). Same rule as the five above: they - // may only ask for what ADR-0112 v1 BUILDS. The fourth chip used to be - // `addAutomation` ("an approval, a status flow, or a notification") and - // every capability it named is refused by v1 (cloud#1956 / PR #1970), so - // it now asks for sample data — `seed` IS on v1's whitelist, and having - // no data is what an existing app most often lacks. REVERT: when - // ADR-0112 v2 re-adds flows and actions, THIS chip's automation wording - // comes back as `addAutomation`; the retired string is pinned for every - // pack in `packages/i18n/src/__tests__/makerEditChips-v1-scope-7709.test.ts`. - editApp: { - addField: "Füge einem der Objekte ein Feld hinzu.", - addObject: "Füge ein neues Objekt hinzu und verknüpfe es mit einem bestehenden.", - addDashboard: "Füge ein Dashboard für die wichtigsten Kennzahlen hinzu.", - addSampleData: "Fülle die vorhandenen Objekte mit realistischen Beispieldatensätzen, damit ich die App vorführen kann.", - }, }, - changesTitle: "Änderungen bestätigen", - changesConfirmed: "Bestätigt", - changesConfirm: "Bestätigen", - changesConfirmHint: "Antworten Sie, um diese Änderung zu bestätigen oder anzupassen.", - changesApplying: "Wird angewendet…", - changesApplied: "Angewendet", - changesDrafted: "Als Entwurf gespeichert", - changesFailed: "Nicht angewendet", discussing: "Angezeigt: {{target}}", focus: { pin: "Weiter zu diesem Datensatz fragen", @@ -2463,47 +2353,15 @@ const de = { switchAccept: "Wechseln", switchDecline: "Beibehalten", }, - changeVerb: { - createObject: "Objekt erstellen", - addField: "Feld hinzufügen", - modifyField: "Feld ändern", - deleteField: "Feld löschen", - createMetadata: "Erstellen", - updateMetadata: "Ändern", - createSeed: "Beispieldaten erzeugen", - createPackage: "App-Paket erstellen", - }, // objectui#3546 slice four — the AI console surfaces: the /ai chat page's app switcher, // connection banner and plan/publish cards, the ChatDock chrome, and the // conversation-list date buckets. `group.*` is the template-key family // `console.ai.group.${key}` (ConversationsSidebar), enumerated from the // ConversationGroupKey union — all five members, no wildcard. collapseToDock: "In die Seitenleiste einklappen", - switchApp: "App wechseln", - switchAppLabel: "Build-Unterhaltungen nach App", - newApp: "Neue App", connectionWaiting: "Warten auf den Server…", connectionStalled: "Arbeitet noch…", connectionOffline: "Verbindung verloren — Neuverbindung…", - designingPlan: "Ihre App wird entworfen…", - designingPlanHint: { - data: "Die Daten, die Sie erfassen möchten, werden strukturiert…", - objects: "Objekte und ihre Felder werden geformt…", - relations: "Verknüpfte Datensätze werden verbunden…", - lookups: "Beziehungen und Lookups werden eingerichtet…", - views: "Bildschirme und Ansichten werden geplant…", - forms: "Formulare und Listen werden angeordnet…", - defaults: "Sinnvolle Standardwerte und Validierungen werden hinzugefügt…", - dashboard: "Ein Dashboard zur Nachverfolgung wird skizziert…", - review: "Es wird noch einmal geprüft, ob die Struktur zusammenpasst…", - finalize: "Der Plan wird zusammengestellt…", - }, - planBuilding: "Wird erstellt…", - planBuilt: "Erstellt", - planDeferred: "Noch nicht erstellt", - planReady: "Der Plan ist fertig. Erstellen Sie ihn jetzt, oder sagen Sie mir, was angepasst werden soll.", - published: "Veröffentlicht", - publishFailed: "Veröffentlichen fehlgeschlagen", unavailableTitle: "KI-Assistent nicht verfügbar", unavailableDescription: "In dieser Bereitstellung ist kein KI-Assistent aktiviert. Alles andere funktioniert wie gewohnt.", unavailableError: "Der KI-Dienst war nicht erreichbar. Er ist möglicherweise vorübergehend offline — versuchen Sie es erneut, oder kehren Sie zur Startseite zurück.", @@ -4512,18 +4370,6 @@ const de = { derivedAiAccess: 'KI-Zugriff aktiviert', }, }, - excelImport: { - noImportableFields: "Dieses Objekt hat keine importierbaren Felder.", - schemaReadFailed: "Das Objektschema konnte nicht gelesen werden.", - imported: "{{count}} Zeile(n) in {{object}} importiert.", - imported_one: "{{count}} Zeile in {{object}} importiert.", - imported_other: "{{count}} Zeilen in {{object}} importiert.", - importFrom: "Echte Zeilen importieren aus", - into: "nach", - opening: "Wird geöffnet…", - importAction: "Importieren", - dismiss: "Verwerfen", - }, cloudWorkspaceTimezoneNotice: { seeded: "Die Zeitzone der Umgebung wurde beim Erstellen anhand Ihres Browsers auf {{zone}} festgelegt. Sie können sie unter Einstellungen → Lokalisierung ändern.", }, @@ -4748,122 +4594,17 @@ const de = { failed: "Fehlgeschlagen", }, phase: { - build: "Erstellen", - design: "Plan entwerfen", stepCount: "{{count}} Schritte", stepCount_one: "{{count}} Schritt", stepCount_other: "{{count}} Schritte", expand: "Schritte anzeigen", collapse: "Schritte ausblenden", }, - plan: { - countObjects: "{{count}} Objekte", - countObjects_one: "{{count}} Objekt", - countObjects_other: "{{count}} Objekte", - countViews: "{{count}} Ansichten", - countViews_one: "{{count}} Ansicht", - countViews_other: "{{count}} Ansichten", - countDashboards: "{{count}} Dashboards", - countDashboards_one: "{{count}} Dashboard", - countDashboards_other: "{{count}} Dashboards", - countSeedData: "Beispieldaten", - extendTarget: "Wird zur bestehenden App hinzugefügt: {{app}}", - awaitingConfirm: "Wartet auf Bestätigung", - // objectstack#32984 — the plan card's build states. - confirmed: "Bestätigt", - buildFailed: "Nicht erstellt — es wurde nichts angelegt", - iterateOrNew: { - question: "Das überschneidet sich mit „{{app}}“, einer App, die Sie bereits haben. Diese App weiter verbessern oder eine separate App erstellen?", - questionUnnamed: "Das überschneidet sich mit einer App, die Sie bereits haben. Diese App weiter verbessern oder eine separate App erstellen?", - extend: "„{{app}}“ weiter verbessern", - buildNew: "Separate App erstellen", - replyHint: "Antworten Sie, welche Option Sie wählen.", - }, - objectsAndFields: "Objekte und Felder", - views: "Ansichten", - suggestedField: "ergänzt", - suggestedFieldLegend: "Mit „{{mark}}“ markierte Felder hat die KI hinzugefügt; Sie haben sie nicht angefordert.", - nameField: "Bezeichnung: {{field}}", - }, build: { - building: "{{app}} wird erstellt…", - built: "{{app}} wurde erstellt", - builtAndLive: "Erstellt und live · {{app}}", - appFallback: "Ihre App", - addingSampleData: "Beispieldaten werden hinzugefügt", - group: { - object: "Objekte", - view: "Ansichten", - dashboard: "Dashboards", - app: "App", - seed: "Beispieldaten", - dataset: "Datensätze", - permission: "Berechtigungen", - other: "Sonstiges", - }, - moreArtifacts: "+{{n}} weitere", - verifying: "Änderung wird geprüft…", - verifyStep: "Schritt {{n}}", - verified: "Änderung geprüft", - // objectstack#32984 — the build card's issues line, in the customer's words. - issuesCount: "{{count}} zu beheben", issuesSummary: "Einige Teile dieses Builds müssen noch korrigiert werden. Bitte den Assistenten, die Probleme zu beheben, dann repariert er sie.", - warningsSummary: "Der Build ist fertig, einige Punkte sind aber prüfenswert. Frag den Assistenten, welche das sind, wenn du sie verbessern möchtest.", - issuesDetails: "Technische Details", - // objectstack#32984 — the published draft badge's failed-item count, which was English in every locale. - needsAttention: "{{count}} erfordern Prüfung", - needsAttention_one: "{{count}} erfordert Prüfung", - needsAttention_other: "{{count}} erfordern Prüfung", health: { - sampleRowsLive: "{{count}} Beispieldatensätze live", - sampleRowsLive_one: "{{count}} Beispieldatensatz live", - sampleRowsLive_other: "{{count}} Beispieldatensätze live", - views: "{{count}} Ansichten", - views_one: "{{count}} Ansicht", - views_other: "{{count}} Ansichten", - widgets: "{{count}} Widgets", - widgets_one: "{{count}} Widget", - widgets_other: "{{count}} Widgets", - seeds: "{{count}} Beispieldatenpakete", - seeds_one: "{{count}} Beispieldatenpaket", - seeds_other: "{{count}} Beispieldatenpakete", - verified: "{{checks}} geprüft", seedFailed: "Die Beispieldaten konnten nicht geladen werden.", }, - unknownPhase: "Unbekannte Build-Phase", - nextStepsLead: "Als Nächstes können Sie sagen: {{steps}}", - nextStepQuote: "„{{step}}“", - draftPosture: "Spätere Änderungen werden als Entwurf gespeichert; mit „Veröffentlichen“ hier im Chat gehen sie live.", - checksPassed: "Prüfungen bestanden {{passed}}/{{total}}", - }, - changes: { - planTitle: "Änderungsplan · {{count}} Änderungen", - planTitle_one: "Änderungsplan · {{count}} Änderung", - planTitle_other: "Änderungsplan · {{count}} Änderungen", - saveDraft: "Als Entwurf speichern", - reviewAndPublish: "Änderungen prüfen und veröffentlichen", - undo: "Rückgängig", - undoWithOthers: "Rückgängig (mit {{count}} weiteren Entwürfen)", - undoWithOthers_one: "Rückgängig (mit {{count}} weiteren Entwurf)", - undoWithOthers_other: "Rückgängig (mit {{count}} weiteren Entwürfen)", - undoConfirm: "Rückgängig verwirft alle {{total}} unveröffentlichten Entwürfe dieses Pakets, davon {{count}}, die nicht zu dieser Änderung gehören.", - undoConfirm_one: "Rückgängig verwirft alle {{total}} unveröffentlichten Entwürfe dieses Pakets, davon {{count}}, der nicht zu dieser Änderung gehört.", - undoConfirm_other: "Rückgängig verwirft alle {{total}} unveröffentlichten Entwürfe dieses Pakets, davon {{count}}, die nicht zu dieser Änderung gehören.", - undoConfirmUnknown: "Rückgängig verwirft alle unveröffentlichten Entwürfe dieses Pakets, nicht nur diese Änderung.", - undoConfirmAction: "Alle verwerfen", - undoCancel: "Abbrechen", - undoing: "Wird rückgängig gemacht…", - undone: "Rückgängig gemacht", - undoFailed: "Rückgängig machen fehlgeschlagen", - kind: { - field: "Feld", - object: "Objekt", - view: "Ansicht", - dashboard: "Dashboard", - app: "App", - seed: "Beispieldaten", - package: "App-Paket", - }, }, }, chatbotError: { diff --git a/ui/packages/i18n/src/locales/en.ts b/ui/packages/i18n/src/locales/en.ts index ad149d80afa..7a5cd7556ac 100644 --- a/ui/packages/i18n/src/locales/en.ts +++ b/ui/packages/i18n/src/locales/en.ts @@ -3014,21 +3014,7 @@ const en = { }, ai: { pendingDrafts: { - // objectstack#34610 — the line points to the shell's draft bar and shows a publish receipt. - publishFromBar: '{{count}} unpublished changes. Publish them from the draft bar at the top.', - publishFromBar_one: '{{count}} unpublished change. Publish it from the draft bar at the top.', - publishFromBar_other: '{{count}} unpublished changes. Publish them from the draft bar at the top.', - showDraftToPublish: '{{count}} unpublished changes. Show the draft to review and publish them.', - showDraftToPublish_one: '{{count}} unpublished change. Show the draft to review and publish it.', - showDraftToPublish_other: '{{count}} unpublished changes. Show the draft to review and publish them.', - showDraft: 'Show draft', - receipt: 'Published. Your changes are live.', - dismissReceipt: 'Dismiss', count: '{{count}} change(s) are not published yet — users cannot see them.', - publish: 'Publish', - published: 'All pending changes are live.', - failed: 'Publish failed.', - publishedWithFindings: 'Published, but the runtime probes reported problems: {{detail}}', }, usage: { title: 'AI usage', @@ -3063,38 +3049,6 @@ const en = { share: 'Share', shareTitle: 'Share this conversation', shareDisabledTitle: 'Start chatting to enable sharing', - // The build conversation's Build Doctor button (its accessible name, - // and its tooltip enabled / before the first message) and the drawer - // title it opens (objectui#10900). - buildDoctor: 'Build Doctor', - buildDoctorTitle: 'Build Doctor — what actually landed?', - buildDoctorDisabledTitle: 'Send a message first', - // The Build Doctor drawer's body (objectui#10969): its description, the - // loading and not-found states, the summary line, the verdict, and each - // section's title and hint. What the report itself carries (tool, artifact - // and status names, timeline text) is data and stays verbatim. - buildDoctorDrawer: { - description: 'What the agent claimed vs what is actually live. Read-only diagnostic.', - reconciling: 'Reconciling…', - notAvailable: 'Not available — the conversation was not found or you are not authorized.', - untitled: '(untitled)', - summary: '{{turns}} turn(s) · {{messages}} msgs · {{tokens}} tok · {{seconds}}s LLM', - allLive: 'All {{count}} attempted change(s) are live — nothing evaporated.', - discrepancies: "{{count}} discrepancy(ies) — what the chat said doesn't match what's live.", - orphanedTitle: 'Proposed but never applied', - orphanedHint: 'A confirm card the agent proposed but no later turn applied — the change silently evaporated.', - missingTitle: 'Claimed but missing', - missingHint: "A tool result said it was applied, but the artifact isn't live in sys_metadata.", - toolErrorsTitle: 'Tool errors', - toolErrorsHint: 'Tool calls that returned an error during the build.', - verifyTitle: 'Build check (verify_build)', - yourApp: 'Your app:', - noIssues: '0 issues', - issueCount: '{{count}} issue(s)', - platformNoise: '{{count}} platform sys_* finding(s) hidden', - pendingActions: 'Pending actions', - timeline: 'Timeline ({{count}})', - }, newChat: 'New', searchChats: 'Search chats…', noChatsYet: 'No chats yet', @@ -3118,54 +3072,16 @@ const en = { liveCanvasLive: 'Live app — {{app}}', loadingAgents: 'Loading agents…', askAnything: 'Ask anything…', - askOrChangeApp: 'Ask about your data, or ask me to change this app…', - describeAppToBuild: 'Describe the app you want to build, or what to change…', emptyTitle: 'Start a conversation', emptyDescription: 'Ask anything — the assistant has access to your current app context.', switchAssistant: 'Switch assistant', chooseAgent: 'Choose assistant…', - // objectui#8329 — the maker's empty-state prose, and the FIRST sentence a - // new user reads on the build surface (it sits above the start chips). - // Same ADR-0112 v1 boundary the chips answer to (cloud#1984 / - // objectui#7709 for the starters, cloud#2022 for the model's own closing - // suggestions): these two descriptions are the product PROMISING, so they - // may only name what v1 BUILDS — objects, fields, views, pages, - // dashboards, sample data, apps and navigation. `build.description` used - // to offer "an app or workflow … objects, screens and automations" and - // `editApp.description` "… view or automation"; v1 has no flows, actions - // or schedules, so a user who took either at its word was refused - // outright — the worst possible answer to the first line on the page. - // - // NOT the same thing as the platform's manual automation surfaces, which - // are real and stay as they are: `home.build.subtitle` (that card opens - // Studio, which does author flows), `packagedAutomation.*` and the - // marketplace `automation` category. The boundary is v1 AI AUTHORING, not - // the word "automation". - // - // REVERT both sentences when ADR-0112 v2 re-adds flows and actions — same - // line of the version roadmap as the chips. Every pack's wording is - // guarded, in its own script, by - // `packages/i18n/src/__tests__/makerEmptyState-v1-scope-8329.test.ts`. empty: { - build: { - title: 'Build with AI', - description: - 'Describe an app in plain language — I draft the objects, screens and sample data, then you review and publish.', - }, ask: { title: 'Ask your data', description: 'Ask questions about your records — counts, lists, and summaries across the data you can access.', }, - editApp: { - title: 'Editing “{{app}}”', - titleGeneric: 'Edit this app', - description: - 'What would you like to change? I’ll modify this app in place — add a field, object, view or dashboard, or adjust what’s already there.', - // objectstack#34608 — the builder's empty state names both halves: data questions and changes. - askOrChangeDescription: - 'Ask about this app’s data — counts, lists and summaries — or tell me what to change, and I’ll modify the app in place: a field, an object, a view or a dashboard.', - }, }, clearConversation: 'Clear', sendHint: 'to send', @@ -3181,9 +3097,6 @@ const en = { // "Open in Builder" handoff card. The card's Approve / Reject buttons // borrow `aiApprovals.approveAndExecute` / `aiApprovals.reject`. toolDenyReason: 'Operator rejected from chat', - builderHandoffTitle: 'Build this in the Builder', - builderHandoffOpen: 'Open in Builder →', - builderHandoffSuperseded: 'A newer request is available', // cloud#3565 — the record-write card: ONE record the chat proposes and the user confirms (确认 / 打开完整表单 / 取消). recordWriteCreateTitle: 'New {{object}}', recordWriteUpdateTitle: 'Change {{object}}', @@ -3231,39 +3144,10 @@ const en = { stopResponse: 'Stop response', trace: 'trace', viewTrace: 'View trace', - // Build-flow draft + "Proposed plan" confirm-gate card (AiChatPage /ai/build). - // Mirror the ConsoleFloatingChatbot locale object so both AI surfaces match. - nextSteps: "What's next", - publishDrafts: 'Publish', - publishOk: 'Published — objects are now live.', - seedWarn: 'Published, but some sample data failed to load.', - openBuiltApp: 'Open app', - viewBuiltAppInStudio: 'View in Studio', - previewDraft: 'Preview', previewApp: 'Preview app', resizeSplit: 'Resize chat and preview', hideChats: 'Hide chats', showChats: 'Show chats', - planTitle: 'Proposed plan', - planQuestions: 'Confirm before building', - planAssumptions: 'Assumptions', - planApproveHint: 'Reply to approve or adjust this plan.', - planApprove: 'Build it', - planAdjust: 'Adjust', - planApproveMessage: 'Looks good — build it as proposed.', - planApproveDefaultsMessage: - 'Build it with your best assumptions; use sensible defaults for the open questions.', - planAnswerMessage: 'For "{{question}}", go with: {{option}}.', - planExtendExistingMessage: 'Keep improving "{{app}}" instead of building a new app.', - planBuildNewAppMessage: 'Build a separate, new app.', - changesTitle: 'Confirm changes', - changesConfirmed: 'Confirmed', - changesConfirm: 'Confirm', - changesConfirmHint: 'Reply to confirm or adjust this change.', - changesApplying: 'Applying…', - changesApplied: 'Applied', - changesDrafted: 'Saved as draft', - changesFailed: 'Not applied', discussing: 'Viewing: {{target}}', // objectstack#36999 — the conversation focus: the record the chat is pinned to. focus: { @@ -3274,32 +3158,14 @@ const en = { switchAccept: 'Switch', switchDecline: 'Keep', }, - // Wording is load-bearing: this is SENT to the agent and must satisfy the - // cloud confirm gate's English clause `apply (this|the) change` - // (service-ai-studio confirm-gate.ts APPROVAL_RE). "apply what you just - // proposed" did NOT match, so the button was inert. Singular "the change" - // so it still matches if the gate ever adds a word boundary. - changesConfirmMessage: 'Confirm — apply the change you just proposed.', - changeVerb: { - createObject: 'Create object', - addField: 'Add field', - modifyField: 'Modify field', - deleteField: 'Delete field', - createMetadata: 'Create', - updateMetadata: 'Modify', - createSeed: 'Generate sample data', - createPackage: 'Create app package', - }, justNow: 'just now', minutesAgo: '{{count}}m ago', hoursAgo: '{{count}}h ago', daysAgo: '{{count}}d ago', agentLabels: { ask: 'Ask', - build: 'Build', // Legacy keys kept for back-compat with any external overrides. dataChat: 'Assistant', - metadataAssistant: 'Metadata Assistant', }, suggestions: { dataChat: { @@ -3307,42 +3173,11 @@ const en = { recentRecords: 'List the 5 most recently created records.', recordCounts: 'Count records for each object.', }, - // cloud#1984 — these five chips are the maker's own recommendations, so - // they may only ask for what ADR-0112 v1 BUILDS: objects, fields, views - // (grid/kanban/calendar/gallery), pages, dashboards and sample data. No - // wording that promises autonomous behaviour (alert / remind / notify / - // automate / status workflow) — v1 has no flows, actions or schedules, and - // the model silently degrades such a request into a board or a filtered - // view, so the chip would promise an alert and deliver a page. REVERT to - // the automation wording when ADR-0112 v2 re-adds flows and actions. - metadataAssistant: { - buildCrm: 'Build a sales CRM — customers, contacts, and deals with a stage field, plus a dashboard that totals deal value by stage.', - buildApp: 'Create a project tracker — projects, tasks with owners and due dates, a board grouped by status, and a calendar of due dates.', - buildFlow: 'Design a support desk — tickets with priority and status fields, a board grouped by status, and links to customers.', - buildInventory: 'Build an inventory app — products, stock levels, suppliers, and a view that filters the items below their reorder point.', - buildRecruiting: 'Make an applicant tracker — candidates, open roles, an interview-stage field, and a board grouped by stage.', - }, generic: { help: 'What can you help me with?', availableObjects: 'List the available data objects.', recentActivity: 'Summarize my recent activity.', }, - // objectui#7709 — the edit-mode starters, shown when the maker is bound - // to an EXISTING app (`?package=`). Same rule as the five above: they - // may only ask for what ADR-0112 v1 BUILDS. The fourth chip used to be - // `addAutomation` ("an approval, a status flow, or a notification") and - // every capability it named is refused by v1 (cloud#1956 / PR #1970), so - // it now asks for sample data — `seed` IS on v1's whitelist, and having - // no data is what an existing app most often lacks. REVERT: when - // ADR-0112 v2 re-adds flows and actions, THIS chip's automation wording - // comes back as `addAutomation`; the retired string is pinned for every - // pack in `packages/i18n/src/__tests__/makerEditChips-v1-scope-7709.test.ts`. - editApp: { - addField: 'Add a field to one of the objects.', - addObject: 'Add a new object and relate it to an existing one.', - addDashboard: 'Add a dashboard for the key metrics.', - addSampleData: 'Fill the existing objects with realistic sample records so I can demo the app.', - }, }, // objectui#3546 slice four — the AI console surfaces: the /ai chat page's app switcher, // connection banner and plan/publish cards, the ChatDock chrome, and the @@ -3350,31 +3185,9 @@ const en = { // `console.ai.group.${key}` (ConversationsSidebar), enumerated from the // ConversationGroupKey union — all five members, no wildcard. collapseToDock: 'Collapse to side panel', - switchApp: 'Switch app', - switchAppLabel: 'Build conversations by app', - newApp: 'New app', connectionWaiting: 'Waiting for server…', connectionStalled: 'Still working…', connectionOffline: 'Connection lost — reconnecting…', - designingPlan: 'Designing your app…', - designingPlanHint: { - data: 'Mapping out the data you’ll track…', - objects: 'Shaping objects and their fields…', - relations: 'Connecting related records…', - lookups: 'Setting up relationships and lookups…', - views: 'Planning the screens and views…', - forms: 'Laying out forms and lists…', - defaults: 'Adding sensible defaults and validations…', - dashboard: 'Sketching a dashboard to track it…', - review: 'Double-checking the structure hangs together…', - finalize: 'Pulling the plan together…', - }, - planBuilding: 'Building…', - planBuilt: 'Built', - planDeferred: 'Not yet built', - planReady: 'The plan is ready. Build it now, or tell me what to adjust.', - published: 'Published', - publishFailed: 'Publish failed', unavailableTitle: 'AI assistant unavailable', unavailableDescription: "This deployment doesn't have an AI assistant enabled. Everything else works as usual.", unavailableError: "Couldn't reach the AI service. It may be temporarily offline — try again, or head back home.", @@ -5459,18 +5272,6 @@ const en = { derivedAiAccess: 'AI access turned on', }, }, - excelImport: { - noImportableFields: 'That object has no importable fields.', - schemaReadFailed: 'Could not read the object schema.', - imported: 'Imported {{count}} row(s) into {{object}}.', - imported_one: 'Imported {{count}} row into {{object}}.', - imported_other: 'Imported {{count}} rows into {{object}}.', - importFrom: 'Import the real rows from', - into: 'into', - opening: 'Opening…', - importAction: 'Import', - dismiss: 'Dismiss', - }, // `cloud:workspace-timezone-notice` — the Cloud welcome page's line naming the // timezone a workspace was seeded with at creation (objectui#11930). `{{zone}}` // is the seed, an IANA id printed verbatim. @@ -5722,123 +5523,18 @@ const en = { failed: 'Failed', }, phase: { - build: 'Build', - design: 'Design the plan', stepCount: '{{count}} steps', stepCount_one: '{{count}} step', stepCount_other: '{{count}} steps', expand: 'Show steps', collapse: 'Hide steps', }, - plan: { - countObjects: '{{count}} objects', - countObjects_one: '{{count}} object', - countObjects_other: '{{count}} objects', - countViews: '{{count}} views', - countViews_one: '{{count}} view', - countViews_other: '{{count}} views', - countDashboards: '{{count}} dashboards', - countDashboards_one: '{{count}} dashboard', - countDashboards_other: '{{count}} dashboards', - countSeedData: 'sample data', - extendTarget: 'Adding to existing app: {{app}}', - awaitingConfirm: 'Awaiting confirmation', - // objectstack#32984 — the plan card's build states. - confirmed: 'Confirmed', - buildFailed: 'Not built — nothing was created', - iterateOrNew: { - question: 'This overlaps "{{app}}", an app you already have. Keep improving it, or build a separate app?', - questionUnnamed: 'This overlaps an app you already have. Keep improving that app, or build a separate one?', - extend: 'Keep improving "{{app}}"', - buildNew: 'Build a separate app', - replyHint: 'Reply to say which.', - }, - objectsAndFields: 'Objects and fields', - views: 'Views', - suggestedField: 'suggested', - suggestedFieldLegend: 'Fields marked “{{mark}}” were added by the AI; you didn’t ask for them.', - nameField: 'Name: {{field}}', - }, build: { - building: 'Building {{app}}…', - built: 'Built {{app}}', - builtAndLive: 'Built and live · {{app}}', - appFallback: 'your app', - addingSampleData: 'adding sample data', - group: { - object: 'Objects', - view: 'Views', - dashboard: 'Dashboards', - app: 'App', - seed: 'Sample data', - dataset: 'Datasets', - permission: 'Permissions', - other: 'Other', - }, - moreArtifacts: '+{{n}} more', - verifying: 'Checking the change…', - verifyStep: 'step {{n}}', - verified: 'Checked the change', - // objectstack#32984 — the build card's issues line, in the customer's words. - issuesCount: '{{count}} to fix', issuesSummary: 'Some parts of this build need fixing before it is ready. Reply "fix the problems" and the assistant will repair them.', - warningsSummary: 'The build is ready, with a few things worth checking. Ask the assistant what they are if you want to improve them.', - issuesDetails: 'Technical details', - // objectstack#32984 — the published draft badge's failed-item count, which was English in every locale. - needsAttention: '{{count}} need attention', - needsAttention_one: '{{count}} needs attention', - needsAttention_other: '{{count}} need attention', // objectstack#32984 — the publish-health line under a Published badge, which was English in every locale. health: { - sampleRowsLive: '{{count}} sample rows live', - sampleRowsLive_one: '{{count}} sample row live', - sampleRowsLive_other: '{{count}} sample rows live', - views: '{{count}} views', - views_one: '{{count}} view', - views_other: '{{count}} views', - widgets: '{{count}} widgets', - widgets_one: '{{count}} widget', - widgets_other: '{{count}} widgets', - seeds: '{{count}} sample data sets', - seeds_one: '{{count}} sample data set', - seeds_other: '{{count}} sample data sets', - verified: '{{checks}} verified', seedFailed: 'Sample data failed to load.', }, - unknownPhase: 'Unknown build phase', - nextStepsLead: 'Next, you can say: {{steps}}', - nextStepQuote: '“{{step}}”', - draftPosture: 'Later changes are saved as drafts; click Publish here in the chat to make them live.', - checksPassed: 'Checks passed {{passed}}/{{total}}', - }, - changes: { - planTitle: 'Change plan · {{count}} changes', - planTitle_one: 'Change plan · {{count}} change', - planTitle_other: 'Change plan · {{count}} changes', - saveDraft: 'Save as draft', - reviewAndPublish: 'Review changes and publish', - undo: 'Undo', - undoWithOthers: 'Undo (and {{count}} other drafts)', - undoWithOthers_one: 'Undo (and {{count}} other draft)', - undoWithOthers_other: 'Undo (and {{count}} other drafts)', - undoConfirm: 'Undo discards all {{total}} unpublished drafts of this package, including {{count}} that are not part of this change.', - undoConfirm_one: 'Undo discards all {{total}} unpublished drafts of this package, including {{count}} that is not part of this change.', - undoConfirm_other: 'Undo discards all {{total}} unpublished drafts of this package, including {{count}} that are not part of this change.', - undoConfirmUnknown: 'Undo discards every unpublished draft of this package, not only this change.', - undoConfirmAction: 'Undo all', - undoCancel: 'Cancel', - undoing: 'Undoing…', - undone: 'Undone', - undoFailed: 'Undo failed', - kind: { - field: 'Field', - object: 'Object', - view: 'View', - dashboard: 'Dashboard', - app: 'App', - seed: 'Sample data', - package: 'App package', - }, }, }, chatbotError: { diff --git a/ui/packages/i18n/src/locales/es.ts b/ui/packages/i18n/src/locales/es.ts index bc44871fe39..7813b1cf04c 100644 --- a/ui/packages/i18n/src/locales/es.ts +++ b/ui/packages/i18n/src/locales/es.ts @@ -2269,23 +2269,7 @@ const es = { }, ai: { pendingDrafts: { - // objectstack#34610 — the line points to the shell's draft bar and shows a publish receipt. - publishFromBar: '{{count}} cambios sin publicar. Publícalos desde la barra del borrador de arriba.', - publishFromBar_one: '{{count}} cambio sin publicar. Publícalo desde la barra del borrador de arriba.', - publishFromBar_many: '{{count}} de cambios sin publicar. Publícalos desde la barra del borrador de arriba.', - publishFromBar_other: '{{count}} cambios sin publicar. Publícalos desde la barra del borrador de arriba.', - showDraftToPublish: '{{count}} cambios sin publicar. Muestra el borrador para revisarlos y publicarlos.', - showDraftToPublish_one: '{{count}} cambio sin publicar. Muestra el borrador para revisarlo y publicarlo.', - showDraftToPublish_many: '{{count}} de cambios sin publicar. Muestra el borrador para revisarlos y publicarlos.', - showDraftToPublish_other: '{{count}} cambios sin publicar. Muestra el borrador para revisarlos y publicarlos.', - showDraft: 'Mostrar borrador', - receipt: 'Publicado. Tus cambios ya están activos.', - dismissReceipt: 'Cerrar', count: "{{count}} cambio(s) aún no se han publicado — los usuarios no pueden verlos.", - publish: "Publicar", - published: "Todos los cambios pendientes están activos.", - failed: "Error al publicar.", - publishedWithFindings: "Publicado, pero las comprobaciones en tiempo de ejecución detectaron problemas: {{detail}}", }, usage: { title: "Uso de IA", @@ -2313,31 +2297,6 @@ const es = { share: "Compartir", shareTitle: "Compartir esta conversación", shareDisabledTitle: "Empiece a chatear para habilitar el uso compartido", - buildDoctor: "Diagnóstico de compilación", - buildDoctorTitle: "Diagnóstico de compilación — ¿qué se aplicó realmente?", - buildDoctorDisabledTitle: "Envíe primero un mensaje", - buildDoctorDrawer: { - description: 'Lo que el agente afirmó frente a lo que está realmente activo. Diagnóstico de solo lectura.', - reconciling: 'Conciliando…', - notAvailable: 'No disponible — no se encontró la conversación o no tiene autorización.', - untitled: '(sin título)', - summary: '{{turns}} turno(s) · {{messages}} msj · {{tokens}} tok · {{seconds}} s LLM', - allLive: 'Los {{count}} cambio(s) intentado(s) están activos — no se perdió nada.', - discrepancies: '{{count}} discrepancia(s) — lo que dijo el chat no coincide con lo que está activo.', - orphanedTitle: 'Propuesto pero nunca aplicado', - orphanedHint: 'Una tarjeta de confirmación que el agente propuso pero que ningún turno posterior aplicó — el cambio se perdió sin aviso.', - missingTitle: 'Afirmado pero ausente', - missingHint: 'Un resultado de herramienta indicó que se aplicó, pero el artefacto no está activo en sys_metadata.', - toolErrorsTitle: 'Errores de herramientas', - toolErrorsHint: 'Llamadas a herramientas que devolvieron un error durante la compilación.', - verifyTitle: 'Comprobación de compilación (verify_build)', - yourApp: 'Su aplicación:', - noIssues: '0 problemas', - issueCount: '{{count}} problema(s)', - platformNoise: '{{count}} hallazgo(s) sys_* de la plataforma oculto(s)', - pendingActions: 'Acciones pendientes', - timeline: 'Cronología ({{count}})', - }, newChat: "Nuevo", searchChats: "Buscar chats…", noChatsYet: "Todavía no hay chats", @@ -2359,29 +2318,15 @@ const es = { liveCanvasLive: "Aplicación en vivo — {{app}}", loadingAgents: "Cargando agentes…", askAnything: "Pregunte lo que quiera…", - askOrChangeApp: "Pregunte por sus datos o pídame que cambie esta app…", - describeAppToBuild: "Describa la app que quiere crear o lo que hay que cambiar…", emptyTitle: "Iniciar una conversación", emptyDescription: "Pregunte lo que quiera — el asistente tiene acceso al contexto de su aplicación actual.", switchAssistant: "Cambiar de asistente", chooseAgent: "Elegir asistente…", empty: { - build: { - title: "Crear con IA", - description: "Describa una aplicación en lenguaje natural — yo redacto los objetos, las pantallas y los datos de ejemplo, y luego usted revisa y publica.", - }, ask: { title: "Pregunte a sus datos", description: "Haga preguntas sobre sus registros — recuentos, listas y resúmenes de los datos a los que tiene acceso.", }, - editApp: { - title: "Editando «{{app}}»", - titleGeneric: "Editar esta aplicación", - description: "¿Qué desea cambiar? Modifico esta aplicación sobre la marcha — añadir un campo, un objeto, una vista o un panel, o ajustar lo que ya existe.", - // objectstack#34608 — the builder's empty state names both halves: data questions and changes. - askOrChangeDescription: - "Pregunta por los datos de esta app —recuentos, listas y resúmenes— o dime qué cambiar y modificaré la app al momento: un campo, un objeto, una vista o un panel.", - }, }, clearConversation: "Borrar", sendHint: "para enviar", @@ -2393,9 +2338,6 @@ const es = { toolFailed: "Error", toolDetailsHidden: "Las entradas de las herramientas y los resultados sin procesar están ocultos en esta vista.", toolDenyReason: "Rechazado por el operador desde el chat", - builderHandoffTitle: "Crear en el constructor", - builderHandoffOpen: "Abrir en el constructor →", - builderHandoffSuperseded: "Hay una solicitud más reciente", recordWriteCreateTitle: "Nuevo {{object}}", recordWriteUpdateTitle: "Cambiar {{object}}", recordWriteConfirm: "Confirmar", @@ -2448,32 +2390,17 @@ const es = { stopResponse: "Detener la respuesta", trace: "traza", viewTrace: "Ver la traza", - nextSteps: "Qué sigue", - publishDrafts: "Publicar", - publishOk: "Publicado — los objetos ya están activos.", - seedWarn: "Publicado, pero no se pudieron cargar algunos datos de ejemplo.", - openBuiltApp: "Abrir la aplicación", - viewBuiltAppInStudio: "Ver en Studio", - previewDraft: "Vista previa", previewApp: "Vista previa de la aplicación", resizeSplit: "Redimensionar el chat y la vista previa", hideChats: "Ocultar los chats", showChats: "Mostrar los chats", - planTitle: "Plan propuesto", - planQuestions: "Confirmar antes de crear", - planAssumptions: "Supuestos", - planApproveHint: "Responda para aprobar o ajustar este plan.", - planApprove: "Crearlo", - planAdjust: "Ajustar", justNow: "ahora mismo", minutesAgo: "hace {{count}} min", hoursAgo: "hace {{count}} h", daysAgo: "hace {{count}} d", agentLabels: { ask: "Preguntar", - build: "Crear", dataChat: "Asistente", - metadataAssistant: "Asistente de metadatos", }, suggestions: { dataChat: { @@ -2481,51 +2408,12 @@ const es = { recentRecords: "Enumera los 5 registros creados más recientemente.", recordCounts: "Cuenta los registros de cada objeto.", }, - // cloud#1984 — these five chips are the maker's own recommendations, so - // they may only ask for what ADR-0112 v1 BUILDS: objects, fields, views - // (grid/kanban/calendar/gallery), pages, dashboards and sample data. No - // wording that promises autonomous behaviour (alert / remind / notify / - // automate / status workflow) — v1 has no flows, actions or schedules, and - // the model silently degrades such a request into a board or a filtered - // view, so the chip would promise an alert and deliver a page. REVERT to - // the automation wording when ADR-0112 v2 re-adds flows and actions. - metadataAssistant: { - buildCrm: "Crea un CRM de ventas — clientes, contactos y oportunidades con un campo de etapa, y un panel que sume el importe por etapa.", - buildApp: "Crea un seguimiento de proyectos — proyectos, tareas con responsables y fechas de vencimiento, un tablero por estado y un calendario de vencimientos.", - buildFlow: "Diseña una mesa de ayuda — tickets con campos de prioridad y estado, un tablero por estado y vínculos con los clientes.", - buildInventory: "Crea una aplicación de inventario — productos, niveles de stock, proveedores y una vista que filtre los artículos por debajo de su punto de pedido.", - buildRecruiting: "Crea un seguimiento de candidaturas — candidatos, vacantes, un campo de etapa de entrevista y un tablero por etapa.", - }, generic: { help: "¿En qué puedes ayudarme?", availableObjects: "Enumera los objetos de datos disponibles.", recentActivity: "Resume mi actividad reciente.", }, - // objectui#7709 — the edit-mode starters, shown when the maker is bound - // to an EXISTING app (`?package=`). Same rule as the five above: they - // may only ask for what ADR-0112 v1 BUILDS. The fourth chip used to be - // `addAutomation` ("an approval, a status flow, or a notification") and - // every capability it named is refused by v1 (cloud#1956 / PR #1970), so - // it now asks for sample data — `seed` IS on v1's whitelist, and having - // no data is what an existing app most often lacks. REVERT: when - // ADR-0112 v2 re-adds flows and actions, THIS chip's automation wording - // comes back as `addAutomation`; the retired string is pinned for every - // pack in `packages/i18n/src/__tests__/makerEditChips-v1-scope-7709.test.ts`. - editApp: { - addField: "Añade un campo a uno de los objetos.", - addObject: "Añade un objeto nuevo y relaciónalo con uno existente.", - addDashboard: "Añade un panel para las métricas clave.", - addSampleData: "Rellena los objetos existentes con registros de ejemplo realistas para poder mostrar la aplicación.", - }, }, - changesTitle: "Confirmar cambios", - changesConfirmed: "Confirmado", - changesConfirm: "Confirmar", - changesConfirmHint: "Responda para confirmar o ajustar este cambio.", - changesApplying: "Aplicando…", - changesApplied: "Aplicado", - changesDrafted: "Guardado como borrador", - changesFailed: "No aplicado", discussing: "Viendo: {{target}}", focus: { pin: "Seguir preguntando sobre este registro", @@ -2535,47 +2423,15 @@ const es = { switchAccept: "Cambiar", switchDecline: "Mantener", }, - changeVerb: { - createObject: "Crear objeto", - addField: "Añadir campo", - modifyField: "Modificar campo", - deleteField: "Eliminar campo", - createMetadata: "Crear", - updateMetadata: "Modificar", - createSeed: "Generar datos de ejemplo", - createPackage: "Crear paquete de aplicación", - }, // objectui#3546 slice four — the AI console surfaces: the /ai chat page's app switcher, // connection banner and plan/publish cards, the ChatDock chrome, and the // conversation-list date buckets. `group.*` is the template-key family // `console.ai.group.${key}` (ConversationsSidebar), enumerated from the // ConversationGroupKey union — all five members, no wildcard. collapseToDock: "Contraer al panel lateral", - switchApp: "Cambiar de aplicación", - switchAppLabel: "Conversaciones de creación por aplicación", - newApp: "Nueva aplicación", connectionWaiting: "Esperando al servidor…", connectionStalled: "Sigue en proceso…", connectionOffline: "Conexión perdida — reconectando…", - designingPlan: "Diseñando su aplicación…", - designingPlanHint: { - data: "Trazando los datos que va a registrar…", - objects: "Dando forma a los objetos y sus campos…", - relations: "Conectando los registros relacionados…", - lookups: "Configurando las relaciones y los campos de búsqueda…", - views: "Planificando las pantallas y las vistas…", - forms: "Organizando los formularios y las listas…", - defaults: "Agregando valores predeterminados y validaciones razonables…", - dashboard: "Bosquejando un panel para el seguimiento…", - review: "Comprobando que la estructura encaje…", - finalize: "Reuniendo el plan…", - }, - planBuilding: "Creando…", - planBuilt: "Creado", - planDeferred: "Aún no creado", - planReady: "El plan está listo. Créelo ahora o dígame qué ajustar.", - published: "Publicado", - publishFailed: "Error al publicar", unavailableTitle: "Asistente de IA no disponible", unavailableDescription: "Esta implementación no tiene habilitado un asistente de IA. Todo lo demás funciona con normalidad.", unavailableError: "No se pudo contactar con el servicio de IA. Puede estar temporalmente sin conexión — reinténtelo o vuelva al inicio.", @@ -4608,19 +4464,6 @@ const es = { derivedAiAccess: 'Acceso a IA activado', }, }, - excelImport: { - noImportableFields: "Ese objeto no tiene campos importables.", - schemaReadFailed: "No se pudo leer el esquema del objeto.", - imported: "Se importaron {{count}} fila(s) en {{object}}.", - imported_one: "Se importó {{count}} fila en {{object}}.", - imported_many: "Se importaron {{count}} de filas en {{object}}.", - imported_other: "Se importaron {{count}} filas en {{object}}.", - importFrom: "Importar las filas reales desde", - into: "a", - opening: "Abriendo…", - importAction: "Importar", - dismiss: "Descartar", - }, cloudWorkspaceTimezoneNotice: { seeded: "La zona horaria del entorno se configuró en {{zone}} a partir de su navegador al crearlo. Puede cambiarla en Configuración → Localización.", }, @@ -4845,8 +4688,6 @@ const es = { failed: "Fallido", }, phase: { - build: "Creación", - design: "Diseño del plan", stepCount: "{{count}} pasos", stepCount_one: "{{count}} paso", stepCount_many: "{{count}} de pasos", @@ -4854,125 +4695,11 @@ const es = { expand: "Mostrar pasos", collapse: "Ocultar pasos", }, - plan: { - countObjects: "{{count}} objetos", - countObjects_one: "{{count}} objeto", - countObjects_many: "{{count}} de objetos", - countObjects_other: "{{count}} objetos", - countViews: "{{count}} vistas", - countViews_one: "{{count}} vista", - countViews_many: "{{count}} de vistas", - countViews_other: "{{count}} vistas", - countDashboards: "{{count}} paneles", - countDashboards_one: "{{count}} panel", - countDashboards_many: "{{count}} de paneles", - countDashboards_other: "{{count}} paneles", - countSeedData: "datos de ejemplo", - extendTarget: "Se añade a la app existente: {{app}}", - awaitingConfirm: "Pendiente de confirmación", - // objectstack#32984 — the plan card's build states. - confirmed: "Confirmado", - buildFailed: "No construido: no se creó nada", - iterateOrNew: { - question: "Esto se solapa con «{{app}}», una app que ya tiene. ¿Seguir mejorándola o crear una app independiente?", - questionUnnamed: "Esto se solapa con una app que ya tiene. ¿Seguir mejorando esa app o crear una independiente?", - extend: "Seguir mejorando «{{app}}»", - buildNew: "Crear una app independiente", - replyHint: "Responda para indicar cuál prefiere.", - }, - objectsAndFields: "Objetos y campos", - views: "Vistas", - suggestedField: "sugerido", - suggestedFieldLegend: "Los campos marcados como «{{mark}}» los añadió la IA; usted no los pidió.", - nameField: "Nombre: {{field}}", - }, build: { - building: "Creando {{app}}…", - built: "Creación de {{app}} completada", - builtAndLive: "Creada y publicada · {{app}}", - appFallback: "su aplicación", - addingSampleData: "añadiendo datos de ejemplo", - group: { - object: "Objetos", - view: "Vistas", - dashboard: "Paneles", - app: "Aplicación", - seed: "Datos de ejemplo", - dataset: "Conjuntos de datos", - permission: "Permisos", - other: "Otros", - }, - moreArtifacts: "+{{n}} más", - verifying: "Comprobando el cambio…", - verifyStep: "paso {{n}}", - verified: "Cambio comprobado", - // objectstack#32984 — the build card's issues line, in the customer's words. - issuesCount: "{{count}} por corregir", issuesSummary: "Algunas partes de esta construcción deben corregirse antes de poder usarse. Responde «corrige los problemas» y el asistente las reparará.", - warningsSummary: "La aplicación está construida, con algunos puntos que conviene revisar. Pregunta al asistente cuáles son si quieres mejorarla.", - issuesDetails: "Detalles técnicos", - // objectstack#32984 — the published draft badge's failed-item count, which was English in every locale. - needsAttention: "{{count}} requieren atención", - needsAttention_one: "{{count}} requiere atención", - needsAttention_many: "{{count}} de elementos requieren atención", - needsAttention_other: "{{count}} requieren atención", health: { - sampleRowsLive: "{{count}} filas de ejemplo publicadas", - sampleRowsLive_one: "{{count}} fila de ejemplo publicada", - sampleRowsLive_many: "{{count}} de filas de ejemplo publicadas", - sampleRowsLive_other: "{{count}} filas de ejemplo publicadas", - views: "{{count}} vistas", - views_one: "{{count}} vista", - views_many: "{{count}} de vistas", - views_other: "{{count}} vistas", - widgets: "{{count}} widgets", - widgets_one: "{{count}} widget", - widgets_many: "{{count}} de widgets", - widgets_other: "{{count}} widgets", - seeds: "{{count}} conjuntos de datos de ejemplo", - seeds_one: "{{count}} conjunto de datos de ejemplo", - seeds_many: "{{count}} de conjuntos de datos de ejemplo", - seeds_other: "{{count}} conjuntos de datos de ejemplo", - verified: "Verificado: {{checks}}", seedFailed: "No se pudieron cargar los datos de ejemplo.", }, - unknownPhase: "Fase de creación desconocida", - nextStepsLead: "A continuación puede decir: {{steps}}", - nextStepQuote: "«{{step}}»", - draftPosture: "Los cambios posteriores se guardan como borrador; publíquelos con «Publicar» aquí en el chat.", - checksPassed: "Comprobaciones superadas {{passed}}/{{total}}", - }, - changes: { - planTitle: "Plan de cambios · {{count}} cambios", - planTitle_one: "Plan de cambios · {{count}} cambio", - planTitle_many: "Plan de cambios · {{count}} de cambios", - planTitle_other: "Plan de cambios · {{count}} cambios", - saveDraft: "Guardar como borrador", - reviewAndPublish: "Revisar cambios y publicar", - undo: "Deshacer", - undoWithOthers: "Deshacer (y {{count}} borradores más)", - undoWithOthers_one: "Deshacer (y {{count}} borrador más)", - undoWithOthers_many: "Deshacer (y {{count}} de borradores más)", - undoWithOthers_other: "Deshacer (y {{count}} borradores más)", - undoConfirm: "Deshacer descarta los {{total}} borradores sin publicar de este paquete, incluidos {{count}} que no forman parte de este cambio.", - undoConfirm_one: "Deshacer descarta los {{total}} borradores sin publicar de este paquete, incluido {{count}} que no forma parte de este cambio.", - undoConfirm_many: "Deshacer descarta los {{total}} borradores sin publicar de este paquete, incluidos {{count}} de borradores que no forman parte de este cambio.", - undoConfirm_other: "Deshacer descarta los {{total}} borradores sin publicar de este paquete, incluidos {{count}} que no forman parte de este cambio.", - undoConfirmUnknown: "Deshacer descarta todos los borradores sin publicar de este paquete, no solo este cambio.", - undoConfirmAction: "Deshacer todo", - undoCancel: "Cancelar", - undoing: "Deshaciendo…", - undone: "Deshecho", - undoFailed: "No se pudo deshacer", - kind: { - field: "Campo", - object: "Objeto", - view: "Vista", - dashboard: "Panel", - app: "Aplicación", - seed: "Datos de ejemplo", - package: "Paquete de aplicación", - }, }, }, chatbotError: { diff --git a/ui/packages/i18n/src/locales/fr.ts b/ui/packages/i18n/src/locales/fr.ts index f25f86cb702..32a0d00c3f0 100644 --- a/ui/packages/i18n/src/locales/fr.ts +++ b/ui/packages/i18n/src/locales/fr.ts @@ -2265,23 +2265,7 @@ const fr = { }, ai: { pendingDrafts: { - // objectstack#34610 — the line points to the shell's draft bar and shows a publish receipt. - publishFromBar: '{{count}} modifications non publiées. Publiez-les depuis la barre du brouillon en haut.', - publishFromBar_one: '{{count}} modification non publiée. Publiez-la depuis la barre du brouillon en haut.', - publishFromBar_many: '{{count}} de modifications non publiées. Publiez-les depuis la barre du brouillon en haut.', - publishFromBar_other: '{{count}} modifications non publiées. Publiez-les depuis la barre du brouillon en haut.', - showDraftToPublish: '{{count}} modifications non publiées. Affichez le brouillon pour les vérifier et les publier.', - showDraftToPublish_one: '{{count}} modification non publiée. Affichez le brouillon pour la vérifier et la publier.', - showDraftToPublish_many: '{{count}} de modifications non publiées. Affichez le brouillon pour les vérifier et les publier.', - showDraftToPublish_other: '{{count}} modifications non publiées. Affichez le brouillon pour les vérifier et les publier.', - showDraft: 'Afficher le brouillon', - receipt: 'Publié. Vos modifications sont en ligne.', - dismissReceipt: 'Fermer', count: "{{count}} modification(s) ne sont pas encore publiée(s) — les utilisateurs ne peuvent pas les voir.", - publish: "Publier", - published: "Toutes les modifications en attente sont actives.", - failed: "Échec de la publication.", - publishedWithFindings: "Publié, mais les contrôles d'exécution ont signalé des problèmes : {{detail}}", }, usage: { title: "Utilisation de l'IA", @@ -2309,31 +2293,6 @@ const fr = { share: "Partager", shareTitle: "Partager cette conversation", shareDisabledTitle: "Commencez à discuter pour activer le partage", - buildDoctor: "Diagnostic de build", - buildDoctorTitle: "Diagnostic de build — qu'est-ce qui a réellement été appliqué ?", - buildDoctorDisabledTitle: "Envoyez d'abord un message", - buildDoctorDrawer: { - description: "Ce que l'agent a annoncé face à ce qui est réellement en ligne. Diagnostic en lecture seule.", - reconciling: 'Rapprochement…', - notAvailable: "Non disponible — la conversation est introuvable ou vous n'êtes pas autorisé.", - untitled: '(sans titre)', - summary: '{{turns}} tour(s) · {{messages}} msg · {{tokens}} jetons · {{seconds}} s LLM', - allLive: "Les {{count}} modification(s) tentée(s) sont en ligne — rien ne s'est perdu.", - discrepancies: '{{count}} écart(s) — ce que le chat a annoncé ne correspond pas à ce qui est en ligne.', - orphanedTitle: 'Proposé mais jamais appliqué', - orphanedHint: "Une carte de confirmation proposée par l'agent qu'aucun tour ultérieur n'a appliquée — la modification s'est perdue silencieusement.", - missingTitle: 'Annoncé mais absent', - missingHint: "Un résultat d'outil indiquait une application, mais l'artefact n'est pas en ligne dans sys_metadata.", - toolErrorsTitle: "Erreurs d'outils", - toolErrorsHint: "Appels d'outils ayant renvoyé une erreur pendant le build.", - verifyTitle: 'Vérification du build (verify_build)', - yourApp: 'Votre application :', - noIssues: '0 problème', - issueCount: '{{count}} problème(s)', - platformNoise: '{{count}} constat(s) sys_* de la plateforme masqué(s)', - pendingActions: 'Actions en attente', - timeline: 'Chronologie ({{count}})', - }, newChat: "Nouveau", searchChats: "Rechercher des discussions…", noChatsYet: "Aucune discussion pour l'instant", @@ -2355,29 +2314,15 @@ const fr = { liveCanvasLive: "Application en direct — {{app}}", loadingAgents: "Chargement des agents…", askAnything: "Posez n'importe quelle question…", - askOrChangeApp: "Posez une question sur vos données ou demandez-moi de modifier cette app…", - describeAppToBuild: "Décrivez l’app que vous voulez créer, ou ce qu’il faut modifier…", emptyTitle: "Démarrer une conversation", emptyDescription: "Posez n'importe quelle question — l'assistant a accès au contexte de votre application actuelle.", switchAssistant: "Changer d'assistant", chooseAgent: "Choisir un assistant…", empty: { - build: { - title: "Créer avec l'IA", - description: "Décrivez une application en langage courant — je rédige les objets, les écrans et les données d'exemple, puis vous vérifiez et publiez.", - }, ask: { title: "Interroger vos données", description: "Posez des questions sur vos enregistrements — comptages, listes et synthèses sur les données auxquelles vous avez accès.", }, - editApp: { - title: "Modification de « {{app}} »", - titleGeneric: "Modifier cette application", - description: "Que souhaitez-vous changer ? Je modifie cette application sur place — ajouter un champ, un objet, une vue ou un tableau de bord, ou ajuster l'existant.", - // objectstack#34608 — the builder's empty state names both halves: data questions and changes. - askOrChangeDescription: - "Posez une question sur les données de cette application — comptages, listes et synthèses — ou dites-moi quoi changer, et je modifie l’application sur place : un champ, un objet, une vue ou un tableau de bord.", - }, }, clearConversation: "Effacer", sendHint: "pour envoyer", @@ -2389,9 +2334,6 @@ const fr = { toolFailed: "Échec", toolDetailsHidden: "Les entrées des outils et les résultats bruts sont masqués dans cette vue.", toolDenyReason: "Rejeté par l'opérateur depuis le chat", - builderHandoffTitle: "Créer dans le constructeur", - builderHandoffOpen: "Ouvrir dans le constructeur →", - builderHandoffSuperseded: "Une demande plus récente est disponible", recordWriteCreateTitle: "Nouveau {{object}}", recordWriteUpdateTitle: "Modifier {{object}}", recordWriteConfirm: "Confirmer", @@ -2444,32 +2386,17 @@ const fr = { stopResponse: "Arrêter la réponse", trace: "trace", viewTrace: "Afficher la trace", - nextSteps: "Et ensuite", - publishDrafts: "Publier", - publishOk: "Publié — les objets sont maintenant actifs.", - seedWarn: "Publié, mais certaines données d'exemple n'ont pas pu être chargées.", - openBuiltApp: "Ouvrir l'application", - viewBuiltAppInStudio: "Voir dans Studio", - previewDraft: "Aperçu", previewApp: "Aperçu de l'application", resizeSplit: "Redimensionner la discussion et l'aperçu", hideChats: "Masquer les discussions", showChats: "Afficher les discussions", - planTitle: "Plan proposé", - planQuestions: "Confirmer avant de créer", - planAssumptions: "Hypothèses", - planApproveHint: "Répondez pour approuver ou ajuster ce plan.", - planApprove: "Créer", - planAdjust: "Ajuster", justNow: "à l'instant", minutesAgo: "il y a {{count}} min", hoursAgo: "il y a {{count}} h", daysAgo: "il y a {{count}} j", agentLabels: { ask: "Demander", - build: "Créer", dataChat: "Assistant", - metadataAssistant: "Assistant de métadonnées", }, suggestions: { dataChat: { @@ -2477,51 +2404,12 @@ const fr = { recentRecords: "Liste les 5 enregistrements créés le plus récemment.", recordCounts: "Compte les enregistrements pour chaque objet.", }, - // cloud#1984 — these five chips are the maker's own recommendations, so - // they may only ask for what ADR-0112 v1 BUILDS: objects, fields, views - // (grid/kanban/calendar/gallery), pages, dashboards and sample data. No - // wording that promises autonomous behaviour (alert / remind / notify / - // automate / status workflow) — v1 has no flows, actions or schedules, and - // the model silently degrades such a request into a board or a filtered - // view, so the chip would promise an alert and deliver a page. REVERT to - // the automation wording when ADR-0112 v2 re-adds flows and actions. - metadataAssistant: { - buildCrm: "Crée un CRM commercial — clients, contacts et affaires avec un champ étape, plus un tableau de bord qui totalise le montant par étape.", - buildApp: "Crée un suivi de projets — projets, tâches avec responsables et échéances, un tableau par statut et un calendrier des échéances.", - buildFlow: "Conçois un service d'assistance — tickets avec des champs priorité et statut, un tableau par statut et des liens vers les clients.", - buildInventory: "Crée une application de stock — produits, niveaux de stock, fournisseurs et une vue qui filtre les articles sous leur seuil de réapprovisionnement.", - buildRecruiting: "Crée un suivi de candidatures — candidats, postes ouverts, un champ étape d'entretien et un tableau par étape.", - }, generic: { help: "En quoi peux-tu m'aider ?", availableObjects: "Liste les objets de données disponibles.", recentActivity: "Résume mon activité récente.", }, - // objectui#7709 — the edit-mode starters, shown when the maker is bound - // to an EXISTING app (`?package=`). Same rule as the five above: they - // may only ask for what ADR-0112 v1 BUILDS. The fourth chip used to be - // `addAutomation` ("an approval, a status flow, or a notification") and - // every capability it named is refused by v1 (cloud#1956 / PR #1970), so - // it now asks for sample data — `seed` IS on v1's whitelist, and having - // no data is what an existing app most often lacks. REVERT: when - // ADR-0112 v2 re-adds flows and actions, THIS chip's automation wording - // comes back as `addAutomation`; the retired string is pinned for every - // pack in `packages/i18n/src/__tests__/makerEditChips-v1-scope-7709.test.ts`. - editApp: { - addField: "Ajoute un champ à l'un des objets.", - addObject: "Ajoute un nouvel objet et relie-le à un objet existant.", - addDashboard: "Ajoute un tableau de bord pour les indicateurs clés.", - addSampleData: "Remplis les objets existants avec des données d'exemple réalistes pour que je puisse présenter l'application.", - }, }, - changesTitle: "Confirmer les modifications", - changesConfirmed: "Confirmé", - changesConfirm: "Confirmer", - changesConfirmHint: "Répondez pour confirmer ou ajuster cette modification.", - changesApplying: "Application…", - changesApplied: "Appliqué", - changesDrafted: "Enregistré comme brouillon", - changesFailed: "Non appliqué", discussing: "Affiché : {{target}}", focus: { pin: "Continuer à poser des questions sur cet enregistrement", @@ -2531,47 +2419,15 @@ const fr = { switchAccept: "Changer", switchDecline: "Conserver", }, - changeVerb: { - createObject: "Créer un objet", - addField: "Ajouter un champ", - modifyField: "Modifier un champ", - deleteField: "Supprimer un champ", - createMetadata: "Créer", - updateMetadata: "Modifier", - createSeed: "Générer des données d'exemple", - createPackage: "Créer un package d'application", - }, // objectui#3546 slice four — the AI console surfaces: the /ai chat page's app switcher, // connection banner and plan/publish cards, the ChatDock chrome, and the // conversation-list date buckets. `group.*` is the template-key family // `console.ai.group.${key}` (ConversationsSidebar), enumerated from the // ConversationGroupKey union — all five members, no wildcard. collapseToDock: "Réduire dans le panneau latéral", - switchApp: "Changer d'application", - switchAppLabel: "Conversations de création par application", - newApp: "Nouvelle application", connectionWaiting: "En attente du serveur…", connectionStalled: "Toujours en cours…", connectionOffline: "Connexion perdue — reconnexion…", - designingPlan: "Conception de votre application…", - designingPlanHint: { - data: "Cartographie des données que vous allez suivre…", - objects: "Définition des objets et de leurs champs…", - relations: "Connexion des enregistrements liés…", - lookups: "Configuration des relations et des champs de recherche…", - views: "Planification des écrans et des vues…", - forms: "Mise en page des formulaires et des listes…", - defaults: "Ajout de valeurs par défaut et de validations pertinentes…", - dashboard: "Esquisse d'un tableau de bord pour le suivi…", - review: "Vérification de la cohérence de la structure…", - finalize: "Assemblage du plan…", - }, - planBuilding: "Création…", - planBuilt: "Créé", - planDeferred: "Pas encore créé", - planReady: "Le plan est prêt. Créez-le maintenant, ou dites-moi ce qu'il faut ajuster.", - published: "Publié", - publishFailed: "Échec de la publication", unavailableTitle: "Assistant IA non disponible", unavailableDescription: "Cette instance n'a pas d'assistant IA activé. Tout le reste fonctionne normalement.", unavailableError: "Impossible de joindre le service IA. Il est peut-être temporairement hors ligne — réessayez, ou retournez à l'accueil.", @@ -4604,19 +4460,6 @@ const fr = { derivedAiAccess: 'Accès IA activé', }, }, - excelImport: { - noImportableFields: "Cet objet n'a aucun champ importable.", - schemaReadFailed: "Impossible de lire le schéma de l'objet.", - imported: "{{count}} ligne(s) importée(s) dans {{object}}.", - imported_one: "{{count}} ligne importée dans {{object}}.", - imported_many: "{{count}} de lignes importées dans {{object}}.", - imported_other: "{{count}} lignes importées dans {{object}}.", - importFrom: "Importer les lignes réelles depuis", - into: "vers", - opening: "Ouverture…", - importAction: "Importer", - dismiss: "Ignorer", - }, cloudWorkspaceTimezoneNotice: { seeded: "Le fuseau horaire de l’environnement a été défini sur {{zone}} d’après votre navigateur lors de sa création. Vous pouvez le modifier dans Paramètres → Localisation.", }, @@ -4841,8 +4684,6 @@ const fr = { failed: "Échec", }, phase: { - build: "Création", - design: "Conception du plan", stepCount: "{{count}} étapes", stepCount_one: "{{count}} étape", stepCount_many: "{{count}} d’étapes", @@ -4850,125 +4691,11 @@ const fr = { expand: "Afficher les étapes", collapse: "Masquer les étapes", }, - plan: { - countObjects: "{{count}} objets", - countObjects_one: "{{count}} objet", - countObjects_many: "{{count}} d'objets", - countObjects_other: "{{count}} objets", - countViews: "{{count}} vues", - countViews_one: "{{count}} vue", - countViews_many: "{{count}} de vues", - countViews_other: "{{count}} vues", - countDashboards: "{{count}} tableaux de bord", - countDashboards_one: "{{count}} tableau de bord", - countDashboards_many: "{{count}} de tableaux de bord", - countDashboards_other: "{{count}} tableaux de bord", - countSeedData: "données d’exemple", - extendTarget: "Ajout à l’app existante : {{app}}", - awaitingConfirm: "En attente de confirmation", - // objectstack#32984 — the plan card's build states. - confirmed: "Confirmé", - buildFailed: "Non construit — rien n’a été créé", - iterateOrNew: { - question: "Ce plan recoupe « {{app}} », une app que vous avez déjà. Continuer à l’améliorer, ou créer une app distincte ?", - questionUnnamed: "Ce plan recoupe une app que vous avez déjà. Continuer à améliorer cette app, ou en créer une distincte ?", - extend: "Continuer à améliorer « {{app}} »", - buildNew: "Créer une app distincte", - replyHint: "Répondez pour indiquer votre choix.", - }, - objectsAndFields: "Objets et champs", - views: "Vues", - suggestedField: "suggéré", - suggestedFieldLegend: "Les champs marqués « {{mark}} » ont été ajoutés par l’IA ; vous ne les avez pas demandés.", - nameField: "Nom : {{field}}", - }, build: { - building: "Création de {{app}}…", - built: "Création de {{app}} terminée", - builtAndLive: "Créée et en ligne · {{app}}", - appFallback: "votre application", - addingSampleData: "ajout de données d’exemple", - group: { - object: "Objets", - view: "Vues", - dashboard: "Tableaux de bord", - app: "Application", - seed: "Données d’exemple", - dataset: "Jeux de données", - permission: "Autorisations", - other: "Autres", - }, - moreArtifacts: "+{{n}} autres", - verifying: "Vérification de la modification…", - verifyStep: "étape {{n}}", - verified: "Modification vérifiée", - // objectstack#32984 — the build card's issues line, in the customer's words. - issuesCount: "{{count}} à corriger", issuesSummary: "Certaines parties de cette construction doivent être corrigées avant d’être utilisables. Répondez « corrige les problèmes » et l’assistant s’en chargera.", - warningsSummary: "L’application est construite, avec quelques points à vérifier. Demandez à l’assistant lesquels si vous voulez l’améliorer.", - issuesDetails: "Détails techniques", - // objectstack#32984 — the published draft badge's failed-item count, which was English in every locale. - needsAttention: "{{count}} nécessitent une vérification", - needsAttention_one: "{{count}} nécessite une vérification", - needsAttention_many: "{{count}} d’éléments nécessitent une vérification", - needsAttention_other: "{{count}} nécessitent une vérification", health: { - sampleRowsLive: "{{count}} lignes d’exemple en ligne", - sampleRowsLive_one: "{{count}} ligne d’exemple en ligne", - sampleRowsLive_many: "{{count}} de lignes d’exemple en ligne", - sampleRowsLive_other: "{{count}} lignes d’exemple en ligne", - views: "{{count}} vues", - views_one: "{{count}} vue", - views_many: "{{count}} de vues", - views_other: "{{count}} vues", - widgets: "{{count}} widgets", - widgets_one: "{{count}} widget", - widgets_many: "{{count}} de widgets", - widgets_other: "{{count}} widgets", - seeds: "{{count}} jeux de données d’exemple", - seeds_one: "{{count}} jeu de données d’exemple", - seeds_many: "{{count}} de jeux de données d’exemple", - seeds_other: "{{count}} jeux de données d’exemple", - verified: "Vérifié : {{checks}}", seedFailed: "Les données d’exemple n’ont pas pu être chargées.", }, - unknownPhase: "Phase de création inconnue", - nextStepsLead: "Ensuite, vous pouvez dire : {{steps}}", - nextStepQuote: "« {{step}} »", - draftPosture: "Les modifications suivantes sont enregistrées comme brouillons ; publiez-les avec « Publier » ici, dans le chat.", - checksPassed: "Vérifications réussies {{passed}}/{{total}}", - }, - changes: { - planTitle: "Plan de modifications · {{count}} modifications", - planTitle_one: "Plan de modifications · {{count}} modification", - planTitle_many: "Plan de modifications · {{count}} de modifications", - planTitle_other: "Plan de modifications · {{count}} modifications", - saveDraft: "Enregistrer comme brouillon", - reviewAndPublish: "Vérifier les modifications et publier", - undo: "Annuler", - undoWithOthers: "Annuler (avec {{count}} autres brouillons)", - undoWithOthers_one: "Annuler (avec {{count}} autre brouillon)", - undoWithOthers_many: "Annuler (avec {{count}} d'autres brouillons)", - undoWithOthers_other: "Annuler (avec {{count}} autres brouillons)", - undoConfirm: "Annuler supprime les {{total}} brouillons non publiés de ce package, dont {{count}} qui ne font pas partie de cette modification.", - undoConfirm_one: "Annuler supprime les {{total}} brouillons non publiés de ce package, dont {{count}} qui ne fait pas partie de cette modification.", - undoConfirm_many: "Annuler supprime les {{total}} brouillons non publiés de ce package, dont {{count}} de brouillons qui ne font pas partie de cette modification.", - undoConfirm_other: "Annuler supprime les {{total}} brouillons non publiés de ce package, dont {{count}} qui ne font pas partie de cette modification.", - undoConfirmUnknown: "Annuler supprime tous les brouillons non publiés de ce package, pas seulement cette modification.", - undoConfirmAction: "Tout annuler", - undoCancel: "Conserver", - undoing: "Annulation…", - undone: "Annulé", - undoFailed: "Échec de l'annulation", - kind: { - field: "Champ", - object: "Objet", - view: "Vue", - dashboard: "Tableau de bord", - app: "Application", - seed: "Données d'exemple", - package: "Package d'application", - }, }, }, chatbotError: { diff --git a/ui/packages/i18n/src/locales/ja.ts b/ui/packages/i18n/src/locales/ja.ts index d25d1b388f8..7d0b5016a98 100644 --- a/ui/packages/i18n/src/locales/ja.ts +++ b/ui/packages/i18n/src/locales/ja.ts @@ -2207,23 +2207,9 @@ const ja = { }, ai: { pendingDrafts: { - // objectstack#34610 — the line points to the shell's draft bar and shows a publish receipt. - publishFromBar: '未公開の変更が {{count}} 件あります。上部の下書きバーから公開してください。', - publishFromBar_one: '未公開の変更が {{count}} 件あります。上部の下書きバーから公開してください。', - publishFromBar_other: '未公開の変更が {{count}} 件あります。上部の下書きバーから公開してください。', - showDraftToPublish: '未公開の変更が {{count}} 件あります。下書きを表示して確認・公開してください。', - showDraftToPublish_one: '未公開の変更が {{count}} 件あります。下書きを表示して確認・公開してください。', - showDraftToPublish_other: '未公開の変更が {{count}} 件あります。下書きを表示して確認・公開してください。', - showDraft: '下書きを表示', - receipt: '公開しました。変更が反映されました。', - dismissReceipt: '閉じる', // {{detail}} はランタイムが返すメッセージ列なので、中間コロンは全角 // (exportFailed などと同じ。単一トークンの値なら半角)。 count: "未公開の変更が {{count}} 件あります — ユーザーには表示されません。", - publish: "公開", - published: "保留中の変更はすべて反映されています。", - failed: "公開に失敗しました。", - publishedWithFindings: "公開しましたが、ランタイムプローブが問題を報告しました:{{detail}}", }, usage: { title: "AI 使用状況", @@ -2249,31 +2235,6 @@ const ja = { share: "共有", shareTitle: "この会話を共有", shareDisabledTitle: "共有するにはチャットを開始してください", - buildDoctor: "ビルド診断", - buildDoctorTitle: "ビルド診断 — 実際に反映された内容は?", - buildDoctorDisabledTitle: "先にメッセージを送信してください", - buildDoctorDrawer: { - description: 'エージェントが主張した内容と、実際に反映されている内容の比較です。読み取り専用の診断です。', - reconciling: '照合中…', - notAvailable: '利用できません — 会話が見つからないか、アクセス権限がありません。', - untitled: '(無題)', - summary: '{{turns}} ターン · {{messages}} 件のメッセージ · {{tokens}} tok · LLM {{seconds}} 秒', - allLive: '試行した {{count}} 件の変更はすべて反映されています — 失われたものはありません。', - discrepancies: '{{count}} 件の不一致 — チャットの内容と実際に反映されている内容が一致しません。', - orphanedTitle: '提案されたが適用されていない', - orphanedHint: 'エージェントが提案した確認カードが、その後どのターンでも適用されず、変更が暗黙のうちに失われました。', - missingTitle: '適用済みとされたが見つからない', - missingHint: 'ツールの結果は適用済みとしていますが、成果物は sys_metadata に反映されていません。', - toolErrorsTitle: 'ツールエラー', - toolErrorsHint: 'ビルド中にエラーを返したツール呼び出しです。', - verifyTitle: 'ビルドチェック(verify_build)', - yourApp: 'あなたのアプリ:', - noIssues: '問題 0 件', - issueCount: '問題 {{count}} 件', - platformNoise: 'プラットフォームの sys_* 検出 {{count}} 件を非表示', - pendingActions: '保留中のアクション', - timeline: 'タイムライン({{count}})', - }, newChat: "新規", searchChats: "チャットを検索…", noChatsYet: "チャットはまだありません", @@ -2295,29 +2256,15 @@ const ja = { liveCanvasLive: "ライブアプリ — {{app}}", loadingAgents: "エージェントを読み込んでいます…", askAnything: "何でも質問してください…", - askOrChangeApp: "データについて質問するか、このアプリの変更を依頼…", - describeAppToBuild: "作りたいアプリ、または変更したい点を入力…", emptyTitle: "会話を始める", emptyDescription: "何でも質問してください — アシスタントは現在のアプリのコンテキストを参照できます。", switchAssistant: "アシスタントを切り替え", chooseAgent: "アシスタントを選択…", empty: { - build: { - title: "AI でビルド", - description: "アプリを普通の言葉で説明してください — オブジェクト、画面、サンプルデータを下書きしますので、確認して公開してください。", - }, ask: { title: "データに質問", description: "レコードについて質問してください — アクセスできるデータの件数、一覧、要約をお答えします。", }, - editApp: { - title: "「{{app}}」を編集中", - titleGeneric: "このアプリを編集", - description: "何を変更しますか?このアプリをその場で変更します — 項目、オブジェクト、ビュー、ダッシュボードの追加や、既存部分の調整ができます。", - // objectstack#34608 — the builder's empty state names both halves: data questions and changes. - askOrChangeDescription: - "このアプリのデータについて質問するか(件数、一覧、要約)、変更したい点を伝えてください。項目、オブジェクト、ビュー、ダッシュボードをその場で変更します。", - }, }, clearConversation: "クリア", sendHint: "で送信", @@ -2329,9 +2276,6 @@ const ja = { toolFailed: "失敗", toolDetailsHidden: "このビューではツールの入力と生の結果は非表示です。", toolDenyReason: "オペレーターがチャットで却下しました", - builderHandoffTitle: "ビルダーで構築する", - builderHandoffOpen: "ビルダーで開く →", - builderHandoffSuperseded: "より新しいリクエストがあります", recordWriteCreateTitle: "{{object}}を新規作成", recordWriteUpdateTitle: "{{object}}を変更", recordWriteConfirm: "確認", @@ -2378,32 +2322,17 @@ const ja = { stopResponse: "応答を停止", trace: "トレース", viewTrace: "トレースを表示", - nextSteps: "次のステップ", - publishDrafts: "公開", - publishOk: "公開しました — オブジェクトが有効になりました。", - seedWarn: "公開しましたが、一部のサンプルデータを読み込めませんでした。", - openBuiltApp: "アプリを開く", - viewBuiltAppInStudio: "Studio で表示", - previewDraft: "プレビュー", previewApp: "アプリをプレビュー", resizeSplit: "チャットとプレビューのサイズを変更", hideChats: "チャットを隠す", showChats: "チャットを表示", - planTitle: "提案されたプラン", - planQuestions: "ビルド前に確認", - planAssumptions: "前提", - planApproveHint: "返信してこのプランを承認または調整してください。", - planApprove: "ビルドする", - planAdjust: "調整", justNow: "たった今", minutesAgo: "{{count}} 分前", hoursAgo: "{{count}} 時間前", daysAgo: "{{count}} 日前", agentLabels: { ask: "質問", - build: "ビルド", dataChat: "アシスタント", - metadataAssistant: "メタデータアシスタント", }, suggestions: { dataChat: { @@ -2411,51 +2340,12 @@ const ja = { recentRecords: "最近作成されたレコードを 5 件表示してください。", recordCounts: "オブジェクトごとのレコード数を数えてください。", }, - // cloud#1984 — these five chips are the maker's own recommendations, so - // they may only ask for what ADR-0112 v1 BUILDS: objects, fields, views - // (grid/kanban/calendar/gallery), pages, dashboards and sample data. No - // wording that promises autonomous behaviour (alert / remind / notify / - // automate / status workflow) — v1 has no flows, actions or schedules, and - // the model silently degrades such a request into a board or a filtered - // view, so the chip would promise an alert and deliver a page. REVERT to - // the automation wording when ADR-0112 v2 re-adds flows and actions. - metadataAssistant: { - buildCrm: "営業 CRM を作って — 顧客、担当者、ステージ項目つきの商談、ステージ別に金額を集計するダッシュボード。", - buildApp: "プロジェクト管理を作って — プロジェクト、担当者と期日つきのタスク、ステータス別ボード、期日のカレンダー。", - buildFlow: "サポートデスクを設計して — 優先度とステータスの項目を持つチケット、ステータス別ボード、顧客との紐付け。", - buildInventory: "在庫管理アプリを作って — 商品、在庫数、仕入先、発注点を下回る商品を絞り込むビュー。", - buildRecruiting: "採用管理を作って — 候補者、募集職種、面接ステージ項目、ステージ別ボード。", - }, generic: { help: "どんなことを手伝ってもらえますか?", availableObjects: "利用できるデータオブジェクトを一覧にしてください。", recentActivity: "最近の自分の活動を要約してください。", }, - // objectui#7709 — the edit-mode starters, shown when the maker is bound - // to an EXISTING app (`?package=`). Same rule as the five above: they - // may only ask for what ADR-0112 v1 BUILDS. The fourth chip used to be - // `addAutomation` ("an approval, a status flow, or a notification") and - // every capability it named is refused by v1 (cloud#1956 / PR #1970), so - // it now asks for sample data — `seed` IS on v1's whitelist, and having - // no data is what an existing app most often lacks. REVERT: when - // ADR-0112 v2 re-adds flows and actions, THIS chip's automation wording - // comes back as `addAutomation`; the retired string is pinned for every - // pack in `packages/i18n/src/__tests__/makerEditChips-v1-scope-7709.test.ts`. - editApp: { - addField: "いずれかのオブジェクトに項目を追加してください。", - addObject: "新しいオブジェクトを追加し、既存のものと関連づけてください。", - addDashboard: "主要指標のダッシュボードを追加してください。", - addSampleData: "既存のオブジェクトに、デモで使えるリアルなサンプルデータを入れてください。", - }, }, - changesTitle: "変更の確認", - changesConfirmed: "確認済み", - changesConfirm: "変更を確定", - changesConfirmHint: "返信してこの変更を確定または調整してください。", - changesApplying: "適用中…", - changesApplied: "適用済み", - changesDrafted: "下書きとして保存", - changesFailed: "未適用", discussing: "表示中: {{target}}", focus: { pin: "このレコードについて質問し続ける", @@ -2465,47 +2355,15 @@ const ja = { switchAccept: "切り替える", switchDecline: "このまま", }, - changeVerb: { - createObject: "オブジェクトを作成", - addField: "項目を追加", - modifyField: "項目を変更", - deleteField: "項目を削除", - createMetadata: "作成", - updateMetadata: "変更", - createSeed: "サンプルデータを生成", - createPackage: "アプリパッケージを作成", - }, // objectui#3546 slice four — the AI console surfaces: the /ai chat page's app switcher, // connection banner and plan/publish cards, the ChatDock chrome, and the // conversation-list date buckets. `group.*` is the template-key family // `console.ai.group.${key}` (ConversationsSidebar), enumerated from the // ConversationGroupKey union — all five members, no wildcard. collapseToDock: "サイドパネルに収める", - switchApp: "アプリを切り替え", - switchAppLabel: "アプリ別のビルド会話", - newApp: "新しいアプリ", connectionWaiting: "サーバーを待っています…", connectionStalled: "まだ処理しています…", connectionOffline: "接続が切断されました — 再接続しています…", - designingPlan: "アプリを設計しています…", - designingPlanHint: { - data: "追跡するデータを整理しています…", - objects: "オブジェクトとそのフィールドを形にしています…", - relations: "関連レコードを接続しています…", - lookups: "リレーションと参照フィールドを設定しています…", - views: "画面とビューを計画しています…", - forms: "フォームとリストを配置しています…", - defaults: "妥当な既定値と検証を追加しています…", - dashboard: "追跡用のダッシュボードを描いています…", - review: "構造全体に矛盾がないか再確認しています…", - finalize: "プランをまとめています…", - }, - planBuilding: "ビルド中…", - planBuilt: "ビルド済み", - planDeferred: "まだビルドされていません", - planReady: "プランの準備ができました。今すぐビルドするか、調整したい点を教えてください。", - published: "公開しました", - publishFailed: "公開に失敗しました", unavailableTitle: "AI アシスタントを利用できません", unavailableDescription: "このデプロイでは AI アシスタントが有効になっていません。それ以外の機能は通常どおり動作します。", unavailableError: "AI サービスに接続できませんでした。一時的にオフラインの可能性があります — 再試行するか、ホームに戻ってください。", @@ -4514,18 +4372,6 @@ const ja = { derivedAiAccess: 'AI アクセスが有効', }, }, - excelImport: { - noImportableFields: "そのオブジェクトにはインポート可能なフィールドがありません。", - schemaReadFailed: "オブジェクトのスキーマを読み取れませんでした。", - imported: "{{count}} 行を {{object}} にインポートしました。", - imported_one: "{{count}} 行を {{object}} にインポートしました。", - imported_other: "{{count}} 行を {{object}} にインポートしました。", - importFrom: "実データのインポート元", - into: "→", - opening: "開いています…", - importAction: "インポート", - dismiss: "閉じる", - }, cloudWorkspaceTimezoneNotice: { seeded: "環境のタイムゾーンは、作成時にブラウザーに合わせて {{zone}} に設定されました。「設定 → ローカリゼーション」で変更できます。", }, @@ -4750,122 +4596,17 @@ const ja = { failed: "失敗", }, phase: { - build: "構築", - design: "プランの設計", stepCount: "{{count}} ステップ", stepCount_one: "{{count}} ステップ", stepCount_other: "{{count}} ステップ", expand: "ステップを表示", collapse: "ステップを隠す", }, - plan: { - countObjects: "{{count}} 件のオブジェクト", - countObjects_one: "{{count}} 件のオブジェクト", - countObjects_other: "{{count}} 件のオブジェクト", - countViews: "{{count}} 件のビュー", - countViews_one: "{{count}} 件のビュー", - countViews_other: "{{count}} 件のビュー", - countDashboards: "{{count}} 件のダッシュボード", - countDashboards_one: "{{count}} 件のダッシュボード", - countDashboards_other: "{{count}} 件のダッシュボード", - countSeedData: "サンプルデータ", - extendTarget: "既存のアプリに追加:{{app}}", - awaitingConfirm: "確認待ち", - // objectstack#32984 — the plan card's build states. - confirmed: "確認済み", - buildFailed: "構築されませんでした · 何も作成されていません", - iterateOrNew: { - question: "このプランは既存のアプリ「{{app}}」と重なっています。このアプリを引き続き改善しますか、それとも別のアプリを作成しますか?", - questionUnnamed: "このプランは既存のアプリと重なっています。そのアプリを引き続き改善しますか、それとも別のアプリを作成しますか?", - extend: "「{{app}}」を引き続き改善", - buildNew: "別のアプリを作成", - replyHint: "どちらにするか返信してください。", - }, - objectsAndFields: "オブジェクトとフィールド", - views: "ビュー", - suggestedField: "追加提案", - suggestedFieldLegend: "「{{mark}}」が付いたフィールドは AI が追加したもので、ご依頼にはありません。", - nameField: "名前:{{field}}", - }, build: { - building: "{{app}}を構築しています…", - built: "{{app}}を構築しました", - builtAndLive: "構築して公開済み · {{app}}", - appFallback: "アプリ", - addingSampleData: "サンプルデータを追加中", - group: { - object: "オブジェクト", - view: "ビュー", - dashboard: "ダッシュボード", - app: "アプリ", - seed: "サンプルデータ", - dataset: "データセット", - permission: "権限", - other: "その他", - }, - moreArtifacts: "他 {{n}} 件", - verifying: "変更を確認しています…", - verifyStep: "ステップ {{n}}", - verified: "変更を確認しました", - // objectstack#32984 — the build card's issues line, in the customer's words. - issuesCount: "要修正 {{count}} 件", issuesSummary: "この構築には、使えるようになる前に修正が必要な部分があります。「問題を修正して」と返信すると、アシスタントが修正します。", - warningsSummary: "アプリは構築済みですが、確認したほうがよい点がいくつかあります。改善したい場合は、アシスタントに内容を尋ねてください。", - issuesDetails: "技術的な詳細", - // objectstack#32984 — the published draft badge's failed-item count, which was English in every locale. - needsAttention: "要確認 {{count}} 件", - needsAttention_one: "要確認 {{count}} 件", - needsAttention_other: "要確認 {{count}} 件", health: { - sampleRowsLive: "サンプルデータ {{count}} 件を公開済み", - sampleRowsLive_one: "サンプルデータ {{count}} 件を公開済み", - sampleRowsLive_other: "サンプルデータ {{count}} 件を公開済み", - views: "{{count}} 件のビュー", - views_one: "{{count}} 件のビュー", - views_other: "{{count}} 件のビュー", - widgets: "{{count}} 件のウィジェット", - widgets_one: "{{count}} 件のウィジェット", - widgets_other: "{{count}} 件のウィジェット", - seeds: "{{count}} 件のサンプルデータセット", - seeds_one: "{{count}} 件のサンプルデータセット", - seeds_other: "{{count}} 件のサンプルデータセット", - verified: "{{checks}} を確認済み", seedFailed: "サンプルデータを読み込めませんでした。", }, - unknownPhase: "不明なビルドフェーズ", - nextStepsLead: "次はこう話しかけられます:{{steps}}", - nextStepQuote: "「{{step}}」", - draftPosture: "以降の変更は下書きとして保存され、このチャットの「公開」で公開します。", - checksPassed: "照合済み {{passed}}/{{total}}", - }, - changes: { - planTitle: "変更案 · {{count}} 件", - planTitle_one: "変更案 · {{count}} 件", - planTitle_other: "変更案 · {{count}} 件", - saveDraft: "下書きとして保存", - reviewAndPublish: "変更を確認して公開", - undo: "取り消す", - undoWithOthers: "取り消す(ほかの下書き {{count}} 件も含む)", - undoWithOthers_one: "取り消す(ほかの下書き {{count}} 件も含む)", - undoWithOthers_other: "取り消す(ほかの下書き {{count}} 件も含む)", - undoConfirm: "取り消すと、このアプリパッケージの未公開の下書き {{total}} 件がすべて破棄されます。うち {{count}} 件は今回の変更ではありません。", - undoConfirm_one: "取り消すと、このアプリパッケージの未公開の下書き {{total}} 件がすべて破棄されます。うち {{count}} 件は今回の変更ではありません。", - undoConfirm_other: "取り消すと、このアプリパッケージの未公開の下書き {{total}} 件がすべて破棄されます。うち {{count}} 件は今回の変更ではありません。", - undoConfirmUnknown: "取り消すと、今回の変更だけでなく、このアプリパッケージの未公開の下書きがすべて破棄されます。", - undoConfirmAction: "すべて取り消す", - undoCancel: "キャンセル", - undoing: "取り消し中…", - undone: "取り消しました", - undoFailed: "取り消せませんでした", - kind: { - field: "フィールド", - object: "オブジェクト", - view: "ビュー", - dashboard: "ダッシュボード", - app: "アプリ", - seed: "サンプルデータ", - package: "アプリパッケージ", - }, }, }, chatbotError: { diff --git a/ui/packages/i18n/src/locales/ko.ts b/ui/packages/i18n/src/locales/ko.ts index 3aae4350d8c..7a0eec5dd46 100644 --- a/ui/packages/i18n/src/locales/ko.ts +++ b/ui/packages/i18n/src/locales/ko.ts @@ -2207,21 +2207,7 @@ const ko = { }, ai: { pendingDrafts: { - // objectstack#34610 — the line points to the shell's draft bar and shows a publish receipt. - publishFromBar: '게시되지 않은 변경이 {{count}}개 있습니다. 상단의 초안 표시줄에서 게시하세요.', - publishFromBar_one: '게시되지 않은 변경이 {{count}}개 있습니다. 상단의 초안 표시줄에서 게시하세요.', - publishFromBar_other: '게시되지 않은 변경이 {{count}}개 있습니다. 상단의 초안 표시줄에서 게시하세요.', - showDraftToPublish: '게시되지 않은 변경이 {{count}}개 있습니다. 초안을 열어 검토하고 게시하세요.', - showDraftToPublish_one: '게시되지 않은 변경이 {{count}}개 있습니다. 초안을 열어 검토하고 게시하세요.', - showDraftToPublish_other: '게시되지 않은 변경이 {{count}}개 있습니다. 초안을 열어 검토하고 게시하세요.', - showDraft: '초안 보기', - receipt: '게시했습니다. 변경 사항이 반영되었습니다.', - dismissReceipt: '닫기', count: "게시되지 않은 변경이 {{count}}건 있습니다 — 사용자에게는 보이지 않습니다.", - publish: "게시", - published: "대기 중인 변경 사항이 모두 반영되었습니다.", - failed: "게시에 실패했습니다.", - publishedWithFindings: "게시했지만 런타임 프로브에서 문제가 보고되었습니다: {{detail}}", }, usage: { title: "AI 사용량", @@ -2247,31 +2233,6 @@ const ko = { share: "공유", shareTitle: "이 대화 공유", shareDisabledTitle: "공유하려면 먼저 대화를 시작하세요", - buildDoctor: "빌드 진단", - buildDoctorTitle: "빌드 진단 — 실제로 반영된 내용은?", - buildDoctorDisabledTitle: "먼저 메시지를 보내세요", - buildDoctorDrawer: { - description: '에이전트가 주장한 내용과 실제로 반영된 내용을 비교합니다. 읽기 전용 진단입니다.', - reconciling: '대조 중…', - notAvailable: '사용할 수 없음 — 대화를 찾을 수 없거나 접근 권한이 없습니다.', - untitled: '(제목 없음)', - summary: '{{turns}}턴 · 메시지 {{messages}}개 · {{tokens}} tok · LLM {{seconds}}초', - allLive: '시도한 변경 {{count}}개가 모두 반영되었습니다 — 사라진 것은 없습니다.', - discrepancies: '불일치 {{count}}건 — 채팅에서 말한 내용과 실제로 반영된 내용이 다릅니다.', - orphanedTitle: '제안되었지만 적용되지 않음', - orphanedHint: '에이전트가 제안한 확인 카드를 이후 어떤 턴에서도 적용하지 않아 변경이 조용히 사라졌습니다.', - missingTitle: '적용되었다고 했지만 없음', - missingHint: '도구 결과는 적용되었다고 했지만 아티팩트가 sys_metadata에 반영되어 있지 않습니다.', - toolErrorsTitle: '도구 오류', - toolErrorsHint: '빌드 중 오류를 반환한 도구 호출입니다.', - verifyTitle: '빌드 검사 (verify_build)', - yourApp: '내 앱:', - noIssues: '문제 0개', - issueCount: '문제 {{count}}개', - platformNoise: '플랫폼 sys_* 발견 {{count}}건 숨김', - pendingActions: '대기 중인 작업', - timeline: '타임라인 ({{count}})', - }, newChat: "새로 만들기", searchChats: "채팅 검색…", noChatsYet: "아직 채팅이 없습니다", @@ -2293,29 +2254,15 @@ const ko = { liveCanvasLive: "실시간 앱 — {{app}}", loadingAgents: "에이전트를 불러오는 중…", askAnything: "무엇이든 물어보세요…", - askOrChangeApp: "데이터에 대해 묻거나 이 앱을 바꿔 달라고 요청하세요…", - describeAppToBuild: "만들고 싶은 앱이나 바꿀 부분을 설명하세요…", emptyTitle: "대화 시작하기", emptyDescription: "무엇이든 물어보세요 — 어시스턴트는 현재 앱 컨텍스트에 접근할 수 있습니다.", switchAssistant: "어시스턴트 전환", chooseAgent: "어시스턴트 선택…", empty: { - build: { - title: "AI로 빌드", - description: "앱을 일상 언어로 설명해 주세요 — 객체, 화면, 샘플 데이터를 초안으로 만들어 드리면 검토 후 게시하시면 됩니다.", - }, ask: { title: "데이터에 질문하기", description: "레코드에 대해 질문하세요 — 접근 가능한 데이터의 개수, 목록, 요약을 알려 드립니다.", }, - editApp: { - title: "“{{app}}” 편집 중", - titleGeneric: "이 앱 편집", - description: "무엇을 바꿀까요? 이 앱을 그 자리에서 수정합니다 — 필드, 객체, 뷰, 대시보드를 추가하거나 기존 내용을 조정할 수 있습니다.", - // objectstack#34608 — the builder's empty state names both halves: data questions and changes. - askOrChangeDescription: - "이 앱의 데이터(건수, 목록, 요약)를 물어보거나 바꿀 점을 알려 주세요. 필드, 개체, 뷰, 대시보드를 그 자리에서 수정합니다.", - }, }, clearConversation: "지우기", sendHint: "눌러 전송", @@ -2327,9 +2274,6 @@ const ko = { toolFailed: "실패", toolDetailsHidden: "이 보기에서는 도구 입력과 원본 결과가 숨겨집니다.", toolDenyReason: "운영자가 채팅에서 거부함", - builderHandoffTitle: "빌더에서 만들기", - builderHandoffOpen: "빌더에서 열기 →", - builderHandoffSuperseded: "더 최근의 요청이 있습니다", recordWriteCreateTitle: "{{object}} 새로 만들기", recordWriteUpdateTitle: "{{object}} 변경", recordWriteConfirm: "확인", @@ -2376,32 +2320,17 @@ const ko = { stopResponse: "응답 중지", trace: "추적", viewTrace: "추적 보기", - nextSteps: "다음 단계", - publishDrafts: "게시", - publishOk: "게시했습니다 — 객체가 이제 활성화되었습니다.", - seedWarn: "게시했지만 일부 샘플 데이터를 불러오지 못했습니다.", - openBuiltApp: "앱 열기", - viewBuiltAppInStudio: "Studio에서 보기", - previewDraft: "미리보기", previewApp: "앱 미리보기", resizeSplit: "채팅과 미리보기 크기 조정", hideChats: "채팅 숨기기", showChats: "채팅 표시", - planTitle: "제안된 계획", - planQuestions: "빌드 전에 확인", - planAssumptions: "가정", - planApproveHint: "회신하여 이 계획을 승인하거나 조정하세요.", - planApprove: "빌드하기", - planAdjust: "조정", justNow: "방금", minutesAgo: "{{count}}분 전", hoursAgo: "{{count}}시간 전", daysAgo: "{{count}}일 전", agentLabels: { ask: "질문", - build: "빌드", dataChat: "어시스턴트", - metadataAssistant: "메타데이터 어시스턴트", }, suggestions: { dataChat: { @@ -2409,51 +2338,12 @@ const ko = { recentRecords: "가장 최근에 생성된 레코드 5건을 보여 주세요.", recordCounts: "객체별 레코드 수를 세어 주세요.", }, - // cloud#1984 — these five chips are the maker's own recommendations, so - // they may only ask for what ADR-0112 v1 BUILDS: objects, fields, views - // (grid/kanban/calendar/gallery), pages, dashboards and sample data. No - // wording that promises autonomous behaviour (alert / remind / notify / - // automate / status workflow) — v1 has no flows, actions or schedules, and - // the model silently degrades such a request into a board or a filtered - // view, so the chip would promise an alert and deliver a page. REVERT to - // the automation wording when ADR-0112 v2 re-adds flows and actions. - metadataAssistant: { - buildCrm: "영업 CRM을 만들어 줘 — 고객, 담당자, 단계 필드가 있는 거래, 단계별 금액을 합산하는 대시보드.", - buildApp: "프로젝트 트래커를 만들어 줘 — 프로젝트, 담당자와 마감일이 있는 작업, 상태별 보드, 마감일 캘린더.", - buildFlow: "고객 지원 데스크를 설계해 줘 — 우선순위와 상태 필드가 있는 티켓, 상태별 보드, 고객 연결.", - buildInventory: "재고 앱을 만들어 줘 — 제품, 재고 수량, 공급업체, 재주문점 미만 제품을 걸러내는 뷰.", - buildRecruiting: "채용 트래커를 만들어 줘 — 지원자, 채용 중인 직무, 면접 단계 필드, 단계별 보드.", - }, generic: { help: "무엇을 도와줄 수 있나요?", availableObjects: "사용 가능한 데이터 객체를 나열해 주세요.", recentActivity: "내 최근 활동을 요약해 주세요.", }, - // objectui#7709 — the edit-mode starters, shown when the maker is bound - // to an EXISTING app (`?package=`). Same rule as the five above: they - // may only ask for what ADR-0112 v1 BUILDS. The fourth chip used to be - // `addAutomation` ("an approval, a status flow, or a notification") and - // every capability it named is refused by v1 (cloud#1956 / PR #1970), so - // it now asks for sample data — `seed` IS on v1's whitelist, and having - // no data is what an existing app most often lacks. REVERT: when - // ADR-0112 v2 re-adds flows and actions, THIS chip's automation wording - // comes back as `addAutomation`; the retired string is pinned for every - // pack in `packages/i18n/src/__tests__/makerEditChips-v1-scope-7709.test.ts`. - editApp: { - addField: "객체 중 하나에 필드를 추가해 주세요.", - addObject: "새 객체를 추가하고 기존 객체와 연결해 주세요.", - addDashboard: "핵심 지표를 위한 대시보드를 추가해 주세요.", - addSampleData: "기존 객체에 데모에서 보여 줄 만한 현실적인 샘플 데이터를 채워 주세요.", - }, }, - changesTitle: "변경 확인", - changesConfirmed: "확인됨", - changesConfirm: "변경 확정", - changesConfirmHint: "회신하여 이 변경을 확정하거나 조정하세요.", - changesApplying: "적용 중…", - changesApplied: "적용됨", - changesDrafted: "초안으로 저장됨", - changesFailed: "적용되지 않음", discussing: "보는 중: {{target}}", focus: { pin: "이 레코드에 대해 계속 질문", @@ -2463,47 +2353,15 @@ const ko = { switchAccept: "전환", switchDecline: "유지", }, - changeVerb: { - createObject: "객체 생성", - addField: "필드 추가", - modifyField: "필드 수정", - deleteField: "필드 삭제", - createMetadata: "생성", - updateMetadata: "수정", - createSeed: "샘플 데이터 생성", - createPackage: "앱 패키지 생성", - }, // objectui#3546 slice four — the AI console surfaces: the /ai chat page's app switcher, // connection banner and plan/publish cards, the ChatDock chrome, and the // conversation-list date buckets. `group.*` is the template-key family // `console.ai.group.${key}` (ConversationsSidebar), enumerated from the // ConversationGroupKey union — all five members, no wildcard. collapseToDock: "사이드 패널로 접기", - switchApp: "앱 전환", - switchAppLabel: "앱별 빌드 대화", - newApp: "새 앱", connectionWaiting: "서버를 기다리는 중…", connectionStalled: "계속 처리하는 중…", connectionOffline: "연결이 끊어졌습니다 — 다시 연결하는 중…", - designingPlan: "앱을 설계하는 중…", - designingPlanHint: { - data: "추적할 데이터를 정리하는 중…", - objects: "객체와 필드를 구성하는 중…", - relations: "관련 레코드를 연결하는 중…", - lookups: "관계와 조회 필드를 설정하는 중…", - views: "화면과 뷰를 계획하는 중…", - forms: "양식과 목록을 배치하는 중…", - defaults: "합리적인 기본값과 검증을 추가하는 중…", - dashboard: "추적용 대시보드를 스케치하는 중…", - review: "구조가 잘 맞물리는지 다시 확인하는 중…", - finalize: "계획을 정리하는 중…", - }, - planBuilding: "빌드 중…", - planBuilt: "빌드 완료", - planDeferred: "아직 빌드하지 않음", - planReady: "계획이 준비되었습니다. 지금 빌드하거나 조정할 부분을 알려주세요.", - published: "게시했습니다", - publishFailed: "게시에 실패했습니다", unavailableTitle: "AI 어시스턴트를 사용할 수 없습니다", unavailableDescription: "이 배포에는 AI 어시스턴트가 활성화되어 있지 않습니다. 나머지 기능은 정상적으로 작동합니다.", unavailableError: "AI 서비스에 연결할 수 없습니다. 일시적으로 오프라인일 수 있습니다 — 다시 시도하거나 홈으로 돌아가세요.", @@ -4511,18 +4369,6 @@ const ko = { derivedAiAccess: 'AI 액세스 켜짐', }, }, - excelImport: { - noImportableFields: "해당 오브젝트에는 가져올 수 있는 필드가 없습니다.", - schemaReadFailed: "오브젝트 스키마를 읽을 수 없습니다.", - imported: "{{count}}개 행을 {{object}}(으)로 가져왔습니다.", - imported_one: "{{count}}개 행을 {{object}}(으)로 가져왔습니다.", - imported_other: "{{count}}개 행을 {{object}}(으)로 가져왔습니다.", - importFrom: "실제 데이터 가져오기 원본", - into: "→", - opening: "여는 중…", - importAction: "가져오기", - dismiss: "닫기", - }, cloudWorkspaceTimezoneNotice: { seeded: "환경 시간대는 생성 시 브라우저에 맞춰 {{zone}}(으)로 설정되었습니다. 설정 → 현지화에서 변경할 수 있습니다.", }, @@ -4747,122 +4593,17 @@ const ko = { failed: "실패", }, phase: { - build: "빌드", - design: "계획 설계", stepCount: "{{count}}단계", stepCount_one: "{{count}}단계", stepCount_other: "{{count}}단계", expand: "단계 보기", collapse: "단계 숨기기", }, - plan: { - countObjects: "오브젝트 {{count}}개", - countObjects_one: "오브젝트 {{count}}개", - countObjects_other: "오브젝트 {{count}}개", - countViews: "뷰 {{count}}개", - countViews_one: "뷰 {{count}}개", - countViews_other: "뷰 {{count}}개", - countDashboards: "대시보드 {{count}}개", - countDashboards_one: "대시보드 {{count}}개", - countDashboards_other: "대시보드 {{count}}개", - countSeedData: "샘플 데이터", - extendTarget: "기존 앱에 추가: {{app}}", - awaitingConfirm: "확인 대기 중", - // objectstack#32984 — the plan card's build states. - confirmed: "확인됨", - buildFailed: "빌드되지 않음 · 아무것도 생성되지 않았습니다", - iterateOrNew: { - question: "이 계획은 이미 있는 앱 “{{app}}”과(와) 겹칩니다. 이 앱을 계속 개선할까요, 아니면 별도의 앱을 만들까요?", - questionUnnamed: "이 계획은 이미 있는 앱과 겹칩니다. 그 앱을 계속 개선할까요, 아니면 별도의 앱을 만들까요?", - extend: "“{{app}}” 계속 개선", - buildNew: "별도의 앱 만들기", - replyHint: "어느 쪽인지 회신해 주세요.", - }, - objectsAndFields: "개체 및 필드", - views: "뷰", - suggestedField: "추가 제안", - suggestedFieldLegend: "'{{mark}}' 표시가 있는 필드는 AI가 추가한 것으로, 요청하지 않은 필드입니다.", - nameField: "이름: {{field}}", - }, build: { - building: "{{app}} 빌드 중…", - built: "{{app}} 빌드 완료", - builtAndLive: "빌드 및 게시 완료 · {{app}}", - appFallback: "앱", - addingSampleData: "샘플 데이터 추가 중", - group: { - object: "오브젝트", - view: "뷰", - dashboard: "대시보드", - app: "앱", - seed: "샘플 데이터", - dataset: "데이터 세트", - permission: "권한", - other: "기타", - }, - moreArtifacts: "외 {{n}}개", - verifying: "변경 사항 확인 중…", - verifyStep: "{{n}}단계", - verified: "변경 사항 확인 완료", - // objectstack#32984 — the build card's issues line, in the customer's words. - issuesCount: "수정 필요 {{count}}건", issuesSummary: "이번 빌드에는 사용하기 전에 수정해야 할 부분이 있습니다. \"문제를 수정해 줘\"라고 답하면 어시스턴트가 수정합니다.", - warningsSummary: "앱이 빌드되었지만 확인해 볼 만한 부분이 몇 가지 있습니다. 개선하고 싶다면 어시스턴트에게 무엇인지 물어보세요.", - issuesDetails: "기술 세부 정보", - // objectstack#32984 — the published draft badge's failed-item count, which was English in every locale. - needsAttention: "확인 필요 {{count}}건", - needsAttention_one: "확인 필요 {{count}}건", - needsAttention_other: "확인 필요 {{count}}건", health: { - sampleRowsLive: "샘플 데이터 {{count}}건 게시됨", - sampleRowsLive_one: "샘플 데이터 {{count}}건 게시됨", - sampleRowsLive_other: "샘플 데이터 {{count}}건 게시됨", - views: "뷰 {{count}}개", - views_one: "뷰 {{count}}개", - views_other: "뷰 {{count}}개", - widgets: "위젯 {{count}}개", - widgets_one: "위젯 {{count}}개", - widgets_other: "위젯 {{count}}개", - seeds: "샘플 데이터 세트 {{count}}개", - seeds_one: "샘플 데이터 세트 {{count}}개", - seeds_other: "샘플 데이터 세트 {{count}}개", - verified: "{{checks}} 확인 완료", seedFailed: "샘플 데이터를 불러오지 못했습니다.", }, - unknownPhase: "알 수 없는 빌드 단계", - nextStepsLead: "다음으로 이렇게 말할 수 있습니다: {{steps}}", - nextStepQuote: "“{{step}}”", - draftPosture: "이후 변경 사항은 초안으로 저장되며, 이 채팅의 「게시」로 게시합니다.", - checksPassed: "검증 통과 {{passed}}/{{total}}", - }, - changes: { - planTitle: "변경안 · {{count}}개", - planTitle_one: "변경안 · {{count}}개", - planTitle_other: "변경안 · {{count}}개", - saveDraft: "초안으로 저장", - reviewAndPublish: "변경 사항 확인 후 게시", - undo: "되돌리기", - undoWithOthers: "되돌리기(다른 초안 {{count}}개 포함)", - undoWithOthers_one: "되돌리기(다른 초안 {{count}}개 포함)", - undoWithOthers_other: "되돌리기(다른 초안 {{count}}개 포함)", - undoConfirm: "되돌리면 이 앱 패키지의 게시되지 않은 초안 {{total}}개가 모두 폐기되며, 그중 {{count}}개는 이번 변경이 아닙니다.", - undoConfirm_one: "되돌리면 이 앱 패키지의 게시되지 않은 초안 {{total}}개가 모두 폐기되며, 그중 {{count}}개는 이번 변경이 아닙니다.", - undoConfirm_other: "되돌리면 이 앱 패키지의 게시되지 않은 초안 {{total}}개가 모두 폐기되며, 그중 {{count}}개는 이번 변경이 아닙니다.", - undoConfirmUnknown: "되돌리면 이번 변경뿐 아니라 이 앱 패키지의 게시되지 않은 초안이 모두 폐기됩니다.", - undoConfirmAction: "모두 되돌리기", - undoCancel: "취소", - undoing: "되돌리는 중…", - undone: "되돌림", - undoFailed: "되돌리지 못했습니다", - kind: { - field: "필드", - object: "오브젝트", - view: "뷰", - dashboard: "대시보드", - app: "앱", - seed: "샘플 데이터", - package: "앱 패키지", - }, }, }, chatbotError: { diff --git a/ui/packages/i18n/src/locales/pt-BR.ts b/ui/packages/i18n/src/locales/pt-BR.ts index cb9e0a0ab6c..b0fab43cdec 100644 --- a/ui/packages/i18n/src/locales/pt-BR.ts +++ b/ui/packages/i18n/src/locales/pt-BR.ts @@ -2264,23 +2264,7 @@ const pt = { }, ai: { pendingDrafts: { - // objectstack#34610 — the line points to the shell's draft bar and shows a publish receipt. - publishFromBar: '{{count}} alterações não publicadas. Publique-as na barra do rascunho no topo.', - publishFromBar_one: '{{count}} alteração não publicada. Publique-a na barra do rascunho no topo.', - publishFromBar_many: '{{count}} de alterações não publicadas. Publique-as na barra do rascunho no topo.', - publishFromBar_other: '{{count}} alterações não publicadas. Publique-as na barra do rascunho no topo.', - showDraftToPublish: '{{count}} alterações não publicadas. Mostre o rascunho para revisá-las e publicá-las.', - showDraftToPublish_one: '{{count}} alteração não publicada. Mostre o rascunho para revisá-la e publicá-la.', - showDraftToPublish_many: '{{count}} de alterações não publicadas. Mostre o rascunho para revisá-las e publicá-las.', - showDraftToPublish_other: '{{count}} alterações não publicadas. Mostre o rascunho para revisá-las e publicá-las.', - showDraft: 'Mostrar rascunho', - receipt: 'Publicado. Suas alterações estão no ar.', - dismissReceipt: 'Fechar', count: "{{count}} alteração(ões) ainda não publicada(s) — os usuários não conseguem vê-las.", - publish: "Publicar", - published: "Todas as alterações pendentes estão ativas.", - failed: "Falha ao publicar.", - publishedWithFindings: "Publicado, mas as verificações de tempo de execução relataram problemas: {{detail}}", }, usage: { title: "Uso de IA", @@ -2308,31 +2292,6 @@ const pt = { share: "Compartilhar", shareTitle: "Compartilhar esta conversa", shareDisabledTitle: "Comece a conversar para habilitar o compartilhamento", - buildDoctor: "Diagnóstico de build", - buildDoctorTitle: "Diagnóstico de build — o que foi realmente aplicado?", - buildDoctorDisabledTitle: "Envie uma mensagem primeiro", - buildDoctorDrawer: { - description: 'O que o agente afirmou versus o que está realmente ativo. Diagnóstico somente leitura.', - reconciling: 'Conciliando…', - notAvailable: 'Indisponível — a conversa não foi encontrada ou você não tem autorização.', - untitled: '(sem título)', - summary: '{{turns}} turno(s) · {{messages}} msgs · {{tokens}} tok · {{seconds}} s LLM', - allLive: 'Todas as {{count}} alteração(ões) tentada(s) estão ativas — nada se perdeu.', - discrepancies: '{{count}} discrepância(s) — o que o chat disse não corresponde ao que está ativo.', - orphanedTitle: 'Proposto, mas nunca aplicado', - orphanedHint: 'Um cartão de confirmação que o agente propôs, mas que nenhum turno posterior aplicou — a alteração se perdeu silenciosamente.', - missingTitle: 'Declarado, mas ausente', - missingHint: 'Um resultado de ferramenta disse que foi aplicado, mas o artefato não está ativo em sys_metadata.', - toolErrorsTitle: 'Erros de ferramentas', - toolErrorsHint: 'Chamadas de ferramentas que retornaram um erro durante o build.', - verifyTitle: 'Verificação do build (verify_build)', - yourApp: 'Seu aplicativo:', - noIssues: '0 problemas', - issueCount: '{{count}} problema(s)', - platformNoise: '{{count}} achado(s) sys_* da plataforma oculto(s)', - pendingActions: 'Ações pendentes', - timeline: 'Linha do tempo ({{count}})', - }, newChat: "Nova", searchChats: "Pesquisar conversas…", noChatsYet: "Ainda não há conversas", @@ -2354,29 +2313,15 @@ const pt = { liveCanvasLive: "Aplicativo ao vivo — {{app}}", loadingAgents: "Carregando agentes…", askAnything: "Pergunte qualquer coisa…", - askOrChangeApp: "Pergunte sobre seus dados ou peça para eu alterar este app…", - describeAppToBuild: "Descreva o app que você quer criar ou o que mudar…", emptyTitle: "Iniciar uma conversa", emptyDescription: "Pergunte qualquer coisa — o assistente tem acesso ao contexto do seu aplicativo atual.", switchAssistant: "Trocar de assistente", chooseAgent: "Escolher assistente…", empty: { - build: { - title: "Criar com IA", - description: "Descreva um aplicativo em linguagem simples — eu rascunho os objetos, telas e dados de exemplo, e então você revisa e publica.", - }, ask: { title: "Pergunte aos seus dados", description: "Faça perguntas sobre seus registros — contagens, listas e resumos dos dados a que você tem acesso.", }, - editApp: { - title: "Editando “{{app}}”", - titleGeneric: "Editar este aplicativo", - description: "O que você quer mudar? Eu altero este aplicativo no lugar — adicionar um campo, objeto, visão ou painel, ou ajustar o que já existe.", - // objectstack#34608 — the builder's empty state names both halves: data questions and changes. - askOrChangeDescription: - "Pergunte sobre os dados deste app — contagens, listas e resumos — ou diga o que mudar, e eu modifico o app na hora: um campo, um objeto, uma visualização ou um painel.", - }, }, clearConversation: "Limpar", sendHint: "para enviar", @@ -2388,9 +2333,6 @@ const pt = { toolFailed: "Falhou", toolDetailsHidden: "As entradas das ferramentas e os resultados brutos estão ocultos nesta visão.", toolDenyReason: "Rejeitado pelo operador no chat", - builderHandoffTitle: "Criar no construtor", - builderHandoffOpen: "Abrir no construtor →", - builderHandoffSuperseded: "Há uma solicitação mais recente", recordWriteCreateTitle: "Novo {{object}}", recordWriteUpdateTitle: "Alterar {{object}}", recordWriteConfirm: "Confirmar", @@ -2443,32 +2385,17 @@ const pt = { stopResponse: "Parar a resposta", trace: "rastro", viewTrace: "Ver o rastro", - nextSteps: "Próximos passos", - publishDrafts: "Publicar", - publishOk: "Publicado — os objetos já estão ativos.", - seedWarn: "Publicado, mas alguns dados de exemplo não puderam ser carregados.", - openBuiltApp: "Abrir o aplicativo", - viewBuiltAppInStudio: "Ver no Studio", - previewDraft: "Pré-visualizar", previewApp: "Pré-visualizar o aplicativo", resizeSplit: "Redimensionar a conversa e a pré-visualização", hideChats: "Ocultar conversas", showChats: "Mostrar conversas", - planTitle: "Plano proposto", - planQuestions: "Confirmar antes de criar", - planAssumptions: "Suposições", - planApproveHint: "Responda para aprovar ou ajustar este plano.", - planApprove: "Criar", - planAdjust: "Ajustar", justNow: "agora mesmo", minutesAgo: "há {{count}} min", hoursAgo: "há {{count}} h", daysAgo: "há {{count}} d", agentLabels: { ask: "Perguntar", - build: "Criar", dataChat: "Assistente", - metadataAssistant: "Assistente de metadados", }, suggestions: { dataChat: { @@ -2476,51 +2403,12 @@ const pt = { recentRecords: "Liste os 5 registros criados mais recentemente.", recordCounts: "Conte os registros de cada objeto.", }, - // cloud#1984 — these five chips are the maker's own recommendations, so - // they may only ask for what ADR-0112 v1 BUILDS: objects, fields, views - // (grid/kanban/calendar/gallery), pages, dashboards and sample data. No - // wording that promises autonomous behaviour (alert / remind / notify / - // automate / status workflow) — v1 has no flows, actions or schedules, and - // the model silently degrades such a request into a board or a filtered - // view, so the chip would promise an alert and deliver a page. REVERT to - // the automation wording when ADR-0112 v2 re-adds flows and actions. - metadataAssistant: { - buildCrm: "Crie um CRM de vendas — clientes, contatos e negócios com um campo de etapa, e um painel que some o valor por etapa.", - buildApp: "Crie um controle de projetos — projetos, tarefas com responsáveis e prazos, um quadro por status e um calendário de prazos.", - buildFlow: "Projete uma central de suporte — chamados com campos de prioridade e status, um quadro por status e vínculos com clientes.", - buildInventory: "Crie um aplicativo de estoque — produtos, níveis de estoque, fornecedores e uma visão que filtre os itens abaixo do ponto de reposição.", - buildRecruiting: "Crie um controle de candidaturas — candidatos, vagas abertas, um campo de etapa de entrevista e um quadro por etapa.", - }, generic: { help: "Com o que você pode me ajudar?", availableObjects: "Liste os objetos de dados disponíveis.", recentActivity: "Resuma minha atividade recente.", }, - // objectui#7709 — the edit-mode starters, shown when the maker is bound - // to an EXISTING app (`?package=`). Same rule as the five above: they - // may only ask for what ADR-0112 v1 BUILDS. The fourth chip used to be - // `addAutomation` ("an approval, a status flow, or a notification") and - // every capability it named is refused by v1 (cloud#1956 / PR #1970), so - // it now asks for sample data — `seed` IS on v1's whitelist, and having - // no data is what an existing app most often lacks. REVERT: when - // ADR-0112 v2 re-adds flows and actions, THIS chip's automation wording - // comes back as `addAutomation`; the retired string is pinned for every - // pack in `packages/i18n/src/__tests__/makerEditChips-v1-scope-7709.test.ts`. - editApp: { - addField: "Adicione um campo a um dos objetos.", - addObject: "Adicione um novo objeto e relacione-o a um existente.", - addDashboard: "Adicione um painel para as métricas principais.", - addSampleData: "Preencha os objetos existentes com registros de exemplo realistas para eu poder demonstrar o aplicativo.", - }, }, - changesTitle: "Confirmar alterações", - changesConfirmed: "Confirmado", - changesConfirm: "Confirmar", - changesConfirmHint: "Responda para confirmar ou ajustar esta alteração.", - changesApplying: "Aplicando…", - changesApplied: "Aplicado", - changesDrafted: "Salvo como rascunho", - changesFailed: "Não aplicado", discussing: "Vendo: {{target}}", focus: { pin: "Continuar perguntando sobre este registro", @@ -2530,47 +2418,15 @@ const pt = { switchAccept: "Trocar", switchDecline: "Manter", }, - changeVerb: { - createObject: "Criar objeto", - addField: "Adicionar campo", - modifyField: "Modificar campo", - deleteField: "Excluir campo", - createMetadata: "Criar", - updateMetadata: "Modificar", - createSeed: "Gerar dados de exemplo", - createPackage: "Criar pacote de aplicativo", - }, // objectui#3546 slice four — the AI console surfaces: the /ai chat page's app switcher, // connection banner and plan/publish cards, the ChatDock chrome, and the // conversation-list date buckets. `group.*` is the template-key family // `console.ai.group.${key}` (ConversationsSidebar), enumerated from the // ConversationGroupKey union — all five members, no wildcard. collapseToDock: "Recolher para o painel lateral", - switchApp: "Trocar de aplicativo", - switchAppLabel: "Conversas de criação por aplicativo", - newApp: "Novo aplicativo", connectionWaiting: "Aguardando o servidor…", connectionStalled: "Ainda processando…", connectionOffline: "Conexão perdida — reconectando…", - designingPlan: "Projetando seu aplicativo…", - designingPlanHint: { - data: "Mapeando os dados que você vai acompanhar…", - objects: "Modelando os objetos e seus campos…", - relations: "Conectando os registros relacionados…", - lookups: "Configurando as relações e os campos de busca…", - views: "Planejando as telas e as visualizações…", - forms: "Organizando os formulários e as listas…", - defaults: "Adicionando valores padrão e validações sensatas…", - dashboard: "Esboçando um painel para acompanhar…", - review: "Verificando se a estrutura faz sentido…", - finalize: "Reunindo o plano…", - }, - planBuilding: "Criando…", - planBuilt: "Criado", - planDeferred: "Ainda não criado", - planReady: "O plano está pronto. Crie agora ou diga o que ajustar.", - published: "Publicado", - publishFailed: "Falha ao publicar", unavailableTitle: "Assistente de IA indisponível", unavailableDescription: "Esta implantação não tem um assistente de IA habilitado. Todo o resto funciona normalmente.", unavailableError: "Não foi possível acessar o serviço de IA. Ele pode estar temporariamente off-line — tente novamente ou volte ao início.", @@ -4603,19 +4459,6 @@ const pt = { derivedAiAccess: 'Acesso à IA ativado', }, }, - excelImport: { - noImportableFields: "Esse objeto não tem campos importáveis.", - schemaReadFailed: "Não foi possível ler o esquema do objeto.", - imported: "{{count}} linha(s) importada(s) para {{object}}.", - imported_one: "{{count}} linha importada para {{object}}.", - imported_many: "{{count}} de linhas importadas para {{object}}.", - imported_other: "{{count}} linhas importadas para {{object}}.", - importFrom: "Importar as linhas reais de", - into: "para", - opening: "Abrindo…", - importAction: "Importar", - dismiss: "Dispensar", - }, cloudWorkspaceTimezoneNotice: { seeded: "O fuso horário do ambiente foi definido como {{zone}} com base no seu navegador quando ele foi criado. Você pode alterá-lo em Configurações → Localização.", }, @@ -4840,8 +4683,6 @@ const pt = { failed: "Falhou", }, phase: { - build: "Criação", - design: "Desenho do plano", stepCount: "{{count}} etapas", stepCount_one: "{{count}} etapa", stepCount_many: "{{count}} de etapas", @@ -4849,125 +4690,11 @@ const pt = { expand: "Mostrar etapas", collapse: "Ocultar etapas", }, - plan: { - countObjects: "{{count}} objetos", - countObjects_one: "{{count}} objeto", - countObjects_many: "{{count}} de objetos", - countObjects_other: "{{count}} objetos", - countViews: "{{count}} visões", - countViews_one: "{{count}} visão", - countViews_many: "{{count}} de visões", - countViews_other: "{{count}} visões", - countDashboards: "{{count}} painéis", - countDashboards_one: "{{count}} painel", - countDashboards_many: "{{count}} de painéis", - countDashboards_other: "{{count}} painéis", - countSeedData: "dados de exemplo", - extendTarget: "Adicionando ao app existente: {{app}}", - awaitingConfirm: "Aguardando confirmação", - // objectstack#32984 — the plan card's build states. - confirmed: "Confirmado", - buildFailed: "Não construído — nada foi criado", - iterateOrNew: { - question: "Isto se sobrepõe a “{{app}}”, um app que você já tem. Continuar melhorando esse app ou criar um app separado?", - questionUnnamed: "Isto se sobrepõe a um app que você já tem. Continuar melhorando esse app ou criar um separado?", - extend: "Continuar melhorando “{{app}}”", - buildNew: "Criar um app separado", - replyHint: "Responda indicando qual prefere.", - }, - objectsAndFields: "Objetos e campos", - views: "Visões", - suggestedField: "sugerido", - suggestedFieldLegend: "Os campos marcados como “{{mark}}” foram adicionados pela IA; você não os pediu.", - nameField: "Nome: {{field}}", - }, build: { - building: "Criando {{app}}…", - built: "Criação de {{app}} concluída", - builtAndLive: "Criado e publicado · {{app}}", - appFallback: "seu aplicativo", - addingSampleData: "adicionando dados de exemplo", - group: { - object: "Objetos", - view: "Visões", - dashboard: "Painéis", - app: "Aplicativo", - seed: "Dados de exemplo", - dataset: "Conjuntos de dados", - permission: "Permissões", - other: "Outros", - }, - moreArtifacts: "+{{n}} mais", - verifying: "Verificando a alteração…", - verifyStep: "etapa {{n}}", - verified: "Alteração verificada", - // objectstack#32984 — the build card's issues line, in the customer's words. - issuesCount: "{{count}} para corrigir", issuesSummary: "Algumas partes desta construção precisam ser corrigidas antes de ficarem prontas. Responda \"corrija os problemas\" e o assistente vai repará-las.", - warningsSummary: "O app está construído, com alguns pontos que vale a pena verificar. Pergunte ao assistente quais são se quiser melhorá-lo.", - issuesDetails: "Detalhes técnicos", - // objectstack#32984 — the published draft badge's failed-item count, which was English in every locale. - needsAttention: "{{count}} precisam de atenção", - needsAttention_one: "{{count}} precisa de atenção", - needsAttention_many: "{{count}} de itens precisam de atenção", - needsAttention_other: "{{count}} precisam de atenção", health: { - sampleRowsLive: "{{count}} linhas de exemplo publicadas", - sampleRowsLive_one: "{{count}} linha de exemplo publicada", - sampleRowsLive_many: "{{count}} de linhas de exemplo publicadas", - sampleRowsLive_other: "{{count}} linhas de exemplo publicadas", - views: "{{count}} visões", - views_one: "{{count}} visão", - views_many: "{{count}} de visões", - views_other: "{{count}} visões", - widgets: "{{count}} widgets", - widgets_one: "{{count}} widget", - widgets_many: "{{count}} de widgets", - widgets_other: "{{count}} widgets", - seeds: "{{count}} conjuntos de dados de exemplo", - seeds_one: "{{count}} conjunto de dados de exemplo", - seeds_many: "{{count}} de conjuntos de dados de exemplo", - seeds_other: "{{count}} conjuntos de dados de exemplo", - verified: "Verificado: {{checks}}", seedFailed: "Não foi possível carregar os dados de exemplo.", }, - unknownPhase: "Fase de criação desconhecida", - nextStepsLead: "Em seguida, você pode dizer: {{steps}}", - nextStepQuote: "“{{step}}”", - draftPosture: "As alterações seguintes ficam salvas como rascunho; publique-as com «Publicar» aqui no chat.", - checksPassed: "Verificações aprovadas {{passed}}/{{total}}", - }, - changes: { - planTitle: "Plano de alterações · {{count}} alterações", - planTitle_one: "Plano de alterações · {{count}} alteração", - planTitle_many: "Plano de alterações · {{count}} de alterações", - planTitle_other: "Plano de alterações · {{count}} alterações", - saveDraft: "Salvar como rascunho", - reviewAndPublish: "Revisar alterações e publicar", - undo: "Desfazer", - undoWithOthers: "Desfazer (e mais {{count}} rascunhos)", - undoWithOthers_one: "Desfazer (e mais {{count}} rascunho)", - undoWithOthers_many: "Desfazer (e mais {{count}} de rascunhos)", - undoWithOthers_other: "Desfazer (e mais {{count}} rascunhos)", - undoConfirm: "Desfazer descarta todos os {{total}} rascunhos não publicados deste pacote, incluindo {{count}} que não fazem parte desta alteração.", - undoConfirm_one: "Desfazer descarta todos os {{total}} rascunhos não publicados deste pacote, incluindo {{count}} que não faz parte desta alteração.", - undoConfirm_many: "Desfazer descarta todos os {{total}} rascunhos não publicados deste pacote, incluindo {{count}} de rascunhos que não fazem parte desta alteração.", - undoConfirm_other: "Desfazer descarta todos os {{total}} rascunhos não publicados deste pacote, incluindo {{count}} que não fazem parte desta alteração.", - undoConfirmUnknown: "Desfazer descarta todos os rascunhos não publicados deste pacote, não só esta alteração.", - undoConfirmAction: "Desfazer tudo", - undoCancel: "Cancelar", - undoing: "Desfazendo…", - undone: "Desfeito", - undoFailed: "Não foi possível desfazer", - kind: { - field: "Campo", - object: "Objeto", - view: "Visão", - dashboard: "Painel", - app: "Aplicativo", - seed: "Dados de exemplo", - package: "Pacote do aplicativo", - }, }, }, chatbotError: { diff --git a/ui/packages/i18n/src/locales/ru.ts b/ui/packages/i18n/src/locales/ru.ts index 6fb51e03a05..cfb81c7c499 100644 --- a/ui/packages/i18n/src/locales/ru.ts +++ b/ui/packages/i18n/src/locales/ru.ts @@ -2331,27 +2331,9 @@ const ru = { }, ai: { pendingDrafts: { - // objectstack#34610 — the line points to the shell's draft bar and shows a publish receipt. - publishFromBar: '{{count}} неопубликованных изменений. Опубликуйте их в панели черновика вверху.', - publishFromBar_one: '{{count}} неопубликованное изменение. Опубликуйте его в панели черновика вверху.', - publishFromBar_few: '{{count}} неопубликованных изменения. Опубликуйте их в панели черновика вверху.', - publishFromBar_many: '{{count}} неопубликованных изменений. Опубликуйте их в панели черновика вверху.', - publishFromBar_other: '{{count}} неопубликованного изменения. Опубликуйте их в панели черновика вверху.', - showDraftToPublish: '{{count}} неопубликованных изменений. Откройте черновик, чтобы проверить и опубликовать их.', - showDraftToPublish_one: '{{count}} неопубликованное изменение. Откройте черновик, чтобы проверить и опубликовать его.', - showDraftToPublish_few: '{{count}} неопубликованных изменения. Откройте черновик, чтобы проверить и опубликовать их.', - showDraftToPublish_many: '{{count}} неопубликованных изменений. Откройте черновик, чтобы проверить и опубликовать их.', - showDraftToPublish_other: '{{count}} неопубликованного изменения. Откройте черновик, чтобы проверить и опубликовать их.', - showDraft: 'Показать черновик', - receipt: 'Опубликовано. Изменения вступили в силу.', - dismissReceipt: 'Закрыть', // Число вынесено в конец («…: {{count}}») — так этот пак пишет // количества, как в home.pendingDrafts.publishedVerified. count: "Ещё не опубликовано изменений: {{count}} — пользователи их не видят.", - publish: "Опубликовать", - published: "Все ожидающие изменения вступили в силу.", - failed: "Не удалось опубликовать.", - publishedWithFindings: "Опубликовано, но проверки среды выполнения выявили проблемы: {{detail}}", }, usage: { title: "Использование ИИ", @@ -2381,31 +2363,6 @@ const ru = { share: "Поделиться", shareTitle: "Поделиться этим диалогом", shareDisabledTitle: "Начните диалог, чтобы включить публикацию", - buildDoctor: "Диагностика сборки", - buildDoctorTitle: "Диагностика сборки — что на самом деле применено?", - buildDoctorDisabledTitle: "Сначала отправьте сообщение", - buildDoctorDrawer: { - description: 'Что заявил агент и что на самом деле действует. Диагностика только для чтения.', - reconciling: 'Сверка…', - notAvailable: 'Недоступно — беседа не найдена или у вас нет доступа.', - untitled: '(без названия)', - summary: 'Ходов: {{turns}} · сообщений: {{messages}} · токенов: {{tokens}} · LLM: {{seconds}} с', - allLive: 'Все попытки изменений ({{count}}) действуют — ничего не потерялось.', - discrepancies: 'Расхождений: {{count}} — сказанное в чате не совпадает с тем, что действует.', - orphanedTitle: 'Предложено, но не применено', - orphanedHint: 'Карточку подтверждения, предложенную агентом, не применил ни один последующий ход — изменение незаметно потерялось.', - missingTitle: 'Заявлено, но отсутствует', - missingHint: 'Результат инструмента сообщил, что изменение применено, но артефакт не действует в sys_metadata.', - toolErrorsTitle: 'Ошибки инструментов', - toolErrorsHint: 'Вызовы инструментов, вернувшие ошибку во время сборки.', - verifyTitle: 'Проверка сборки (verify_build)', - yourApp: 'Ваше приложение:', - noIssues: 'Проблем: 0', - issueCount: 'Проблем: {{count}}', - platformNoise: 'Скрыто находок платформы sys_*: {{count}}', - pendingActions: 'Ожидающие действия', - timeline: 'Хронология ({{count}})', - }, newChat: "Создать", searchChats: "Поиск по чатам…", noChatsYet: "Чатов пока нет", @@ -2427,29 +2384,15 @@ const ru = { liveCanvasLive: "Работающее приложение — {{app}}", loadingAgents: "Загрузка агентов…", askAnything: "Спросите о чём угодно…", - askOrChangeApp: "Спросите о данных или попросите меня изменить это приложение…", - describeAppToBuild: "Опишите приложение, которое хотите создать, или что изменить…", emptyTitle: "Начните диалог", emptyDescription: "Спросите о чём угодно — ассистент видит контекст вашего текущего приложения.", switchAssistant: "Сменить ассистента", chooseAgent: "Выберите ассистента…", empty: { - build: { - title: "Создать с помощью ИИ", - description: "Опишите приложение обычными словами — я подготовлю объекты, экраны и демонстрационные данные, а вы проверите и опубликуете.", - }, ask: { title: "Спросите свои данные", description: "Задавайте вопросы о записях — количество, списки и сводки по доступным вам данным.", }, - editApp: { - title: "Редактирование «{{app}}»", - titleGeneric: "Редактировать это приложение", - description: "Что нужно изменить? Я изменю это приложение на месте — добавлю поле, объект, представление или дашборд либо скорректирую существующее.", - // objectstack#34608 — the builder's empty state names both halves: data questions and changes. - askOrChangeDescription: - "Спросите о данных этого приложения — количествах, списках и сводках — или скажите, что изменить, и я изменю приложение на месте: поле, объект, представление или дашборд.", - }, }, clearConversation: "Очистить", sendHint: "чтобы отправить", @@ -2461,9 +2404,6 @@ const ru = { toolFailed: "Ошибка", toolDetailsHidden: "Входные данные инструментов и необработанные результаты в этом режиме скрыты.", toolDenyReason: "Отклонено оператором в чате", - builderHandoffTitle: "Создать в конструкторе", - builderHandoffOpen: "Открыть в конструкторе →", - builderHandoffSuperseded: "Есть более новый запрос", recordWriteCreateTitle: "Новая запись: {{object}}", recordWriteUpdateTitle: "Изменить {{object}}", recordWriteConfirm: "Подтвердить", @@ -2522,32 +2462,17 @@ const ru = { stopResponse: "Остановить ответ", trace: "трассировка", viewTrace: "Посмотреть трассировку", - nextSteps: "Что дальше", - publishDrafts: "Опубликовать", - publishOk: "Опубликовано — объекты активны.", - seedWarn: "Опубликовано, но часть примеров данных загрузить не удалось.", - openBuiltApp: "Открыть приложение", - viewBuiltAppInStudio: "Открыть в Studio", - previewDraft: "Предпросмотр", previewApp: "Предпросмотр приложения", resizeSplit: "Изменить размер чата и предпросмотра", hideChats: "Скрыть чаты", showChats: "Показать чаты", - planTitle: "Предложенный план", - planQuestions: "Подтвердите перед сборкой", - planAssumptions: "Допущения", - planApproveHint: "Ответьте, чтобы утвердить или скорректировать этот план.", - planApprove: "Собрать", - planAdjust: "Скорректировать", justNow: "только что", minutesAgo: "{{count}} мин назад", hoursAgo: "{{count}} ч назад", daysAgo: "{{count}} дн назад", agentLabels: { ask: "Вопрос", - build: "Сборка", dataChat: "Ассистент", - metadataAssistant: "Ассистент по метаданным", }, suggestions: { dataChat: { @@ -2555,51 +2480,12 @@ const ru = { recentRecords: "Перечисли 5 последних созданных записей.", recordCounts: "Посчитай количество записей по каждому объекту.", }, - // cloud#1984 — these five chips are the maker's own recommendations, so - // they may only ask for what ADR-0112 v1 BUILDS: objects, fields, views - // (grid/kanban/calendar/gallery), pages, dashboards and sample data. No - // wording that promises autonomous behaviour (alert / remind / notify / - // automate / status workflow) — v1 has no flows, actions or schedules, and - // the model silently degrades such a request into a board or a filtered - // view, so the chip would promise an alert and deliver a page. REVERT to - // the automation wording when ADR-0112 v2 re-adds flows and actions. - metadataAssistant: { - buildCrm: "Создай CRM для продаж — клиенты, контакты и сделки с полем этапа, а также дашборд с суммой сделок по этапам.", - buildApp: "Создай трекер проектов — проекты, задачи с ответственными и сроками, доска по статусам и календарь сроков.", - buildFlow: "Спроектируй службу поддержки — заявки с полями приоритета и статуса, доска по статусам и связи с клиентами.", - buildInventory: "Создай приложение для склада — товары, остатки, поставщики и представление, отбирающее товары ниже точки заказа.", - buildRecruiting: "Создай трекер кандидатов — кандидаты, открытые вакансии, поле этапа собеседования и доска по этапам.", - }, generic: { help: "Чем ты можешь мне помочь?", availableObjects: "Перечисли доступные объекты данных.", recentActivity: "Сделай сводку моей недавней активности.", }, - // objectui#7709 — the edit-mode starters, shown when the maker is bound - // to an EXISTING app (`?package=`). Same rule as the five above: they - // may only ask for what ADR-0112 v1 BUILDS. The fourth chip used to be - // `addAutomation` ("an approval, a status flow, or a notification") and - // every capability it named is refused by v1 (cloud#1956 / PR #1970), so - // it now asks for sample data — `seed` IS on v1's whitelist, and having - // no data is what an existing app most often lacks. REVERT: when - // ADR-0112 v2 re-adds flows and actions, THIS chip's automation wording - // comes back as `addAutomation`; the retired string is pinned for every - // pack in `packages/i18n/src/__tests__/makerEditChips-v1-scope-7709.test.ts`. - editApp: { - addField: "Добавь поле в один из объектов.", - addObject: "Добавь новый объект и свяжи его с существующим.", - addDashboard: "Добавь дашборд с ключевыми показателями.", - addSampleData: "Заполни существующие объекты правдоподобными демонстрационными записями, чтобы приложение можно было показать.", - }, }, - changesTitle: "Подтвердите изменения", - changesConfirmed: "Подтверждено", - changesConfirm: "Подтвердить", - changesConfirmHint: "Ответьте, чтобы подтвердить или скорректировать это изменение.", - changesApplying: "Применение…", - changesApplied: "Применено", - changesDrafted: "Сохранено как черновик", - changesFailed: "Не применено", discussing: "Просмотр: {{target}}", focus: { pin: "Продолжать спрашивать об этой записи", @@ -2609,47 +2495,15 @@ const ru = { switchAccept: "Переключить", switchDecline: "Оставить", }, - changeVerb: { - createObject: "Создать объект", - addField: "Добавить поле", - modifyField: "Изменить поле", - deleteField: "Удалить поле", - createMetadata: "Создать", - updateMetadata: "Изменить", - createSeed: "Сгенерировать примеры данных", - createPackage: "Создать пакет приложения", - }, // objectui#3546 slice four — the AI console surfaces: the /ai chat page's app switcher, // connection banner and plan/publish cards, the ChatDock chrome, and the // conversation-list date buckets. `group.*` is the template-key family // `console.ai.group.${key}` (ConversationsSidebar), enumerated from the // ConversationGroupKey union — all five members, no wildcard. collapseToDock: "Свернуть в боковую панель", - switchApp: "Сменить приложение", - switchAppLabel: "Диалоги сборки по приложениям", - newApp: "Новое приложение", connectionWaiting: "Ожидание сервера…", connectionStalled: "Всё ещё выполняется…", connectionOffline: "Соединение потеряно — переподключение…", - designingPlan: "Проектирование вашего приложения…", - designingPlanHint: { - data: "Определяю данные, которые вы будете отслеживать…", - objects: "Формирую объекты и их поля…", - relations: "Соединяю связанные записи…", - lookups: "Настраиваю связи и подстановки…", - views: "Планирую экраны и представления…", - forms: "Размещаю формы и списки…", - defaults: "Добавляю разумные значения по умолчанию и проверки…", - dashboard: "Набрасываю дашборд для отслеживания…", - review: "Перепроверяю, что структура согласована…", - finalize: "Собираю план воедино…", - }, - planBuilding: "Сборка…", - planBuilt: "Собрано", - planDeferred: "Ещё не собрано", - planReady: "План готов. Соберите его сейчас или скажите, что нужно скорректировать.", - published: "Опубликовано", - publishFailed: "Не удалось опубликовать", unavailableTitle: "Ассистент ИИ недоступен", unavailableDescription: "В этой среде ассистент ИИ не включён. Всё остальное работает как обычно.", unavailableError: "Не удалось связаться с сервисом ИИ. Возможно, он временно недоступен — повторите попытку или вернитесь на главную.", @@ -4713,20 +4567,6 @@ const ru = { derivedAiAccess: 'Доступ к ИИ включён', }, }, - excelImport: { - noImportableFields: "У этого объекта нет полей, доступных для импорта.", - schemaReadFailed: "Не удалось прочитать схему объекта.", - imported: "Импортировано строк: {{count}} в {{object}}.", - imported_one: "Импортировано строк: {{count}} в {{object}}.", - imported_few: "Импортировано строк: {{count}} в {{object}}.", - imported_many: "Импортировано строк: {{count}} в {{object}}.", - imported_other: "Импортировано строк: {{count}} в {{object}}.", - importFrom: "Импортировать реальные строки из", - into: "в", - opening: "Открытие…", - importAction: "Импорт", - dismiss: "Скрыть", - }, cloudWorkspaceTimezoneNotice: { seeded: "Часовой пояс окружения был задан по вашему браузеру при его создании: {{zone}}. Его можно изменить в разделе «Настройки → Локализация».", }, @@ -4951,8 +4791,6 @@ const ru = { failed: "Ошибка выполнения", }, phase: { - build: "Сборка", - design: "Проектирование плана", stepCount: "шагов: {{count}}", stepCount_one: "{{count}} шаг", stepCount_few: "{{count}} шага", @@ -4961,136 +4799,11 @@ const ru = { expand: "Показать шаги", collapse: "Скрыть шаги", }, - plan: { - countObjects: "объектов: {{count}}", - countObjects_one: "{{count}} объект", - countObjects_few: "{{count}} объекта", - countObjects_many: "{{count}} объектов", - countObjects_other: "{{count}} объекта", - countViews: "представлений: {{count}}", - countViews_one: "{{count}} представление", - countViews_few: "{{count}} представления", - countViews_many: "{{count}} представлений", - countViews_other: "{{count}} представления", - countDashboards: "дашбордов: {{count}}", - countDashboards_one: "{{count}} дашборд", - countDashboards_few: "{{count}} дашборда", - countDashboards_many: "{{count}} дашбордов", - countDashboards_other: "{{count}} дашборда", - countSeedData: "демоданные", - extendTarget: "Добавление в существующее приложение: {{app}}", - awaitingConfirm: "Ожидает подтверждения", - // objectstack#32984 — the plan card's build states. - confirmed: "Подтверждено", - buildFailed: "Не создано — ничего не было создано", - iterateOrNew: { - question: "Это пересекается с «{{app}}» — приложением, которое у вас уже есть. Продолжить улучшать его или создать отдельное приложение?", - questionUnnamed: "Это пересекается с приложением, которое у вас уже есть. Продолжить улучшать его или создать отдельное приложение?", - extend: "Продолжить улучшать «{{app}}»", - buildNew: "Создать отдельное приложение", - replyHint: "Ответьте, какой вариант выбрать.", - }, - objectsAndFields: "Объекты и поля", - views: "Представления", - suggestedField: "предложено", - suggestedFieldLegend: "Поля с пометкой «{{mark}}» добавил ИИ; вы их не запрашивали.", - nameField: "Название: {{field}}", - }, build: { - building: "Создание {{app}}…", - built: "Создание {{app}} завершено", - builtAndLive: "Создано и опубликовано · {{app}}", - appFallback: "вашего приложения", - addingSampleData: "добавление демоданных", - group: { - object: "Объекты", - view: "Представления", - dashboard: "Дашборды", - app: "Приложение", - seed: "Демоданные", - dataset: "Наборы данных", - permission: "Разрешения", - other: "Другое", - }, - moreArtifacts: "ещё {{n}}", - verifying: "Проверка изменения…", - verifyStep: "шаг {{n}}", - verified: "Изменение проверено", - // objectstack#32984 — the build card's issues line, in the customer's words. - issuesCount: "Нужно исправить: {{count}}", issuesSummary: "Часть этой сборки нужно исправить, прежде чем ею можно будет пользоваться. Ответьте «исправь проблемы», и ассистент всё починит.", - warningsSummary: "Приложение собрано, но несколько моментов стоит проверить. Спросите ассистента, какие именно, если хотите его улучшить.", - issuesDetails: "Технические подробности", - // objectstack#32984 — the published draft badge's failed-item count, which was English in every locale. - needsAttention: "{{count}} требуют внимания", - needsAttention_one: "{{count}} требует внимания", - needsAttention_few: "{{count}} требуют внимания", - needsAttention_many: "{{count}} требуют внимания", - needsAttention_other: "{{count}} требуют внимания", health: { - sampleRowsLive: "опубликовано строк примеров: {{count}}", - sampleRowsLive_one: "опубликована {{count}} строка примеров", - sampleRowsLive_few: "опубликованы {{count}} строки примеров", - sampleRowsLive_many: "опубликовано {{count}} строк примеров", - sampleRowsLive_other: "опубликовано {{count}} строки примеров", - views: "представлений: {{count}}", - views_one: "{{count}} представление", - views_few: "{{count}} представления", - views_many: "{{count}} представлений", - views_other: "{{count}} представления", - widgets: "виджетов: {{count}}", - widgets_one: "{{count}} виджет", - widgets_few: "{{count}} виджета", - widgets_many: "{{count}} виджетов", - widgets_other: "{{count}} виджета", - seeds: "наборов примеров: {{count}}", - seeds_one: "{{count}} набор примеров", - seeds_few: "{{count}} набора примеров", - seeds_many: "{{count}} наборов примеров", - seeds_other: "{{count}} набора примеров", - verified: "Проверено: {{checks}}", seedFailed: "Не удалось загрузить примеры данных.", }, - unknownPhase: "Неизвестный этап сборки", - nextStepsLead: "Дальше можно сказать: {{steps}}", - nextStepQuote: "«{{step}}»", - draftPosture: "Дальнейшие изменения сохраняются как черновики; опубликуйте их кнопкой «Опубликовать» здесь, в чате.", - checksPassed: "Проверки пройдены {{passed}}/{{total}}", - }, - changes: { - planTitle: "План изменений · изменений: {{count}}", - planTitle_one: "План изменений · {{count}} изменение", - planTitle_few: "План изменений · {{count}} изменения", - planTitle_many: "План изменений · {{count}} изменений", - planTitle_other: "План изменений · {{count}} изменения", - saveDraft: "Сохранить как черновик", - reviewAndPublish: "Проверить изменения и опубликовать", - undo: "Отменить", - undoWithOthers: "Отменить (других черновиков: {{count}})", - undoWithOthers_one: "Отменить (и ещё {{count}} черновик)", - undoWithOthers_few: "Отменить (и ещё {{count}} черновика)", - undoWithOthers_many: "Отменить (и ещё {{count}} черновиков)", - undoWithOthers_other: "Отменить (и ещё {{count}} черновика)", - undoConfirm: "Отмена удалит все неопубликованные черновики этого пакета ({{total}}), из них не относятся к этому изменению: {{count}}.", - undoConfirm_one: "Отмена удалит все неопубликованные черновики этого пакета ({{total}}), из них {{count}} не относится к этому изменению.", - undoConfirm_few: "Отмена удалит все неопубликованные черновики этого пакета ({{total}}), из них {{count}} не относятся к этому изменению.", - undoConfirm_many: "Отмена удалит все неопубликованные черновики этого пакета ({{total}}), из них {{count}} не относятся к этому изменению.", - undoConfirm_other: "Отмена удалит все неопубликованные черновики этого пакета ({{total}}), из них {{count}} не относятся к этому изменению.", - undoConfirmUnknown: "Отмена удалит все неопубликованные черновики этого пакета, а не только это изменение.", - undoConfirmAction: "Отменить всё", - undoCancel: "Не отменять", - undoing: "Отмена…", - undone: "Отменено", - undoFailed: "Не удалось отменить", - kind: { - field: "Поле", - object: "Объект", - view: "Представление", - dashboard: "Дашборд", - app: "Приложение", - seed: "Демоданные", - package: "Пакет приложения", - }, }, }, chatbotError: { diff --git a/ui/packages/i18n/src/locales/zh-Hans.ts b/ui/packages/i18n/src/locales/zh-Hans.ts index f9bb950a450..25149433edb 100644 --- a/ui/packages/i18n/src/locales/zh-Hans.ts +++ b/ui/packages/i18n/src/locales/zh-Hans.ts @@ -2552,21 +2552,7 @@ const zh = { }, ai: { pendingDrafts: { - // objectstack#34610 — the line points to the shell's draft bar and shows a publish receipt. - publishFromBar: '有 {{count}} 项未发布的改动,请在顶部的草稿栏发布。', - publishFromBar_one: '有 {{count}} 项未发布的改动,请在顶部的草稿栏发布。', - publishFromBar_other: '有 {{count}} 项未发布的改动,请在顶部的草稿栏发布。', - showDraftToPublish: '有 {{count}} 项未发布的改动,打开草稿查看并发布。', - showDraftToPublish_one: '有 {{count}} 项未发布的改动,打开草稿查看并发布。', - showDraftToPublish_other: '有 {{count}} 项未发布的改动,打开草稿查看并发布。', - showDraft: '查看草稿', - receipt: '已发布,改动已生效。', - dismissReceipt: '关闭', count: '有 {{count}} 项改动尚未发布——用户还看不到。', - publish: '发布', - published: '全部待发布改动已生效。', - failed: '发布失败。', - publishedWithFindings: '已发布,但运行时探针发现问题:{{detail}}', }, usage: { title: 'AI 用量', @@ -2592,31 +2578,6 @@ const zh = { share: '分享', shareTitle: '分享此对话', shareDisabledTitle: '开始对话后即可分享', - buildDoctor: '构建诊断', - buildDoctorTitle: '构建诊断 — 实际生效了哪些变更?', - buildDoctorDisabledTitle: '请先发送一条消息', - buildDoctorDrawer: { - description: '智能体声称的变更与实际已生效的内容对照。只读诊断。', - reconciling: '正在核对…', - notAvailable: '不可用——未找到该对话,或你没有访问权限。', - untitled: '(无标题)', - summary: '{{turns}} 轮 · {{messages}} 条消息 · {{tokens}} tok · LLM {{seconds}} 秒', - allLive: '全部 {{count}} 项尝试的变更均已生效——没有丢失。', - discrepancies: '{{count}} 处不一致——对话中所说的与实际生效的内容不符。', - orphanedTitle: '已提议但从未应用', - orphanedHint: '智能体提议了确认卡片,但之后没有任何一轮应用它——该变更被静默丢弃。', - missingTitle: '声称已应用但缺失', - missingHint: '工具结果称已应用,但该产物并未在 sys_metadata 中生效。', - toolErrorsTitle: '工具错误', - toolErrorsHint: '构建期间返回错误的工具调用。', - verifyTitle: '构建检查(verify_build)', - yourApp: '你的应用:', - noIssues: '0 个问题', - issueCount: '{{count}} 个问题', - platformNoise: '已隐藏 {{count}} 条平台 sys_* 发现', - pendingActions: '待处理操作', - timeline: '时间线({{count}})', - }, newChat: '新对话', searchChats: '搜索对话…', noChatsYet: '暂无对话', @@ -2638,29 +2599,15 @@ const zh = { liveCanvasLive: '运行预览 · {{app}}', loadingAgents: '正在加载助手…', askAnything: '输入你的问题…', - askOrChangeApp: '问问数据,或让我改改这个应用…', - describeAppToBuild: '描述你想搭建的应用,或要改的地方…', emptyTitle: '开始对话', emptyDescription: '可以直接提问,助手会结合当前应用上下文提供帮助。', switchAssistant: '切换助手', chooseAgent: '选择助手…', empty: { - build: { - title: '用 AI 搭建', - description: '用自然语言描述一个应用 —— 我会起草对象、界面和示例数据,随后你审阅并发布。', - }, ask: { title: '向你的数据提问', description: '针对你的记录提问 —— 在你有权访问的数据范围内进行计数、列举和汇总。', }, - editApp: { - title: '正在编辑「{{app}}」', - titleGeneric: '编辑此应用', - description: '想改点什么?我会就地修改这个应用 —— 加字段、对象、视图或仪表盘,或调整已有内容。', - // objectstack#34608 — the builder's empty state names both halves: data questions and changes. - askOrChangeDescription: - '问数据,或者让我改这个应用 —— 可以问记录的计数、列表和汇总,也可以告诉我要改什么,我会就地修改:字段、对象、视图或仪表盘。', - }, }, clearConversation: '清空', sendHint: '发送', @@ -2672,9 +2619,6 @@ const zh = { toolFailed: '失败', toolDetailsHidden: '已隐藏工具参数和原始结果,仅保留过程摘要。', toolDenyReason: '操作员已在对话中拒绝', - builderHandoffTitle: '在构建器中搭建', - builderHandoffOpen: '在构建器中打开 →', - builderHandoffSuperseded: '已有更新的请求', recordWriteCreateTitle: '新建{{object}}', recordWriteUpdateTitle: '修改{{object}}', recordWriteConfirm: '确认', @@ -2721,43 +2665,10 @@ const zh = { stopResponse: '停止生成', trace: '调试 trace', viewTrace: '查看调试 trace', - // 搭建流程的草稿与「方案预览」确认卡片(AiChatPage /ai/build)。 - // 与 ConsoleFloatingChatbot 的 locale 对象保持一致,两个 AI 界面文案统一。 - nextSteps: '下一步', - publishDrafts: '发布', - publishOk: '已发布,对象已生效。', - seedWarn: '已发布,但部分示例数据未能载入。', - openBuiltApp: '打开应用', - viewBuiltAppInStudio: '在 Studio 中查看', - previewDraft: '预览', previewApp: '预览应用', resizeSplit: '调整对话与预览的宽度', hideChats: '隐藏对话列表', showChats: '显示对话列表', - planTitle: '方案预览', - planQuestions: '搭建前请确认', - planAssumptions: '假设', - planApproveHint: '回复以确认或调整该方案。', - planApprove: '开始搭建', - planAdjust: '调整方案', - // The two messages the "开始搭建" button SENDS (not the label above) must - // match the cloud confirm gate's APPROVAL_RE (service-ai-studio - // confirm-gate.ts), or the agent re-proposes instead of building and the - // button looks inert. The gate anchors Chinese approval on 确认 (or - // 直接搭建) — a bare "…搭建吧" does NOT match. Keep these 确认-anchored. - planApproveMessage: '确认,开始搭建。', - planApproveDefaultsMessage: '确认搭建,未决问题按你的合理假设和默认处理。', - planAnswerMessage: '关于「{{question}}」,我选择「{{option}}」。', - planExtendExistingMessage: '在「{{app}}」上继续完善,不另建应用。', - planBuildNewAppMessage: '另建一个独立应用。', - changesTitle: '确认改动', - changesConfirmed: '已确认', - changesConfirm: '确认修改', - changesConfirmHint: '回复以确认或调整该改动。', - changesApplying: '应用中…', - changesApplied: '已生效', - changesDrafted: '已暂存为草稿', - changesFailed: '未生效', discussing: '正在看:{{target}}', focus: { pin: '钉住这条记录,换页后仍问它', @@ -2767,27 +2678,14 @@ const zh = { switchAccept: '改为问它', switchDecline: '不用', }, - changesConfirmMessage: '确认修改,应用你刚才提议的改动。', - changeVerb: { - createObject: '新建对象', - addField: '新增字段', - modifyField: '修改字段', - deleteField: '删除字段', - createMetadata: '新建', - updateMetadata: '修改', - createSeed: '生成示例数据', - createPackage: '新建应用包', - }, justNow: '刚刚', minutesAgo: '{{count}} 分钟前', hoursAgo: '{{count}} 小时前', daysAgo: '{{count}} 天前', agentLabels: { ask: '提问', - build: '构建', // 旧键保留,兼容外部覆盖。 dataChat: '智能助手', - metadataAssistant: '元数据开发助手', }, suggestions: { dataChat: { @@ -2795,42 +2693,11 @@ const zh = { recentRecords: '帮我列出最近创建的 5 条记录。', recordCounts: '统计每个对象的记录数。', }, - // cloud#1984 — these five chips are the maker's own recommendations, so - // they may only ask for what ADR-0112 v1 BUILDS: objects, fields, views - // (grid/kanban/calendar/gallery), pages, dashboards and sample data. No - // wording that promises autonomous behaviour (alert / remind / notify / - // automate / status workflow) — v1 has no flows, actions or schedules, and - // the model silently degrades such a request into a board or a filtered - // view, so the chip would promise an alert and deliver a page. REVERT to - // the automation wording when ADR-0112 v2 re-adds flows and actions. - metadataAssistant: { - buildCrm: '帮我搭建一个 CRM:客户、联系人、商机,以及一个按阶段汇总商机金额的仪表盘。', - buildApp: '做一个项目管理应用:项目、任务(负责人、截止日期),按状态分组的看板,以及按截止日期的日历视图。', - buildFlow: '设计一个工单系统:工单、优先级、状态(下拉),以及按状态分组的看板。', - buildInventory: '做一个库存管理应用:商品、库存量、供应商,并用一个视图筛出低于安全库存的商品。', - buildRecruiting: '做一个招聘跟踪应用:候选人、在招岗位、面试阶段字段,以及按阶段分组的看板。', - }, generic: { help: '你可以帮我做什么?', availableObjects: '列出可用的数据对象。', recentActivity: '总结我的最近动态。', }, - // objectui#7709 — the edit-mode starters, shown when the maker is bound - // to an EXISTING app (`?package=`). Same rule as the five above: they - // may only ask for what ADR-0112 v1 BUILDS. The fourth chip used to be - // `addAutomation` ("an approval, a status flow, or a notification") and - // every capability it named is refused by v1 (cloud#1956 / PR #1970), so - // it now asks for sample data — `seed` IS on v1's whitelist, and having - // no data is what an existing app most often lacks. REVERT: when - // ADR-0112 v2 re-adds flows and actions, THIS chip's automation wording - // comes back as `addAutomation`; the retired string is pinned for every - // pack in `packages/i18n/src/__tests__/makerEditChips-v1-scope-7709.test.ts`. - editApp: { - addField: '给某个对象加一个字段。', - addObject: '新增一个对象,并关联到已有对象。', - addDashboard: '加一个展示关键指标的仪表盘。', - addSampleData: '给现有对象补一批贴近真实的示例数据,好拿去演示。', - }, }, // objectui#3546 slice four — the AI console surfaces: the /ai chat page's app switcher, // connection banner and plan/publish cards, the ChatDock chrome, and the @@ -2838,31 +2705,9 @@ const zh = { // `console.ai.group.${key}` (ConversationsSidebar), enumerated from the // ConversationGroupKey union — all five members, no wildcard. collapseToDock: '收起到侧边栏', - switchApp: '切换应用', - switchAppLabel: '按应用查看搭建对话', - newApp: '新建应用', connectionWaiting: '正在等待服务器…', connectionStalled: '仍在处理…', connectionOffline: '连接已断开 — 正在重新连接…', - designingPlan: '正在设计你的应用…', - designingPlanHint: { - data: '正在梳理你要跟踪的数据…', - objects: '正在设计对象及其字段…', - relations: '正在关联相关记录…', - lookups: '正在设置关系与关联查找…', - views: '正在规划界面与视图…', - forms: '正在排布表单与列表…', - defaults: '正在添加合理的默认值与校验…', - dashboard: '正在勾画用于跟踪的仪表盘…', - review: '正在复核整体结构是否自洽…', - finalize: '正在汇总方案…', - }, - planBuilding: '正在搭建…', - planBuilt: '已搭建', - planDeferred: '尚未搭建', - planReady: '方案已就绪。现在就开始搭建,或者告诉我需要调整什么。', - published: '已发布', - publishFailed: '发布失败', unavailableTitle: 'AI 助手不可用', unavailableDescription: '当前部署未启用 AI 助手。其他功能一切正常。', unavailableError: '无法连接 AI 服务。它可能暂时离线 — 请重试,或返回首页。', @@ -4773,18 +4618,6 @@ const zh = { derivedAiAccess: '已开启 AI 访问', }, }, - excelImport: { - noImportableFields: '该对象没有可导入的字段。', - schemaReadFailed: '无法读取对象结构。', - imported: '已把 {{count}} 行真实数据导入「{{object}}」。', - imported_one: '已把 {{count}} 行真实数据导入「{{object}}」。', - imported_other: '已把 {{count}} 行真实数据导入「{{object}}」。', - importFrom: '把真实数据导入自', - into: '到', - opening: '打开中…', - importAction: '导入', - dismiss: '忽略', - }, cloudWorkspaceTimezoneNotice: { seeded: '环境时区在创建时已按你的浏览器设为 {{zone}},可在「设置 → 本地化」中修改。', }, @@ -5009,122 +4842,17 @@ const zh = { failed: '失败', }, phase: { - build: '搭建', - design: '设计方案', stepCount: '{{count}} 步', stepCount_one: '{{count}} 步', stepCount_other: '{{count}} 步', expand: '展开步骤', collapse: '收起步骤', }, - plan: { - countObjects: '{{count}} 个对象', - countObjects_one: '{{count}} 个对象', - countObjects_other: '{{count}} 个对象', - countViews: '{{count}} 个视图', - countViews_one: '{{count}} 个视图', - countViews_other: '{{count}} 个视图', - countDashboards: '{{count}} 个仪表盘', - countDashboards_one: '{{count}} 个仪表盘', - countDashboards_other: '{{count}} 个仪表盘', - countSeedData: '示例数据', - extendTarget: '添加到现有应用:{{app}}', - awaitingConfirm: '等待确认', - // objectstack#32984 — the plan card's build states. - confirmed: '已确认', - buildFailed: '未搭建成功 · 没有创建任何内容', - iterateOrNew: { - question: '这个方案和你已有的应用「{{app}}」重叠。要在它上面继续完善,还是另建一个独立应用?', - questionUnnamed: '这个方案和你已有的一个应用重叠。要在那个应用上继续完善,还是另建一个独立应用?', - extend: '在「{{app}}」上继续完善', - buildNew: '另建一个独立应用', - replyHint: '回复告诉我选哪一个。', - }, - objectsAndFields: '对象与字段', - views: '视图', - suggestedField: '补充', - suggestedFieldLegend: '标「{{mark}}」的字段是 AI 自行补充的,你没有要求。', - nameField: '名称:{{field}}', - }, build: { - building: '正在构建 · {{app}}…', - built: '已构建 · {{app}}', - builtAndLive: '已搭建并上线 · {{app}}', - appFallback: '你的应用', - addingSampleData: '正在添加示例数据', - group: { - object: '对象', - view: '视图', - dashboard: '仪表盘', - app: '应用', - seed: '示例数据', - dataset: '数据集', - permission: '权限', - other: '其他', - }, - moreArtifacts: '+{{n}} 个', - verifying: '正在检查改动…', - verifyStep: '第 {{n}} 步', - verified: '已检查改动', - // objectstack#32984 — the build card's issues line, in the customer's words. - issuesCount: '{{count}} 处待修复', issuesSummary: '这次搭建有部分内容需要修复后才能使用。回复「修复这些问题」,助手会帮你处理。', - warningsSummary: '应用已搭建好,有几处值得检查。想进一步完善的话,可以问问助手具体是哪些。', - issuesDetails: '技术详情', - // objectstack#32984 — the published draft badge's failed-item count, which was English in every locale. - needsAttention: '{{count}} 项需要处理', - needsAttention_one: '{{count}} 项需要处理', - needsAttention_other: '{{count}} 项需要处理', health: { - sampleRowsLive: '{{count}} 条示例数据已上线', - sampleRowsLive_one: '{{count}} 条示例数据已上线', - sampleRowsLive_other: '{{count}} 条示例数据已上线', - views: '{{count}} 个视图', - views_one: '{{count}} 个视图', - views_other: '{{count}} 个视图', - widgets: '{{count}} 个仪表盘组件', - widgets_one: '{{count}} 个仪表盘组件', - widgets_other: '{{count}} 个仪表盘组件', - seeds: '{{count}} 组示例数据', - seeds_one: '{{count}} 组示例数据', - seeds_other: '{{count}} 组示例数据', - verified: '已核对 {{checks}}', seedFailed: '示例数据未能加载。', }, - unknownPhase: '未知的构建阶段', - nextStepsLead: '接下来可以说:{{steps}}', - nextStepQuote: '「{{step}}」', - draftPosture: '之后的修改先存草稿,在对话里点「发布」即可上线。', - checksPassed: '核对通过 {{passed}}/{{total}}', - }, - changes: { - planTitle: '修改方案 · {{count}} 项', - planTitle_one: '修改方案 · {{count}} 项', - planTitle_other: '修改方案 · {{count}} 项', - saveDraft: '存为草稿', - reviewAndPublish: '查看变更并发布', - undo: '撤销', - undoWithOthers: '撤销(连同另外 {{count}} 项草稿)', - undoWithOthers_one: '撤销(连同另外 {{count}} 项草稿)', - undoWithOthers_other: '撤销(连同另外 {{count}} 项草稿)', - undoConfirm: '撤销会丢弃这个应用包全部 {{total}} 项未发布的草稿,其中 {{count}} 项不属于这次修改。', - undoConfirm_one: '撤销会丢弃这个应用包全部 {{total}} 项未发布的草稿,其中 {{count}} 项不属于这次修改。', - undoConfirm_other: '撤销会丢弃这个应用包全部 {{total}} 项未发布的草稿,其中 {{count}} 项不属于这次修改。', - undoConfirmUnknown: '撤销会丢弃这个应用包里全部未发布的草稿,不只是这次修改。', - undoConfirmAction: '全部撤销', - undoCancel: '取消', - undoing: '正在撤销…', - undone: '已撤销', - undoFailed: '撤销失败', - kind: { - field: '字段', - object: '对象', - view: '视图', - dashboard: '仪表盘', - app: '应用', - seed: '示例数据', - package: '应用包', - }, }, }, chatbotError: { diff --git a/ui/packages/i18n/src/locales/zh-Hant.ts b/ui/packages/i18n/src/locales/zh-Hant.ts index 43b3fc4ab87..7b6c60bea92 100644 --- a/ui/packages/i18n/src/locales/zh-Hant.ts +++ b/ui/packages/i18n/src/locales/zh-Hant.ts @@ -2552,21 +2552,7 @@ const zhHant = { }, ai: { pendingDrafts: { - // objectstack#34610 — the line points to the shell's draft bar and shows a publish receipt. - publishFromBar: '有 {{count}} 項未釋出的改動,請在頂部的草稿欄釋出。', - publishFromBar_one: '有 {{count}} 項未釋出的改動,請在頂部的草稿欄釋出。', - publishFromBar_other: '有 {{count}} 項未釋出的改動,請在頂部的草稿欄釋出。', - showDraftToPublish: '有 {{count}} 項未釋出的改動,開啟草稿檢視並發布。', - showDraftToPublish_one: '有 {{count}} 項未釋出的改動,開啟草稿檢視並發布。', - showDraftToPublish_other: '有 {{count}} 項未釋出的改動,開啟草稿檢視並發布。', - showDraft: '檢視草稿', - receipt: '已釋出,改動已生效。', - dismissReceipt: '關閉', count: '有 {{count}} 項改動尚未釋出——使用者還看不到。', - publish: '釋出', - published: '全部待發布改動已生效。', - failed: '釋出失敗。', - publishedWithFindings: '已釋出,但執行環境探針發現問題:{{detail}}', }, usage: { title: 'AI 用量', @@ -2592,31 +2578,6 @@ const zhHant = { share: '分享', shareTitle: '分享此對話', shareDisabledTitle: '開始對話後即可分享', - buildDoctor: '構建診斷', - buildDoctorTitle: '構建診斷 — 實際生效了哪些變更?', - buildDoctorDisabledTitle: '請先發送一條訊息', - buildDoctorDrawer: { - description: '智慧體聲稱的變更與實際已生效的內容對照。只讀診斷。', - reconciling: '正在核對…', - notAvailable: '不可用——未找到該對話,或你沒有訪問權限。', - untitled: '(無標題)', - summary: '{{turns}} 輪 · {{messages}} 條訊息 · {{tokens}} tok · LLM {{seconds}} 秒', - allLive: '全部 {{count}} 項嘗試的變更均已生效——沒有丟失。', - discrepancies: '{{count}} 處不一致——對話中所說的與實際生效的內容不符。', - orphanedTitle: '已提議但從未應用', - orphanedHint: '智慧體提議了確認卡片,但之後沒有任何一輪應用它——該變更被靜默丟棄。', - missingTitle: '聲稱已應用但缺失', - missingHint: '工具結果稱已應用,但該產物並未在 sys_metadata 中生效。', - toolErrorsTitle: '工具錯誤', - toolErrorsHint: '構建期間返回錯誤的工具呼叫。', - verifyTitle: '構建檢查(verify_build)', - yourApp: '你的應用:', - noIssues: '0 個問題', - issueCount: '{{count}} 個問題', - platformNoise: '已隱藏 {{count}} 條平台 sys_* 發現', - pendingActions: '待處理操作', - timeline: '時間線({{count}})', - }, newChat: '新對話', searchChats: '搜尋對話…', noChatsYet: '暫無對話', @@ -2638,29 +2599,15 @@ const zhHant = { liveCanvasLive: '執行預覽 · {{app}}', loadingAgents: '正在載入助手…', askAnything: '輸入你的問題…', - askOrChangeApp: '問問資料,或讓我改改這個應用…', - describeAppToBuild: '描述你想搭建的應用,或要改的地方…', emptyTitle: '開始對話', emptyDescription: '可以直接提問,助手會結合當前應用上下文提供幫助。', switchAssistant: '切換助手', chooseAgent: '選擇助手…', empty: { - build: { - title: '用 AI 搭建', - description: '用自然語言描述一個應用 —— 我會起草物件、介面和示例資料,隨後你審閱並發布。', - }, ask: { title: '向你的資料提問', description: '針對你的記錄提問 —— 在你有權訪問的資料範圍內進行計數、列舉和彙總。', }, - editApp: { - title: '正在編輯「{{app}}」', - titleGeneric: '編輯此應用', - description: '想改點什麼?我會就地修改這個應用 —— 加欄位、物件、檢視或儀表盤,或調整已有內容。', - // objectstack#34608 — the builder's empty state names both halves: data questions and changes. - askOrChangeDescription: - '問資料,或者讓我改這個應用 —— 可以問記錄的計數、列表和彙總,也可以告訴我要改什麼,我會就地修改:欄位、物件、檢視或儀表盤。', - }, }, clearConversation: '清空', sendHint: '傳送', @@ -2672,9 +2619,6 @@ const zhHant = { toolFailed: '失敗', toolDetailsHidden: '已隱藏工具引數和原始結果,僅保留過程摘要。', toolDenyReason: '操作員已在對話中拒絕', - builderHandoffTitle: '在構建器中搭建', - builderHandoffOpen: '在構建器中開啟 →', - builderHandoffSuperseded: '已有更新的請求', recordWriteCreateTitle: '新建{{object}}', recordWriteUpdateTitle: '修改{{object}}', recordWriteConfirm: '確認', @@ -2721,43 +2665,10 @@ const zhHant = { stopResponse: '停止生成', trace: '除錯 trace', viewTrace: '檢視除錯 trace', - // 搭建流程的草稿與「方案預覽」確認卡片(AiChatPage /ai/build)。 - // 與 ConsoleFloatingChatbot 的 locale 物件保持一致,兩個 AI 介面文案統一。 - nextSteps: '下一步', - publishDrafts: '釋出', - publishOk: '已釋出,物件已生效。', - seedWarn: '已釋出,但部分示例資料未能載入。', - openBuiltApp: '開啟應用', - viewBuiltAppInStudio: '在 Studio 中檢視', - previewDraft: '預覽', previewApp: '預覽應用', resizeSplit: '調整對話與預覽的寬度', hideChats: '隱藏對話列表', showChats: '顯示對話列表', - planTitle: '方案預覽', - planQuestions: '搭建前請確認', - planAssumptions: '假設', - planApproveHint: '回覆以確認或調整該方案。', - planApprove: '開始搭建', - planAdjust: '調整方案', - // The two messages the "開始搭建" button SENDS (not the label above) must - // match the cloud confirm gate's APPROVAL_RE (service-ai-studio - // confirm-gate.ts), or the agent re-proposes instead of building and the - // button looks inert. The gate anchors Chinese approval on 確認 (or - // 直接搭建) — a bare "…搭建吧" does NOT match. Keep these 確認-anchored. - // planApproveMessage: gate-only, read from zh-Hans (GATE_ONLY_KEYS, scripts/zh-hant.mjs). - // planApproveDefaultsMessage: gate-only, read from zh-Hans (GATE_ONLY_KEYS, scripts/zh-hant.mjs). - // planAnswerMessage: gate-only, read from zh-Hans (GATE_ONLY_KEYS, scripts/zh-hant.mjs). - // planExtendExistingMessage: gate-only, read from zh-Hans (GATE_ONLY_KEYS, scripts/zh-hant.mjs). - // planBuildNewAppMessage: gate-only, read from zh-Hans (GATE_ONLY_KEYS, scripts/zh-hant.mjs). - changesTitle: '確認改動', - changesConfirmed: '已確認', - changesConfirm: '確認修改', - changesConfirmHint: '回覆以確認或調整該改動。', - changesApplying: '應用中…', - changesApplied: '已生效', - changesDrafted: '已暫存為草稿', - changesFailed: '未生效', discussing: '正在看:{{target}}', focus: { pin: '釘住這條記錄,換頁後仍問它', @@ -2767,27 +2678,14 @@ const zhHant = { switchAccept: '改為問它', switchDecline: '不用', }, - // changesConfirmMessage: gate-only, read from zh-Hans (GATE_ONLY_KEYS, scripts/zh-hant.mjs). - changeVerb: { - createObject: '新建物件', - addField: '新增欄位', - modifyField: '修改欄位', - deleteField: '刪除欄位', - createMetadata: '新建', - updateMetadata: '修改', - createSeed: '生成示例資料', - createPackage: '新建應用包', - }, justNow: '剛剛', minutesAgo: '{{count}} 分鐘前', hoursAgo: '{{count}} 小時前', daysAgo: '{{count}} 天前', agentLabels: { ask: '提問', - build: '構建', // 舊鍵保留,相容外部覆蓋。 dataChat: '智慧助手', - metadataAssistant: '中繼資料開發助手', }, suggestions: { dataChat: { @@ -2795,42 +2693,11 @@ const zhHant = { recentRecords: '幫我列出最近建立的 5 條記錄。', recordCounts: '統計每個物件的記錄數。', }, - // cloud#1984 — these five chips are the maker's own recommendations, so - // they may only ask for what ADR-0112 v1 BUILDS: objects, fields, views - // (grid/kanban/calendar/gallery), pages, dashboards and sample data. No - // wording that promises autonomous behaviour (alert / remind / notify / - // automate / status workflow) — v1 has no flows, actions or schedules, and - // the model silently degrades such a request into a board or a filtered - // view, so the chip would promise an alert and deliver a page. REVERT to - // the automation wording when ADR-0112 v2 re-adds flows and actions. - metadataAssistant: { - buildCrm: '幫我搭建一個 CRM:客戶、聯絡人、商機,以及一個按階段彙總商機金額的儀表盤。', - buildApp: '做一個專案管理應用:專案、任務(負責人、截止日期),按狀態分組的看板,以及按截止日期的日曆檢視。', - buildFlow: '設計一個工單系統:工單、優先順序、狀態(下拉),以及按狀態分組的看板。', - buildInventory: '做一個庫存管理應用:商品、庫存量、供應商,並用一個檢視篩出低於安全庫存的商品。', - buildRecruiting: '做一個招聘跟蹤應用:候選人、在招崗位、面試階段欄位,以及按階段分組的看板。', - }, generic: { help: '你可以幫我做什麼?', availableObjects: '列出可用的資料物件。', recentActivity: '總結我的最近動態。', }, - // objectui#7709 — the edit-mode starters, shown when the maker is bound - // to an EXISTING app (`?package=`). Same rule as the five above: they - // may only ask for what ADR-0112 v1 BUILDS. The fourth chip used to be - // `addAutomation` ("an approval, a status flow, or a notification") and - // every capability it named is refused by v1 (cloud#1956 / PR #1970), so - // it now asks for sample data — `seed` IS on v1's whitelist, and having - // no data is what an existing app most often lacks. REVERT: when - // ADR-0112 v2 re-adds flows and actions, THIS chip's automation wording - // comes back as `addAutomation`; the retired string is pinned for every - // pack in `packages/i18n/src/__tests__/makerEditChips-v1-scope-7709.test.ts`. - editApp: { - addField: '給某個物件加一個欄位。', - addObject: '新增一個物件,並關聯到已有物件。', - addDashboard: '加一個展示關鍵指標的儀表盤。', - addSampleData: '給現有物件補一批貼近真實的示例資料,好拿去演示。', - }, }, // objectui#3546 slice four — the AI console surfaces: the /ai chat page's app switcher, // connection banner and plan/publish cards, the ChatDock chrome, and the @@ -2838,31 +2705,9 @@ const zhHant = { // `console.ai.group.${key}` (ConversationsSidebar), enumerated from the // ConversationGroupKey union — all five members, no wildcard. collapseToDock: '收起到側邊欄', - switchApp: '切換應用', - switchAppLabel: '按應用檢視搭建對話', - newApp: '新建應用', connectionWaiting: '正在等待伺服器…', connectionStalled: '仍在處理…', connectionOffline: '連線已斷開 — 正在重新連線…', - designingPlan: '正在設計你的應用…', - designingPlanHint: { - data: '正在梳理你要跟蹤的資料…', - objects: '正在設計物件及其欄位…', - relations: '正在關聯相關記錄…', - lookups: '正在設定關係與關聯查詢…', - views: '正在規劃介面與檢視…', - forms: '正在排布表單與列表…', - defaults: '正在新增合理的預設值與校驗…', - dashboard: '正在勾畫用於跟蹤的儀表盤…', - review: '正在複核整體結構是否自洽…', - finalize: '正在彙總方案…', - }, - planBuilding: '正在搭建…', - planBuilt: '已搭建', - planDeferred: '尚未搭建', - planReady: '方案已就緒。現在就開始搭建,或者告訴我需要調整什麼。', - published: '已釋出', - publishFailed: '釋出失敗', unavailableTitle: 'AI 助手不可用', unavailableDescription: '當前部署未啟用 AI 助手。其他功能一切正常。', unavailableError: '無法連線 AI 服務。它可能暫時離線 — 請重試,或返回首頁。', @@ -4773,18 +4618,6 @@ const zhHant = { derivedAiAccess: '已開啟 AI 訪問', }, }, - excelImport: { - noImportableFields: '該物件沒有可匯入的欄位。', - schemaReadFailed: '無法讀取物件結構。', - imported: '已把 {{count}} 行真實資料匯入「{{object}}」。', - imported_one: '已把 {{count}} 行真實資料匯入「{{object}}」。', - imported_other: '已把 {{count}} 行真實資料匯入「{{object}}」。', - importFrom: '把真實資料匯入自', - into: '到', - opening: '開啟中…', - importAction: '匯入', - dismiss: '忽略', - }, cloudWorkspaceTimezoneNotice: { seeded: '環境時區在建立時已按你的瀏覽器設為 {{zone}},可在「設定 → 本地化」中修改。', }, @@ -5009,122 +4842,17 @@ const zhHant = { failed: '失敗', }, phase: { - build: '搭建', - design: '設計方案', stepCount: '{{count}} 步', stepCount_one: '{{count}} 步', stepCount_other: '{{count}} 步', expand: '展開步驟', collapse: '收起步驟', }, - plan: { - countObjects: '{{count}} 個物件', - countObjects_one: '{{count}} 個物件', - countObjects_other: '{{count}} 個物件', - countViews: '{{count}} 個檢視', - countViews_one: '{{count}} 個檢視', - countViews_other: '{{count}} 個檢視', - countDashboards: '{{count}} 個儀表盤', - countDashboards_one: '{{count}} 個儀表盤', - countDashboards_other: '{{count}} 個儀表盤', - countSeedData: '示例資料', - extendTarget: '新增到現有應用:{{app}}', - awaitingConfirm: '等待確認', - // objectstack#32984 — the plan card's build states. - confirmed: '已確認', - buildFailed: '未搭建成功 · 沒有建立任何內容', - iterateOrNew: { - question: '這個方案和你已有的應用「{{app}}」重疊。要在它上面繼續完善,還是另建一個獨立應用?', - questionUnnamed: '這個方案和你已有的一個應用重疊。要在那個應用上繼續完善,還是另建一個獨立應用?', - extend: '在「{{app}}」上繼續完善', - buildNew: '另建一個獨立應用', - replyHint: '回覆告訴我選哪一個。', - }, - objectsAndFields: '物件與欄位', - views: '檢視', - suggestedField: '補充', - suggestedFieldLegend: '標「{{mark}}」的欄位是 AI 自行補充的,你沒有要求。', - nameField: '名稱:{{field}}', - }, build: { - building: '正在構建 · {{app}}…', - built: '已構建 · {{app}}', - builtAndLive: '已搭建並上線 · {{app}}', - appFallback: '你的應用', - addingSampleData: '正在新增示例資料', - group: { - object: '物件', - view: '檢視', - dashboard: '儀表盤', - app: '應用', - seed: '示例資料', - dataset: '資料集', - permission: '權限', - other: '其他', - }, - moreArtifacts: '+{{n}} 個', - verifying: '正在檢查改動…', - verifyStep: '第 {{n}} 步', - verified: '已檢查改動', - // objectstack#32984 — the build card's issues line, in the customer's words. - issuesCount: '{{count}} 處待修復', issuesSummary: '這次搭建有部分內容需要修復後才能使用。回覆「修復這些問題」,助手會幫你處理。', - warningsSummary: '應用已搭建好,有幾處值得檢查。想進一步完善的話,可以問問助手具體是哪些。', - issuesDetails: '技術詳情', - // objectstack#32984 — the published draft badge's failed-item count, which was English in every locale. - needsAttention: '{{count}} 項需要處理', - needsAttention_one: '{{count}} 項需要處理', - needsAttention_other: '{{count}} 項需要處理', health: { - sampleRowsLive: '{{count}} 條示例資料已上線', - sampleRowsLive_one: '{{count}} 條示例資料已上線', - sampleRowsLive_other: '{{count}} 條示例資料已上線', - views: '{{count}} 個檢視', - views_one: '{{count}} 個檢視', - views_other: '{{count}} 個檢視', - widgets: '{{count}} 個儀表盤元件', - widgets_one: '{{count}} 個儀表盤元件', - widgets_other: '{{count}} 個儀表盤元件', - seeds: '{{count}} 組示例資料', - seeds_one: '{{count}} 組示例資料', - seeds_other: '{{count}} 組示例資料', - verified: '已核對 {{checks}}', seedFailed: '示例資料未能載入。', }, - unknownPhase: '未知的構建階段', - nextStepsLead: '接下來可以說:{{steps}}', - nextStepQuote: '「{{step}}」', - draftPosture: '之後的修改先存草稿,在對話裡點「釋出」即可上線。', - checksPassed: '核對通過 {{passed}}/{{total}}', - }, - changes: { - planTitle: '修改方案 · {{count}} 項', - planTitle_one: '修改方案 · {{count}} 項', - planTitle_other: '修改方案 · {{count}} 項', - saveDraft: '存為草稿', - reviewAndPublish: '檢視變更並發布', - undo: '撤銷', - undoWithOthers: '撤銷(連同另外 {{count}} 項草稿)', - undoWithOthers_one: '撤銷(連同另外 {{count}} 項草稿)', - undoWithOthers_other: '撤銷(連同另外 {{count}} 項草稿)', - undoConfirm: '撤銷會丟棄這個應用包全部 {{total}} 項未釋出的草稿,其中 {{count}} 項不屬於這次修改。', - undoConfirm_one: '撤銷會丟棄這個應用包全部 {{total}} 項未釋出的草稿,其中 {{count}} 項不屬於這次修改。', - undoConfirm_other: '撤銷會丟棄這個應用包全部 {{total}} 項未釋出的草稿,其中 {{count}} 項不屬於這次修改。', - undoConfirmUnknown: '撤銷會丟棄這個應用包裡全部未釋出的草稿,不只是這次修改。', - undoConfirmAction: '全部撤銷', - undoCancel: '取消', - undoing: '正在撤銷…', - undone: '已撤銷', - undoFailed: '撤銷失敗', - kind: { - field: '欄位', - object: '物件', - view: '檢視', - dashboard: '儀表盤', - app: '應用', - seed: '示例資料', - package: '應用包', - }, }, }, chatbotError: { diff --git a/ui/packages/i18n/src/namespaces/studio/en.ts b/ui/packages/i18n/src/namespaces/studio/en.ts index 959f7cd4da0..8b5e91143ee 100644 --- a/ui/packages/i18n/src/namespaces/studio/en.ts +++ b/ui/packages/i18n/src/namespaces/studio/en.ts @@ -2838,9 +2838,6 @@ const STUDIO_EN: Record = { 'engine.studio.access.bannerPair': 'This app’s and {package}’s objects · live on save', // objectstack#35018 — the open set's origin in the builder's words (the Studio title note). 'engine.studio.access.origin.app': 'Included with the app', - // objectstack#35018 — the word before the open item's label on the copilot's "Viewing" line. - 'engine.studio.copilot.subject.access': 'Access', - 'engine.studio.copilot.subject.flow': 'Flow', 'engine.studio.access.bannerTitlePair': 'This permission set is part of the customization of {package}, so {package}’s objects are listed as well as this app’s, and saving changes only these grants — grants from other apps stay as they are. Changes go live when you press Save in the top bar.', // objectui#11781 — a read-only package saves no draft; objectui#12453 makes this the header link's title. @@ -3523,18 +3520,11 @@ const STUDIO_EN: Record = { // principal who may enter Studio may open (objectstack#37565). 'engine.studio.notFound.allMetadata': 'Open organization flows', 'engine.studio.notFound.pillar': 'This page does not exist. Studio has no "{pillar}" section; pick Data, Automations, Interfaces, Access or All metadata above.', - 'engine.studio.aiCopilot': 'AI Assistant', - // objectui#12725 — the Studio right slot: properties OR the copilot. + // objectui#12725 — the Studio right slot (the properties panel). 'engine.studio.slot.label': 'Right panel', - 'engine.studio.slot.switchHint': 'Switch with ⌘. (Ctrl+.)', 'engine.studio.slot.collapse': 'Hide the right panel', 'engine.studio.slot.expand': 'Show the right panel', - 'engine.studio.slot.backToChat': 'Back to the conversation', - 'engine.studio.slot.planPending': 'a plan awaits your approval', - 'engine.studio.slot.pendingCount': '{count} awaiting your approval', - 'engine.studio.slot.openFullPage': 'Open full page', - // objectstack#34725 — the slot header's History button and its resize handle. - 'engine.studio.slot.history': 'History', + // objectstack#34725 — the slot's resize handle. 'engine.studio.slot.resize': 'Resize the right panel', // objectstack#34725 — the line over the Data canvas while the AI assistant's drafts are on it. 'engine.studio.copilotChanges.lineOne': 'The AI assistant just made {count} change', diff --git a/ui/packages/i18n/src/namespaces/studio/zh.ts b/ui/packages/i18n/src/namespaces/studio/zh.ts index 779a1a3fa49..2b773a9b910 100644 --- a/ui/packages/i18n/src/namespaces/studio/zh.ts +++ b/ui/packages/i18n/src/namespaces/studio/zh.ts @@ -2537,9 +2537,6 @@ const STUDIO_ZH: Record = { 'engine.studio.access.bannerPair': '本应用及 {package} 对象 · 保存后生效', // objectstack#35018 — the open set's origin in the builder's words (the Studio title note). 'engine.studio.access.origin.app': '随应用提供', - // objectstack#35018 — the word before the open item's label on the copilot's 「正在看」 line. - 'engine.studio.copilot.subject.access': '权限', - 'engine.studio.copilot.subject.flow': '流程', 'engine.studio.access.bannerTitlePair': '这个权限集属于 {package} 的定制,所以除本应用的对象外也列出 {package} 的对象;保存时只改这部分授权,其他应用给出的授权保持不变。改动在点击顶栏「保存」后立即生效。', 'engine.studio.access.bannerTitleReadOnly': @@ -3107,18 +3104,11 @@ const STUDIO_ZH: Record = { 'engine.studio.notFound.packageList': '打开软件包列表', 'engine.studio.notFound.allMetadata': '打开「组织流程」', 'engine.studio.notFound.pillar': '页面不存在。Studio 没有“{pillar}”这一栏,请在上方选择数据、自动化、界面、权限或全部元数据。', - 'engine.studio.aiCopilot': 'AI 助手', - // objectui#12725 — Studio 右栏:属性或 AI 助手二选一。 + // objectui#12725 — Studio 右栏(属性面板)。 'engine.studio.slot.label': '右栏', - 'engine.studio.slot.switchHint': '⌘.(Ctrl+.)切换', 'engine.studio.slot.collapse': '收起右栏', 'engine.studio.slot.expand': '展开右栏', - 'engine.studio.slot.backToChat': '回到对话', - 'engine.studio.slot.planPending': '方案待确认', - 'engine.studio.slot.pendingCount': '{count} 项待确认', - 'engine.studio.slot.openFullPage': '在完整页面中打开', - // objectstack#34725 — 右栏标题栏的「历史」按钮与拖宽手柄。 - 'engine.studio.slot.history': '历史', + // objectstack#34725 — 右栏的拖宽手柄。 'engine.studio.slot.resize': '调整右栏宽度', // objectstack#34725 — 画布上方那条提示:AI 助手的草稿改动落在画布上时出现。 'engine.studio.copilotChanges.lineOne': 'AI 刚改了 {count} 处', diff --git a/ui/packages/plugin-chatbot/src/ChatbotEnhanced.tsx b/ui/packages/plugin-chatbot/src/ChatbotEnhanced.tsx index 55bb95ef939..69823bacb6d 100644 --- a/ui/packages/plugin-chatbot/src/ChatbotEnhanced.tsx +++ b/ui/packages/plugin-chatbot/src/ChatbotEnhanced.tsx @@ -36,7 +36,7 @@ import { } from '@object-ui/components'; import { SchemaRenderer } from '@object-ui/react'; import { formatNumber, useObjectTranslation, useSafeTranslate } from '@object-ui/i18n'; -import { AlertCircle, ArrowRight, Copy, Check, RefreshCw, CornerDownLeft, Bot, Eye, GitCompareArrows, Rocket, Clock3, CheckCircle2, ChevronDown, XCircle, Loader2, ShieldCheck, TriangleAlert, ClipboardList, HelpCircle, Info, Table2, WifiOff, Sparkles, Hourglass, Trash2 } from 'lucide-react'; +import { AlertCircle, Copy, Check, RefreshCw, CornerDownLeft, Bot, Clock3, CheckCircle2, ChevronDown, XCircle, Loader2, TriangleAlert, Table2, WifiOff, Sparkles, Hourglass, Trash2 } from 'lucide-react'; import type { ChatStatus } from 'ai'; import { humanizeToolName, @@ -65,7 +65,6 @@ import { import { ListLinkContext, RecordLinkContext } from './recordLink'; import type { OpenListLink } from './recordLink'; import { isHitlContinuation } from './hitlContinuation'; -import type { PublishHealth, PublishOutcome } from './publishHealth'; import { PromptInput, PromptInputBody, @@ -103,23 +102,10 @@ import { Source, } from './elements/sources'; import { - parseResultEnvelope, - detectAuthoringVerdict, - detectBuiltAppPackage, - detectBuildChecklist, - detectPublishedBuildReview, - buildProgressFromDraftReview, detectPackageRemovedResult, - supersededPlanIds, - type BuildResultChecklist, - type DraftReview, - type ProposedChanges, - type ProposedPlan, - type ProposedPlanCard, type RecordWrite, type SampleDataCleanup, type PackageRemoval, - type ReplayOutcome, } from './mapMessages'; import type { DatasetProvenance, ObjectQuerySource, RecordCitationParsed } from '@objectstack/spec/ai'; import { AnswerSourceBlock } from './AnswerSource'; @@ -153,22 +139,6 @@ export interface ChatbotEnhancedMessage { sources?: ChatSource[]; /** Optional backend trace id (e.g. `ai_traces.id`) for debugging. */ traceId?: string; - /** - * Live build progress from a long-running tool (apply_blueprint), lifted from - * the stream's reconciled `data-build-progress` part. When present, the chat - * renders a growing "build tree" so the user watches the app take shape - * instead of staring at a thinking spinner. - */ - buildProgress?: ChatBuildProgress; - /** - * Live blueprint-DESIGN progress from the long, atomic `propose_blueprint` - * call, lifted from the stream's reconciled `data-blueprint-progress` part. - * When present, the chat renders a "Designing…" panel whose object chips - * appear one-by-one — upgrading the purely-presentational rotating-hint - * placeholder to real, event-driven progress. Transient (never persisted): - * on reload the authoritative "Proposed plan" card is the record instead. - */ - blueprintProgress?: ChatBlueprintProgress; /** * Charts to render inline in the assistant bubble, lifted from the stream's * `data-chart` parts (emitted by the `visualize_data` tool via @@ -223,83 +193,6 @@ export interface ChatChart { textOffset?: number; } -/** - * A build-progress frame's phase: `@objectstack/spec/ai`'s closed - * `BuildProgressPhase` vocabulary, plus `unknown` for a value outside it, which - * is surfaced as a warning — never as "Building" (objectui#11988). Spelled out - * rather than imported so the published typings need no newer spec floor; - * `buildVerify-11988.test.tsx` asserts at compile time that it equals the - * spec's union, both ways. - */ -type ChatBuildPhase = 'structure' | 'data' | 'verify' | 'done' | 'unknown'; - -/** A reconciled snapshot of an in-flight app build (apply_blueprint). */ -export interface ChatBuildProgress { - /** Coarse phase: drafting structure, generating sample data, or finished. */ - phase: ChatBuildPhase; - /** Human label for the app being built (for the panel header). */ - appLabel?: string; - /** - * Artifacts drafted so far, cumulative. `label` is the artifact's display - * label when the frame carries one; the panel shows it in place of `name`. - */ - items: Array<{ type: string; name: string; label?: string }>; - /** Count of artifacts done and the rough total (for the progress bar). */ - done: number; - total: number; - /** - * Monotonic emit counter from the server. Bumps on every progress update — - * including the keep-alive heartbeats sent during long, quiet seed-generation - * awaits — so it's the reliable "a fresh byte just arrived" signal the build - * panel keys its liveness off (content fields stay identical across a - * heartbeat). Absent from older runtimes. - */ - seq?: number; - /** - * The post-apply verification loop, read from its own `build-verify` part - * beside the tree (objectui#11988): `verify` while a hop runs, `done` once - * the loop exits. `hop` and `tool` are the spec frame's own fields. - */ - verify?: { phase: ChatBuildPhase; hop?: number; tool?: string }; -} - -/** - * A reconciled snapshot of an in-flight blueprint DESIGN (`propose_blueprint`). - * The plan-design step is a long, atomic LLM request; the server now streams a - * reconciled `data-blueprint-progress` part as the schema takes shape, so the - * chat can show objects appearing one-by-one instead of a static spinner. - * Mirrors `ChatBuildProgress` (apply_blueprint's BUILD progress) but for the - * pre-build PLAN — it is superseded by the authoritative "Proposed plan" card - * the instant the tool result lands. - */ -export interface ChatBlueprintProgress { - /** - * Coarse phase. `designing` while the plan is being drafted; `done` once the - * authoritative blueprint has arrived (on the `propose_blueprint` tool - * result). Anything unrecognised — including absent — is treated as designing. - */ - phase: 'designing' | 'done'; - /** Human one-liner for the app being designed (revealed progressively). */ - summary?: string; - /** Human label for the new app (absent in extend mode). */ - appLabel?: string; - /** Extend mode: the existing app the new objects would be added into. */ - targetApp?: string; - /** - * Objects surfaced so far, cumulative — they appear one-by-one as the design - * streams. `fields` is the field count for the chip's "· N" suffix. - */ - objects: Array<{ name: string; label?: string; fields?: number }>; - /** Running totals for a compact "N objects · N views · …" line. */ - counts?: { objects?: number; views?: number; dashboards?: number }; - /** - * Monotonic emit counter from the server — the reliable "a fresh byte just - * arrived" liveness signal (advances on keep-alive heartbeats too, where the - * content fields are identical). Absent from older runtimes. - */ - seq?: number; -} - /** * One tool invocation as `` RENDERS it: the AI SDK v6 states * (the three approval states included) plus the render-only keys @@ -355,56 +248,7 @@ export interface ChatbotEnhancedToolInvocation { */ pendingActionId?: string; /** - * ObjectStack ADR-0033 extension. When a metadata-authoring tool stages a - * change as a DRAFT, its result carries `{ status: 'drafted', type, name, … }` - * (or a `drafted: [{type,name}]` batch from `apply_blueprint`). `mapMessages.ts` - * lifts the reviewable targets here so chat UIs can render a "Review N - * change(s)" affordance that opens the designer's review/diff. Nothing is - * live until the human publishes — this is the review entry point. - * - * The shape is `mapMessages.ts`'s `DraftReview`, the type `detectDraftResult` - * returns, referenced rather than repeated: an inline copy of its fields - * drifted the moment `DraftReview` gained the producer's `kind` - * (objectui#10109). - */ - draftReview?: DraftReview; - /** - * ObjectStack extension. `propose_blueprint` returns a PLAN before anything - * is staged (`status: 'blueprint_proposed'`). `mapMessages.ts` lifts the - * reviewable shape here so chat UIs can render a "Proposed plan" card — the - * objects the build will create, the agent's assumptions, and any - * structure-deciding questions — and the user can approve or adjust before - * `apply_blueprint` runs. Nothing is created yet; this is the confirm gate. - * - * The shape is `mapMessages.ts`'s `ProposedPlan`, referenced rather than - * repeated, for the reason `draftReview` above gives (objectui#12724 added - * the field, view and app-label rows to it). - */ - proposedPlan?: ProposedPlan; - /** Granular metadata-change preview (confirm-before-change). Set only - * when a mutating tool returned status:'changes_proposed' — i.e. it was - * NOT yet approved this turn, so nothing changed. Rendered as a 确认修改 card. - * - * The shape is `mapMessages.ts`'s `ProposedChanges`, the type - * `detectProposedChanges` returns, referenced rather than repeated for the - * reason `draftReview` above gives (objectui#12894 added the posture and - * the primary action to it). */ - proposedChanges?: ProposedChanges; - /** - * ADR-0057 P4 — the `ask` agent's structured decline-and-redirect. Set when - * the ask agent called `suggest_builder` (`{ handoff:'build', prompt, - * packageId? }`) because the user asked to author. `mapMessages.ts` lifts the - * handoff here so the chat renders an explicit "Open in Builder →" action that - * opens the build surface seeded with `prompt` — never a silent re-route into - * authoring (ADR-0063). - */ - builderHandoff?: { - prompt: string; - packageId?: string; - }; - /** - * cloud#1658 — the ask agent's `open_record` structured hand-off (the record - * sibling of `builderHandoff`). Rendered as a "打开这条记录 →" action landing + * cloud#1658 — the ask agent's `open_record` structured hand-off. Rendered as a "打开这条记录 →" action landing * on the record the agent already resolved. */ recordHandoff?: { @@ -439,18 +283,6 @@ export interface ChatbotEnhancedToolInvocation { * before the user confirms (the generic Approve / Deny strip is the decision). */ packageRemoval?: PackageRemoval; - /** - * objectui#5695 — the terminal verdict of a confirm-replay (`replay_` - * tool results; cloud `runApprovedProposalReplay`). Rendered as a terminal - * state on the ORIGINAL 确认修改 card — 已生效 / 已暂存为草稿 / 未生效 — so a - * rolled-back publish exists somewhere a USER can see it, independent of - * whether the model narrates it honestly. - * - * The shape is `mapMessages.ts`'s `ReplayOutcome`, referenced rather than - * repeated (objectui#12894 added the applied card of a change saved as a - * draft to it). - */ - replayOutcome?: ReplayOutcome; } export interface ChatSource { @@ -536,20 +368,6 @@ export interface ChatbotLabels { * mid-turn — e.g. "Connection lost — reconnecting…". The honest disconnect cue. */ connectionOfflineLabel?: string; - /** - * Lead-in shown while the build agent is designing a plan (the long, atomic - * `propose_blueprint` call) — e.g. "Designing your app…". Pairs with the live - * timer so the wait reads as deliberate work, not a hang. - */ - designingPlanLabel?: string; - /** - * Rotating "what I'm doing now" hints cycled through during that same - * propose_blueprint wait (the call is a single atomic LLM request with no - * partial stream, so these are presentational reassurance, not live status). - * Defaults to a sensible English set when omitted; pass a localized list to - * override. An empty array disables rotation (only `designingPlanLabel` shows). - */ - designingPlanHints?: string[]; } export type ChatbotProcessVisibility = 'hidden' | 'summary' | 'debug'; @@ -579,21 +397,14 @@ export interface ChatbotEnhancedProps extends React.HTMLAttributes
) : null} - {tool.draftReview && - tool.draftReview.items.length > 0 && - (onReviewDraft || - ((onPublishDrafts || onPreviewDraft) && tool.draftReview.packageId)) ? ( - <> - {/* flex-wrap so the action buttons drop to a new line on a - narrow (mobile) row instead of forcing horizontal scroll. */} -
- {onPublishDrafts && tool.draftReview.packageId ? ( - draftIsPublished ? ( - // Published (auto or manual): a stable status badge, not a - // stale button. Keeps the card honest about lifecycle state. - - - {publishedLabel} - {/* objectstack#32984 — through the pack; it was English in every locale. */} - {tool.draftReview.failedCount - ? ` · ${tCount('chatbot.build.needsAttention', { - count: tool.draftReview.failedCount, - defaultValue: '{{count}} need attention', - })}` - : ''} - - ) : publishFromShellBar ? null : ( - - ) - ) : null} - {onReviewDraft ? ( - - ) : null} - {/* ADR-0037: drafted-app preview — see it as-if-published - without publishing. A draft set that includes an app - previews the app (the canvas previews whole apps). - objectui#12968 (objectstack#24324 ruling A): any other - draft previews too, through `onPreviewDraft`, which - opens the affected surface; it needs the package id, - the app's route segment. Hidden once the package has - no pending drafts (live count when available, else this - session's history). */} - {!draftIsPublished - ? (() => { - const review = tool.draftReview!; - const preview = draftPreviewAction(review.items, review.packageId, review.materialized === true, { - onPreviewDraftApp, - onPreviewDraft, - }); - return preview ? ( - - ) : null; - })() - : null} - {/* ADR-0038 L1 chip: the graph-lint verdict, so the user sees - WHY a build did or didn't auto-publish without reading - tool JSON. Green = referentially clean; amber = blocking - issues, the build stays draft until the agent repairs. */} - {tool.draftReview.verification && !(failureOnChecklist && tool.draftReview.verification.errors > 0) ? ( - tool.draftReview.verification.errors > 0 ? ( - - - {buildIssuesCountLabel(tool.draftReview.verification.errors)} - - ) : ( - - - {verifiedLabel} - - ) - ) : null} - {tool.draftReview.summary ? ( - // min-w-0 + flex-1 so this nowrap summary TRUNCATES within the - // row instead of expanding it past the viewport on mobile - // (#2493 — a flex child needs min-w-0 for `truncate` to bite). - - {tool.draftReview.summary} - - ) : null} -
- {/* ADR-0038 L1 — the findings behind the issues chip. - objectstack#32984 — each finding's `message` / `fix` is - written for the AGENT that repairs the build ('Seed "x" - sets "quote" on none of its 12 row(s) — … Do NOT publish - this seed with the column empty.'), so the card no longer - prints it as its own sentence. It says what the customer - can do, and keeps the findings one click away for whoever - needs them. */} - {tool.draftReview.issues && tool.draftReview.issues.length > 0 ? ( -
- {(() => { - const issues = tool.draftReview!.issues!; - const errorCount = issues.filter((i) => i.severity === 'error').length; - if (errorCount > 0 && failureOnChecklist) return null; - return ( -
0 ? 'text-red-600' : 'text-amber-600', - )} - data-testid="draft-issues-summary" - > - {errorCount > 0 ? ( - - ) : ( - - )} - - {errorCount > 0 - ? tt( - 'chatbot.build.issuesSummary', - 'Some parts of this build need fixing before it is ready. Reply "fix the problems" and the assistant will repair them.', - ) - : tt( - 'chatbot.build.warningsSummary', - 'The build is ready, with a few things worth checking. Ask the assistant what they are if you want to improve them.', - )} - -
- ); - })()} -
- - {tt('chatbot.build.issuesDetails', 'Technical details')} - -
    - {tool.draftReview.issues.map((iss, idx) => ( -
  • - {iss.fix ? `${iss.message} — ${iss.fix}` : iss.message} -
  • - ))} -
-
-
- ) : null} - {/* ADR-0038 L3 — build-health line: what the publish actually - did at runtime. Renders only when the host supplied health - data; "Published" alone never implies "verified". */} - {publishedToolCalls.has(tool.toolCallId) ? ( - - ) : null} - {/* Post-build getting-started checklist — concrete next actions - (make the data yours, refine, automate, publish) so a finished - build isn't a dead end. Backend supplies these as - `nextSteps` on the apply_blueprint result; lifecycle-neutral. */} - {/* objectui#12724 — a whole-app build says its next steps on - the finished build card instead (「接下来可以说」), so - only an incremental edit keeps the list here. */} - {tool.draftReview.nextSteps && - tool.draftReview.nextSteps.length > 0 && - !buildProgressFromDraftReview(tool.draftReview) ? ( -
- {nextStepsLabel} - {tool.draftReview.nextSteps.map((step, idx) => ( -
- → - {step} -
- ))} -
- ) : null} - - ) : null} - {/* Pre-build "Proposed plan" card — propose_blueprint returns a plan - (objects, assumptions, structure-deciding questions) before - anything is staged. Surfacing it as a reviewable card (not a bare - "Completed" step) gives the user the Airtable-style confirm gate: - see what will be built, then approve or adjust. Nothing is live - yet. */} - {/* ADR-0057 P4 — the `ask` agent declined an authoring request and - called `suggest_builder`. Render an explicit "Open in Builder →" - that hands the request to the build surface seeded with the - prompt (ADR-0063 decline-and-redirect — never a silent re-route). */} - {tool.builderHandoff ? ( -
- - - {builderHandoffTitleLabel} - -

{tool.builderHandoff.prompt}

- {(() => { - // #2458 UX#5 — only the LATEST handoff card stays actionable; - // an older (superseded) card's prompt is stale, so its button is - // disabled rather than re-firing an outdated request. - const superseded = - !!latestHandoffToolCallId && tool.toolCallId !== latestHandoffToolCallId; - return ( - - ); - })()} -
- ) : null} {/* cloud#3565 — 「清理示例数据」: what the seed ledger recorded, per table, so the user confirms a list rather than a payload, and that the removal cannot be undone (the maintainer's note on @@ -4628,682 +1930,23 @@ const ChatbotEnhanced = React.forwardRef( className="flex flex-col gap-2 border-t bg-muted/20 px-3 py-2.5" data-testid="record-handoff" > - - - {recordHandoffTitleLabel} - -

- {tool.recordHandoff.label ?? tool.recordHandoff.objectName} - {tool.recordHandoff.reason ? ` — ${tool.recordHandoff.reason}` : ''} -

- -
- ) : null} - {tool.proposedPlan ? ( -
- {/* objectui#12724 — the header names the app the plan builds - (`blueprint.app.label`) and, until the user decides, says - the plan waits for them. */} -
- - - - {tool.proposedPlan.appLabel - ? `${planTitleLabel} · ${tool.proposedPlan.appLabel}` - : planTitleLabel} - - - {onSendMessage && - planBuildStateOf(tool.toolCallId) === 'pending' ? ( - - {planAwaitingLabel} - - ) : null} -
- {(() => { - // objectui#12724 — the producer's sample-data line - // (`planCard.sampleData.line`, 「示例数据 12 条/对象」) takes - // the place of the bare "sample data" count bit. - const plan = tool.proposedPlan!; - const sampleLine = plan.planCard?.sampleData?.line; - const bits = countBitsOf(sampleLine ? { ...plan.counts, seedData: 0 } : plan.counts); - if (sampleLine) bits.push(sampleLine); - return bits.length ? ( - {bits.join(' · ')} - ) : null; - })()} - {tool.proposedPlan.targetApp ? ( - - + {extendChip(tool.proposedPlan.targetApp)} - - ) : null} - {tool.proposedPlan.summary ? ( -

{tool.proposedPlan.summary}

- ) : null} - {tool.proposedPlan.planCard ? ( - // objectui#12724 — the plan card v2 rows, from `planCard`. - - ) : tool.proposedPlan.objects.some((o) => o.fields) ? ( - // objectui#12724 — one row per object with a chip per - // declared field (`blueprint.objects[].fields`). -
- - {planObjectsLabel} - - {tool.proposedPlan.objects.map((o) => ( -
- - {o.label || o.name} - -
- {o.fields ? ( - o.fields.map((f) => ( - - {f.label || f.name} - - )) - ) : o.fieldCount > 0 ? ( - · {o.fieldCount} - ) : null} -
-
- ))} -
- ) : tool.proposedPlan.objects.length > 0 ? ( -
- {tool.proposedPlan.objects.map((o) => ( - - - {o.label || o.name} - {o.fieldCount > 0 ? ( - · {o.fieldCount} - ) : null} - - ))} -
- ) : null} - {(() => { - // objectui#12724 — each view with its intent line: from - // `planCard.views`, or from the envelope's `viewIntents` when - // a producer that predates `planCard` sends only those. - const plan = tool.proposedPlan!; - const intentRows = plan.planCard ? plan.planCard.views : plan.viewIntents; - if (intentRows && intentRows.length > 0) { - return ( -
- - {planViewsLabel} - - {intentRows.map((v) => ( -
- - {v.label ?? v.view} - - - {v.line} - -
- ))} -
- ); - } - // objectui#12724 phase 1 — the views the build creates - // (`blueprint.views`), by name, when no intent line is sent. - return plan.views && plan.views.length > 0 ? ( -
- - {planViewsLabel} - - {plan.views.map((v) => ( -
- · - {v.label || v.name} -
- ))} -
- ) : null; - })()} - {/* Assumptions split into ordinary design notes vs. business - rules the build is explicitly DEFERRING ("待补 / Not yet - built"). The deferred set gets its own labelled, tinted - section with an hourglass so a user can't mistake a - still-to-come rule for delivered behaviour (improvement 2). */} - {(() => { - const { designNotes, deferred } = classifyAssumptions( - tool.proposedPlan!.assumptions, - ); - const posture = tool.proposedPlan!.planCard?.posture; - return ( - <> - {designNotes.length > 0 || posture ? ( - // objectui#12724 — a list, one item per assumption - // (`planCard.assumptions`, else `blueprint.assumptions`), - // then how the build will land (`planCard.posture.line`, - // cloud#2924) as the last item, where the artboard draws it. -
- - {planAssumptionsLabel} - -
    - {designNotes.map((a, idx) => ( -
  • {a}
  • - ))} - {posture ? ( -
  • - {posture.line} -
  • - ) : null} -
-
- ) : null} - {deferred.length > 0 ? ( -
- - - {planDeferredLabel} - - {deferred.map((a, idx) => ( -
- · - {a} -
- ))} -
- ) : null} - - ); - })()} - {tool.proposedPlan.questions.length > 0 ? ( -
- - - {planQuestionsLabel} - - {tool.proposedPlan.questions.map((q, idx) => { - // One-click answer chips when the backend derived options - // for this exact question; otherwise the user types a reply. - const choice = tool.proposedPlan!.questionChoices?.find((c) => c.text === q); - return ( -
-
- ? - {q} -
- {onSendMessage && choice && choice.options.length > 0 ? ( -
- {choice.options.map((opt, oi) => ( - - ))} -
- ) : null} -
- ); - })} -
- ) : null} - {/* One-click confirm gate: "Build it" sends an approval message - (accepting defaults when questions remain), "Adjust" focuses - the input so the user types changes. Falls back to a text hint - when the host hasn't wired message sending. Once this plan's - build has run (issue #432) the actions collapse to a static - "Built" badge so it can't be re-triggered. - objectstack#27480 — an `iterate_or_new` plan has no such - gate: it overlaps an app that already exists, so in place - of the actions it asks whether to keep improving that app - or build a separate one. */} - {tool.proposedPlan.iterateOrNew ? ( - - ) : onSendMessage ? ( - planBuildSettledOrMoving(planBuildStateOf(tool.toolCallId)) ? ( -
- {renderPlanBuildBadge(planBuildStateOf(tool.toolCallId))} -
- ) : ( -
- {renderPlanBuildBadge(planBuildStateOf(tool.toolCallId))} - - - {/* objectui#12724 — the reply door beside the buttons. */} - - {planApproveHintLabel} - -
- ) - ) : ( - - {planApproveHintLabel} - - )} -
- ) : null} - {/* FALLBACK confirm gate — a propose_blueprint that FINISHED but whose - result didn't parse into the rich plan card above (a thin/oddly - shaped envelope, or a prose proposal). Previously this collapsed - into a "Propose blueprint · Completed" chip and the user was left - with the assistant's prose telling them to reply "确认" — no - button, guess-the-phrase. We always give them an explicit, one - click "Build it" / "Adjust" instead. Same approve/adjust handlers - and the same #432 built-state collapse as the structured card. */} - {isUnstructuredBuildProposal(tool) ? ( -
- - - {planTitleLabel} - -

{planReadyLabel}

- {onSendMessage ? ( - planBuildSettledOrMoving(planBuildStateOf(tool.toolCallId)) ? ( -
- {renderPlanBuildBadge(planBuildStateOf(tool.toolCallId))} -
- ) : ( -
- {renderPlanBuildBadge(planBuildStateOf(tool.toolCallId))} - - -
- ) - ) : ( - - {planApproveHintLabel} - - )} -
- ) : null} - {/* Granular confirm-before-change card — a mutating tool that was - not approved this turn returns status:'changes_proposed' (a - preview) instead of committing. Same confirm gate as the plan - card: see the change, then confirm / adjust. Nothing changed - yet. */} - {tool.proposedChanges ? ( -
- {isChangePlanV2(tool.proposedChanges) ? ( - // objectui#12894 — change card v2 (the StudioRailCopilot - // artboard), drawn when the envelope carries cloud#2924's - // posture: 「修改方案 · N 项」, the posture note, one row per - // change. An envelope without it draws the card below, as - // before. - - ) : ( - <> - - - {changesTitleLabel} - - {tool.proposedChanges.summary ? ( -

{tool.proposedChanges.summary}

- ) : null} -
- {tool.proposedChanges.changes.map((c, idx) => ( -
- - {formatChangeRow(c, changeVerbLabels, changeLabelResolvers)} -
- ))} -
- - )} - {(() => { - // objectui#5695 — after 确认修改, the card carries the replay's - // verdict instead of going dark. Terminal states render on - // EVERY surface (incl. the read-only share page): a UI-owned - // failure state is the layer a model cannot narrate over. - const outcome = replayOutcomeByProposalId.get(tool.toolCallId); - if (outcome?.kind === 'published') { - return ( -
- - - {changesAppliedLabel} - -
- ); - } - if (outcome?.kind === 'failed') { - return ( -
- - - {changesFailedLabel} - - {outcome.error ? ( - - {outcome.error} - - ) : null} -
- ); - } - if (outcome?.kind === 'drafted' && outcome.appliedCard) { - // objectui#12894 — the applied card of a change saved as a - // draft (cloud#2924): its title and lines as the producer - // wrote them, 查看变更并发布 and 撤销. - const packageId = outcome.packageId; - const discard = discardByToolCall.get(tool.toolCallId); - // objectui#12968 — the items this replay drafted preview - // through the same door the drafted result's Preview uses. - const preview = draftPreviewAction(outcome.items ?? [], packageId, false, { - onPreviewDraftApp, - onPreviewDraft, - }); - return ( - onReviewDrafts(packageId) : undefined} - onPublish={ - !publishFromShellBar && !onReviewDrafts && onPublishDrafts && packageId - ? () => void handlePublishDrafts(packageId) - : undefined - } - publishLabel={publishDraftsLabel} - onDiscard={ - onDiscardDrafts && packageId - ? () => void requestDiscardDrafts(tool.toolCallId, packageId, outcome.draftState) - : undefined - } - onDiscardConfirm={ - onDiscardDrafts && packageId - ? () => void runDiscardDrafts(tool.toolCallId, packageId) - : undefined - } - onDiscardCancel={() => setDiscardState(tool.toolCallId, undefined)} - /> - ); - } - if (outcome?.kind === 'drafted') { - const preview = draftPreviewAction(outcome.items ?? [], outcome.packageId, false, { - onPreviewDraftApp, - onPreviewDraft, - }); - return ( -
- - - {changesDraftedLabel} - - {onPublishDrafts && outcome.packageId ? ( - - ) : null} - {preview ? ( - - ) : null} -
- ); - } - // objectui#7253 — the confirm never reached the server: the AI - // quota guardrail refused it with a 429. No replay envelope - // will ever arrive for it, so this state is UI-owned, and it - // is terminal rather than a rollback to the buttons: clicking - // Confirm again buys the same refusal. Ranked below the three - // server verdicts above — a real outcome always outranks a - // client-side refusal. - if (quotaBlockedChanges.has(tool.toolCallId)) { - return ( -
- - - {changesFailedLabel} - - -
- ); - } - const applying = - outcome?.kind === 'applying' || confirmPendingIds.has(tool.toolCallId); - if (applying) { - return ( -
- - - {changesApplyingLabel} - -
- ); - } - if (!onSendMessage) { - return ( - - {changesConfirmHintLabel} - - ); - } - if (confirmedChangeIds.has(tool.toolCallId)) { - // Legacy fallback for hosts whose replay envelope predates - // the outcome fields: a later same-tool commit still - // collapses the card, just without a verdict. - return ( -
- - - {changesConfirmedLabel} - -
- ); - } - // objectui#10965 — `update_metadata` returns `changes_proposed` - // mid-turn, so this card renders while the proposing turn is - // still streaming and being stored. Its actions wait on the - // same `planActionsLocked` the plan card uses (objectui#10925). - return ( -
- - -
- ); - })()} + + + {recordHandoffTitleLabel} + +

+ {tool.recordHandoff.label ?? tool.recordHandoff.objectName} + {tool.recordHandoff.reason ? ` — ${tool.recordHandoff.reason}` : ''} +

+
) : null} @@ -5398,36 +2041,12 @@ const ChatbotEnhanced = React.forwardRef( // draws no bubble: live, after a reload, or on a shared // transcript. The model still received it. if (isUser && isHitlContinuation(message.content)) return null; - // One plan card per build turn: the newest plan, the one the - // runtime builds; earlier plans of the turn draw as steps. - const tools = (message.toolInvocations ?? []).map((tool) => - withoutSupersededPlan(tool, supersededPlans), - ); + const tools = message.toolInvocations ?? []; const reasoning = message.reasoning?.trim(); const sources = message.sources ?? []; - const buildProgress = !isUser ? message.buildProgress : undefined; - // The live "Designing…" panel is a hand-off affordance: it - // yields to the authoritative "Proposed plan" card the instant - // the propose_blueprint result lands. Suppress it once any tool - // on this turn carries a structured plan — which also makes it a - // no-op on reload (only the persisted plan card exists then). - const blueprintProgress = - !isUser && !tools.some((t) => Boolean(t.proposedPlan)) - ? message.blueprintProgress - : undefined; const summaryTools = !isUser && processVisibility === 'summary' - ? tools.filter( - (tool) => - !shouldRenderDetailedTool(tool) && - // While the live design panel is up it already - // represents the running propose_blueprint, so don't - // also surface that tool's rotating-hint row in the - // activity strip (the panel supersedes the - // placeholder). With no events the row stays and shows - // the placeholder as before. - !(blueprintProgress && tool.toolName === 'propose_blueprint'), - ) + ? tools.filter((tool) => !shouldRenderDetailedTool(tool)) : []; const detailedTools = !isUser && processVisibility === 'debug' @@ -5448,7 +2067,7 @@ const ChatbotEnhanced = React.forwardRef( // thinking indicator instead of dead air. Covers the ask-decline // wait (tool-call latency before `suggest_builder` lands): no // prose, no rendered tool row (summary chip / detailed card), no - // shown reasoning (only surfaced in debug), no build/design panel. + // shown reasoning (only surfaced in debug). const reasoningVisible = processVisibility === 'debug' && Boolean(reasoning); const isEmptyAssistantStreaming = !isUser && @@ -5456,67 +2075,16 @@ const ChatbotEnhanced = React.forwardRef( !hasVisibleProse && summaryTools.length === 0 && detailedTools.length === 0 && - !reasoningVisible && - !buildProgress && - !blueprintProgress; // a streaming design/build shows its panel, not the dots + !reasoningVisible; // objectui#10899 — does this turn already SHOW its activity (a // tool row, a build/design panel)? Then the quiet 执行过程 note // a hydrated tool-call placeholder turn falls back to says // nothing the row above it does not, and a reloaded multi-step // build printed it under every step. The note stays for a // placeholder turn with nothing else on screen (#772). - // objectui#12724 — the whole-app build's draft tool (its - // envelope names the package and the `nextSteps`), and whether - // the build is live: the envelope itself says `published` (an - // auto-publish environment), or this chat published the draft. - const builtAppDraft = tools.find( - (tool) => - tool.draftReview?.packageId && - tool.draftReview.kind !== 'edit' && - tool.draftReview.items?.some((i) => i.type === 'app'), - ); - // An auto-publish environment's envelope says `published` and - // lifts no draft review, so its package is read off the - // envelope itself (the reader the page's binding uses). - const publishedBuild = tools.find( - (tool) => - parseResultEnvelope(tool.result)?.status === 'published' && - Boolean(detectBuiltAppPackage(tool.result)), - ); - const builtPackageId = - builtAppDraft?.draftReview?.packageId ?? - (publishedBuild ? detectBuiltAppPackage(publishedBuild.result) : undefined); - // objectstack#25887 — the result card's next steps ride - // the published envelope too, so a published build (a replayed - // one included) draws them as a drafted build does. - const builtNextSteps = - builtAppDraft?.draftReview?.nextSteps ?? - (publishedBuild ? detectPublishedBuildReview(publishedBuild.result)?.nextSteps : undefined); - // objectui#12724 — the result card's checklist: the LAST one - // the turn produced, so a `verify_build` that re-measured the - // build after a repair supersedes `apply_blueprint`'s. - let buildChecklist: BuildResultChecklist | undefined; - if (buildProgress?.phase === 'done') { - for (let i = tools.length - 1; i >= 0 && !buildChecklist; i--) { - buildChecklist = detectBuildChecklist(tools[i].result); - } - } - // A materialized build whose envelope says the app is already - // listed (`appHidden: false`) is published: ADR-0045 publish - // = live AND visible. - const buildIsLive = - publishedBuild !== undefined || - (builtAppDraft?.draftReview?.materialized === true && - builtAppDraft.draftReview.appHidden === false) || - (builtAppDraft !== undefined && - (builtPackageId !== undefined && pendingByPackage.has(builtPackageId) - ? pendingByPackage.get(builtPackageId) === 0 - : publishedToolCalls.has(builtAppDraft.toolCallId))); const showsActivity = summaryTools.length > 0 || - detailedTools.length > 0 || - Boolean(buildProgress) || - Boolean(blueprintProgress); + detailedTools.length > 0; // objectui#13492 — the answer body in stream order; the // streaming cursor rides the last text run, where it sat when // the charts always trailed the text. @@ -5567,41 +2135,6 @@ const ChatbotEnhanced = React.forwardRef( labels={L} /> ) : null} - {blueprintProgress ? ( - - ) : null} - {buildProgress ? ( - - ) : null} {!isUser && processVisibility === 'debug' && reasoning ? ( ( ) : null} {!isUser && detailedTools.length > 0 - ? detailedTools.map((tool) => - renderToolDetail(tool, { failureOnChecklist: buildChecklist?.status === 'failed' }), - ) + ? detailedTools.map((tool) => renderToolDetail(tool)) : null} {isUser ? ( message.content ? ( @@ -6240,130 +2771,6 @@ function LivenessIndicator({ ); } -/** - * Default rotating hints for the propose_blueprint wait. Presentational - * reassurance — the call is one atomic LLM request with no partial stream, so - * these don't reflect real sub-steps; they just let the (tens-of-seconds) wait - * read as deliberate design work instead of a hang. Order roughly follows how a - * human would think a schema through, with a few extra later-stage lines so a - * multi-minute wait keeps showing fresh copy instead of an obvious 5-item loop - * (improvement 4). Overridable/localizable via the `designingPlanHints` label. - */ -const DEFAULT_DESIGNING_PLAN_HINTS = [ - 'Mapping out the data you’ll track…', - 'Shaping objects and their fields…', - 'Connecting related records…', - 'Setting up relationships and lookups…', - 'Planning the screens and views…', - 'Laying out forms and lists…', - 'Adding sensible defaults and validations…', - 'Sketching a dashboard to track it…', - 'Double-checking the structure hangs together…', - 'Pulling the plan together…', -]; - -/** How long each design-stage hint stays up (ms) before advancing to the next. */ -const DESIGNING_HINT_ROTATE_MS = 3500; - -/** - * Which design hint to show after `elapsedMs` of waiting. Pure + deterministic - * so it can be unit-tested and so the visible stage is a function of the live - * elapsed clock (improvement 4) rather than a free-running interval. - * - * It advances ONE stage every `stepMs`, then CLAMPS on the final hint instead of - * wrapping back to the start — so a long wait reads as steady forward progress - * ("…pulling it together" stays up at the end) and never loops back to "mapping - * data", which would look like it restarted. Returns the 0-based stage index; - * `-1` when there is nothing to show (empty list). This is presentational - * staging, NOT a claim of real sub-step progress or a fake percentage. - */ -export function selectDesignHintIndex( - elapsedMs: number, - hintCount: number, - stepMs: number = DESIGNING_HINT_ROTATE_MS, -): number { - if (hintCount <= 0) return -1; - if (hintCount === 1) return 0; - const safeElapsed = Number.isFinite(elapsedMs) && elapsedMs > 0 ? elapsedMs : 0; - const step = stepMs > 0 ? stepMs : DESIGNING_HINT_ROTATE_MS; - const stage = Math.floor(safeElapsed / step); - return Math.min(stage, hintCount - 1); -} - -/** - * Friendly in-progress indicator for the build agent's `propose_blueprint` - * step. Because that call is a SINGLE long, atomic LLM request (no token - * stream, no partial results), a bare elapsed timer made it look like the UI - * might be stuck. This pairs the live `ToolRunningTimer` with a short lead-in - * ("Designing your app…"), a hint that ADVANCES through the design stages as the - * wait grows, and a row of step dots filled up to the current stage so the wait - * visibly "moves forward". The staging is purely presentational — it is NOT - * claiming real sub-step progress or a percentage; it just clamps on the final - * stage rather than looping. An empty `hints` array (or a single entry) just - * pins the lead-in + timer with no rotation or dots. - */ -function BuildProposalProgressHint({ - label, - hints, - offlineLabel, -}: { - label: string; - hints: string[]; - offlineLabel: string; -}) { - // Re-read the real elapsed clock once per stage interval; the visible stage is - // DERIVED from it (via the pure selector) so the hint and the step dots advance - // off one source of truth. The live seconds timer beside this ticks every 1s on - // its own, so the strip keeps "moving" between stage changes. - const [elapsedMs, setElapsedMs] = React.useState(0); - React.useEffect(() => { - if (hints.length <= 1) return; // nothing to advance through - const start = Date.now(); - const id = setInterval(() => setElapsedMs(Date.now() - start), DESIGNING_HINT_ROTATE_MS); - return () => clearInterval(id); - }, [hints.length]); - const index = selectDesignHintIndex(elapsedMs, hints.length); - const hint = index >= 0 ? hints[index] : undefined; - // Show the lightweight step dots only once there are real stages to track and - // we won't crowd the strip (cap the dot count so a long custom list stays sane). - const showDots = hints.length > 1 && hints.length <= 12; - return ( - - - {label} - {hint ? ( - // `key` on the hint text restarts the fade each time it swaps, so the - // stage change reads as a gentle transition rather than an instant flicker. - - {hint} - - ) : null} - {showDots ? ( - - {hints.map((_, i) => ( - - ))} - - ) : null} - - - ); -} - /** * Compact elapsed-timer + offline cue for a tool that is currently RUNNING * (issue #432) — e.g. the "Propose blueprint · Running" header. Counts up from @@ -6401,658 +2808,6 @@ function ToolRunningTimer({ offlineLabel }: { offlineLabel: string }) { ); } -const BUILD_GROUP_ORDER = ['object', 'view', 'dashboard', 'app', 'seed']; - -/** - * The build tree's per-type row headings, through the pack (objectui#7388). - * - * These were a module-level English `Record`, so every row of an otherwise - * localized panel read "Objects / Views / Dashboards / App / Sample data" in - * English — the same island the header strings were in, and the more visible - * half of it (one per row, on every build). - * - * The lookup stays a STATIC switch rather than `t('chatbot.build.group.' + type)`: - * a computed key is invisible to `check-i18n-call-site-keys`, which is the gate - * that proves each key exists in the `en` pack. The `default` arm answers a - * neutral "Other" heading: a raw type id (`dataset`, `permission`) read as an - * untranslated word, or as an error, in the middle of a localized sentence - * (objectstack#27419). Never a raw type id, never a raw i18n key. - */ -function useBuildGroupLabel(): (type: string) => string { - const { t } = useObjectTranslation(); - return React.useCallback( - (type: string) => { - switch (type) { - case 'object': - return t('chatbot.build.group.object', { defaultValue: 'Objects' }); - case 'view': - return t('chatbot.build.group.view', { defaultValue: 'Views' }); - case 'dashboard': - return t('chatbot.build.group.dashboard', { defaultValue: 'Dashboards' }); - case 'app': - return t('chatbot.build.group.app', { defaultValue: 'App' }); - case 'seed': - return t('chatbot.build.group.seed', { defaultValue: 'Sample data' }); - case 'dataset': - return t('chatbot.build.group.dataset', { defaultValue: 'Datasets' }); - case 'permission': - return t('chatbot.build.group.permission', { defaultValue: 'Permissions' }); - default: - return t('chatbot.build.group.other', { defaultValue: 'Other' }); - } - }, - [t], - ); -} - -/** - * Live "Designing…" panel for an in-flight blueprint DESIGN (`propose_blueprint`). - * The plan-design call is a long, atomic LLM request; the server now streams a - * reconciled `data-blueprint-progress` part as the schema takes shape, so this - * panel shows objects appearing one-by-one (label + field count) with the - * summary / extend target revealed progressively — replacing the purely - * presentational rotating-hint placeholder with real, event-driven progress. - * - * It is a LIVE affordance only: the caller stops rendering it the instant the - * `propose_blueprint` result lands (a structured `proposedPlan` exists on the - * turn), so the authoritative "Proposed plan" card takes over cleanly. With no - * progress events (older runtimes / non-streaming turns) this never renders and - * the rotating-hint placeholder remains — zero regression. - */ -function BlueprintProgressPanel({ - progress, - designingLabel = 'Designing your app…', - extendChip, - waitingLabel = 'Waiting for server…', - stalledLabel = 'Still working…', - offlineLabel = 'Connection lost — reconnecting…', -}: { - progress: ChatBlueprintProgress; - designingLabel?: string; - /** objectui#11658 — the localized scope-chip text for a target app (see - * `useExtendChip`); the panel owns no wording of its own for it. */ - extendChip: (targetApp: string) => string; - waitingLabel?: string; - stalledLabel?: string; - offlineLabel?: string; -}) { - const { phase, summary, appLabel, targetApp, objects, counts, seq } = progress; - const countBitsOf = useMetadataCountBits(); - const isDone = phase === 'done'; - // Real activity key, mirroring BuildProgressPanel: prefer the server's - // monotonic `seq` (it also advances on keep-alive heartbeats, where the - // content fields don't change), else a content signature for older runtimes. - // Drives the liveness indicator off observed bytes so the wait reads as - // "designing" rather than a hang. - const activityKey = seq ?? `${phase}:${objects.length}`; - // At `done` the app's own summary/label is the most informative header; while - // designing, the localized "Designing your app…" lead-in pairs with the - // summary shown on its own line below. - const headerText = isDone ? summary || appLabel || designingLabel : designingLabel; - const countBits = countBitsOf(counts ?? {}); - return ( -
-
- {isDone ? ( - - ) : ( - - )} - {headerText} - {targetApp ? ( - - + {extendChip(targetApp)} - - ) : null} - {!isDone ? ( - - - - ) : null} -
- {/* Summary one-liner — revealed progressively as the design streams. At - `done` it's already promoted into the header, so only show it here - while designing. */} - {!isDone && (summary || appLabel) ? ( -

{summary || appLabel}

- ) : null} - {objects.length > 0 ? ( -
- {objects.map((o) => ( - // `key` on the stable object name fades each chip in exactly once as - // it first appears, so the panel reads as objects materialising one - // by one rather than a list snapping into place. - - - {o.label || o.name} - {o.fields ? · {o.fields} : null} - - ))} -
- ) : null} - {countBits.length > 0 ? ( - - {countBits.join(' · ')} - - ) : null} -
- ); -} - -/** - * objectui#12724 — the plan card's object rows from `planCard.objects` (the - * AiBuild artboard): the object's label, one chip per field with the format its - * sample data is held to in mono type (`format.label`), a dashed 「补充」 chip for - * a field the user's words did not name (`suggested`, with one legend line - * under the rows saying what the mark means, #33419), the stage field's - * lifecycle beside its label (`lifecycle.label`, objectui#12994), and - * 「名称:FIELD」 under the chips when the object declares its name field - * (`nameField`). Each of those four is drawn only when its key is present. When - * the title is composed rather than typed, the producer's own line - * (`nameField.generated.line`, objectui#13004) is drawn in place of 「名称:FIELD」. - */ -function PlanCardObjectRows({ - objects, - heading, -}: { - objects: ProposedPlanCard['objects']; - heading: string; -}) { - const { t } = useObjectTranslation(); - const suggestedMark = t('chatbot.plan.suggestedField', { defaultValue: 'suggested' }); - // #33419 — the mark alone does not say what it means, so a card with any - // suggested field draws one legend line under its rows. - const anySuggested = objects.some((o) => o.fields.some((f) => f.suggested)); - return ( -
- {heading} - {objects.map((o) => ( -
- - {o.label} - -
-
- {o.fields.map((f) => ( - - {f.label} - {f.format ? ( - - {f.format.label} - - ) : null} - {f.lifecycle ? ( - - {f.lifecycle.label} - - ) : null} - {f.suggested ? · {suggestedMark} : null} - - ))} -
- {o.nameField ? ( - - {o.nameField.generated - ? o.nameField.generated.line - : t('chatbot.plan.nameField', { field: o.nameField.label, defaultValue: 'Name: {{field}}' })} - - ) : null} -
-
- ))} - {anySuggested ? ( - - {t('chatbot.plan.suggestedFieldLegend', { - mark: suggestedMark, - defaultValue: 'Fields marked “{{mark}}” were added by the AI; you didn’t ask for them.', - })} - - ) : null} -
- ); -} - -/** - * objectui#12724 — the result card's checklist (the AiBuild artboard's 核对 - * rows): every line the producer measured on the build, objects in one column - * and views and the sample data in the other, each with its own pass mark. - * The lines are the producer's words, read verbatim from `checklist.lines`. - * objectstack#34627 — a `verification` line states the build's failed verdict - * in red: the producer's `label`, then its issue `count`. A failed checklist is - * then the one place the card's turn states the failure. - */ -function BuildChecklistRows({ checklist }: { checklist: BuildResultChecklist }) { - const { t } = useObjectTranslation(); - const objectLines = checklist.lines.filter((l) => l.kind === 'object'); - const otherLines = checklist.lines.filter((l) => l.kind !== 'object'); - const column = (lines: BuildResultChecklist['lines'], testId: string) => - lines.length > 0 ? ( -
    - {lines.map((l, idx) => - l.kind === 'verification' ? ( -
  • - - - {l.label} - {' · '} - - {t('chatbot.build.issuesCount', { count: l.count, defaultValue: '{{count}} to fix' })} - - -
  • - ) : ( -
  • - {l.status === 'passed' ? ( - - ) : ( - - )} - {l.line} -
  • - ), - )} -
- ) : null; - return ( -
-
- {column(objectLines, 'build-checklist-objects')} - {column(otherLines, 'build-checklist-checks')} -
-
- ); -} - -/** - * Live "build tree" for an in-flight app build (apply_blueprint). Renders the - * artifacts as they stream in (via the message's `buildProgress`), so the user - * watches objects → views → dashboard → app → sample data appear instead of a - * blank thinking spinner. Collapses to a "Built X" summary when done. - */ -function BuildProgressPanel({ - progress, - appSegment, - onOpenBuiltApp, - openBuiltAppLabel = 'Open app', - onDesignBuiltApp, - designBuiltAppLabel = 'Design in Studio', - getArtifactAction, - onPreviewDraftApp, - previewDraftLabel = 'Preview', - onBuildResult, - live = false, - nextSteps, - checklist, - publishFromShellBar = false, - waitingLabel = 'Waiting for server…', - stalledLabel = 'Still working…', - offlineLabel = 'Connection lost — reconnecting…', -}: { - progress: ChatBuildProgress; - /** The build's owning package id (from its draft envelope), for deep links. */ - appSegment?: string; - /** - * objectui#12724 — the turn's latest `checklist` (`apply_blueprint`, then - * `verify_build` after a repair). When present, the finished card shows its - * 核对通过 chip and lines in place of the artifact list, and its `app` and - * `packageId` feed 打开应用 and 在 Studio 中查看. - */ - checklist?: BuildResultChecklist; - /** - * objectui#12724 — the build is published (its envelope says so, or this - * chat's publish signal does), so the finished card says 「已搭建并上线」. - * Without that signal it keeps saying only that the app was built. - */ - live?: boolean; - /** objectui#12724 — the build envelope's `nextSteps`, for the 「接下来可以说」 line. */ - nextSteps?: string[]; - /** - * objectstack#34610 — {@link ChatbotEnhancedProps.publishFromShellBar}: the - * chat draws no Publish, so the footer does not tell the user to click one - * here. - */ - publishFromShellBar?: boolean; - onOpenBuiltApp?: (appName: string) => void; - openBuiltAppLabel?: string; - onDesignBuiltApp?: (appName: string, appSegment?: string) => void; - designBuiltAppLabel?: string; - getArtifactAction?: ( - artifact: { type: string; name: string }, - appSegment?: string, - ) => (() => void) | null; - onPreviewDraftApp?: (appName: string) => void; - previewDraftLabel?: string; - /** {@link ChatbotEnhancedProps.onBuildResult}: this card's app, label and live state. */ - onBuildResult?: ChatbotEnhancedProps['onBuildResult']; - waitingLabel?: string; - stalledLabel?: string; - offlineLabel?: string; -}) { - const { phase, appLabel, items, done, total, seq, verify } = progress; - // objectui#7388 — every string this panel OWNS goes through the pack. The - // labels it receives as props (`openBuiltAppLabel`, the connection cues, …) - // are already localized by the host; these were the island left behind. - const { t } = useObjectTranslation(); - const groupLabelOf = useBuildGroupLabel(); - const isDone = phase === 'done'; - // objectui#11988 — only the phases the tree draws read as "Building"; any - // other value is surfaced as a warning, never coerced into one of them. - const unknownPhase = t('chatbot.build.unknownPhase', { defaultValue: 'Unknown build phase' }); - const isUnknown = !isDone && phase !== 'structure' && phase !== 'data'; - // The unnamed-build stand-in is itself a translated noun phrase, so it can be - // interpolated into the two header frames the same way a real app label is — - // one hole per frame, which is what `check-i18n-call-site-keys` checks. - // objectui#12724 — the checklist's `app.label` names the app the build - // landed in, so a finished card prefers it to the stream's label. - const appName = - checklist?.app?.label ?? appLabel ?? t('chatbot.build.appFallback', { defaultValue: 'your app' }); - // Real activity key: bumps whenever the server streams another build-progress - // part. Prefer the server's monotonic `seq` (it also advances on the keep-alive - // heartbeats during long, quiet seed-generation awaits, where the content - // fields don't change); fall back to the content signature for older runtimes - // that don't send `seq`. Drives the liveness indicator off observed bytes, so a - // healthy build reads as "receiving" and a genuine stall as amber. - const activityKey = seq ?? `${phase}:${done}:${items.length}`; - // The created `app` artifact (navigation shell) — the natural "open it" target. - // objectui#12724 — the checklist's `app` says which app 打开应用 opens (the - // new one, or the existing app an extend build landed in) and its - // `packageId` which package 在 Studio 中查看 opens; without them the doors - // read the staged artifacts and the draft envelope, as before. - const stagedApp = items.find((it) => it.type === 'app'); - const builtApp = checklist?.app ?? stagedApp; - const studioSegment = checklist?.packageId ?? appSegment; - // The card's own answer, handed to the host as the card shows it: the label - // its title names the app by and whether that title says the app is live. - const resultAppName = builtApp?.name; - const resultLabel = checklist?.app?.label ?? appLabel; - const resultLive = isDone && live; - React.useEffect(() => { - if (!onBuildResult || !resultAppName) return; - onBuildResult({ - appName: resultAppName, - ...(resultLabel ? { label: resultLabel } : {}), - live: resultLive, - }); - }, [onBuildResult, resultAppName, resultLabel, resultLive]); - const showChecklist = isDone && checklist !== undefined; - const pct = total > 0 ? Math.min(100, Math.round((done / total) * 100)) : isDone ? 100 : 6; - const groups = new Map>(); - for (const it of items) { - const arr = groups.get(it.type) ?? []; - // The frame's label when it carries one; the machine name otherwise. - arr.push({ name: it.name, display: it.label || it.name.replace(/_sample$/, '') }); - groups.set(it.type, arr); - } - const orderedTypes = [ - ...BUILD_GROUP_ORDER.filter((t) => groups.has(t)), - ...[...groups.keys()].filter((t) => !BUILD_GROUP_ORDER.includes(t)), - ]; - return ( -
-
- {isDone ? ( - - ) : isUnknown ? ( - - ) : ( - - )} - - {isDone - ? live - ? t('chatbot.build.builtAndLive', { app: appName, defaultValue: 'Built and live · {{app}}' }) - : t('chatbot.build.built', { app: appName, defaultValue: 'Built {{app}}' }) - : isUnknown - ? unknownPhase - : t('chatbot.build.building', { app: appName, defaultValue: 'Building {{app}}…' })} - - {!isDone && phase === 'data' ? ( - - {t('chatbot.build.addingSampleData', { defaultValue: 'adding sample data' })} - - ) : null} - {!isDone ? ( - - - - ) : null} - {showChecklist ? ( - // objectui#12724 — 核对通过 passed/total, as the checklist counts it. - - {t('chatbot.build.checksPassed', { - passed: checklist.passed, - total: checklist.total, - defaultValue: 'Checks passed {{passed}}/{{total}}', - })} - - ) : null} -
- {/* objectui#12724 — a finished build is a result card, not a progress bar. */} - {!isDone ? ( -
-
-
- ) : null} - {showChecklist ? ( - // objectui#12724 — a finished build with a checklist shows what was - // verified on it, not the list of staged artifacts. - - ) : ( -
    - {orderedTypes.map((type) => { - const entries = groups.get(type)!; - return ( -
  • - - - {groupLabelOf(type)}{' '} - {entries.slice(0, 6).map((entry, i) => { - // Deep-link the artifact to its direct-edit home (Studio - // pillar) once the build is done — the host decides which - // types are linkable (null → plain text). Mid-build stays - // plain: half-built artifacts have nowhere stable to land. - const action = isDone - ? getArtifactAction?.({ type, name: entry.name }, appSegment) - : null; - return ( - - {i > 0 ? ', ' : null} - {action ? ( - - ) : ( - entry.display - )} - - ); - })} - {entries.length > 6 - ? ` ${t('chatbot.build.moreArtifacts', { - n: entries.length - 6, - defaultValue: '+{{n}} more', - })}` - : ''} - -
  • - ); - })} -
- )} - {verify ? ( - // The verification line advances per hop and closes on `done`. -
- {verify.phase === 'done' ? ( - - ) : verify.phase === 'verify' ? ( - - ) : ( - - )} - {verify.phase === 'done' - ? t('chatbot.build.verified', { defaultValue: 'Checked the change' }) - : verify.phase === 'verify' - ? t('chatbot.build.verifying', { defaultValue: 'Checking the change…' }) - : unknownPhase} - {verify.phase === 'verify' && verify.hop !== undefined - ? ` ${t('chatbot.build.verifyStep', { n: verify.hop, defaultValue: 'step {{n}}' })}` - : null} -
- ) : null} - {isDone && builtApp && (onDesignBuiltApp || onOpenBuiltApp || onPreviewDraftApp) ? ( -
- {/* objectui#12724 (the AiBuild artboard, ruled by the maintainer): - the finished card's PRIMARY action opens the built app (its - first navigation item); Studio is the secondary door. Both are - in-app navigations the user chooses — nothing navigates on its - own when a build lands. A host without onOpenBuiltApp puts - Studio in the primary slot. */} - {onOpenBuiltApp ? ( - - ) : null} - {onDesignBuiltApp ? ( - - ) : null} - {/* ADR-0037: see the drafted app as-if-published, before Publish. */} - {onPreviewDraftApp && stagedApp ? ( - - ) : null} -
- ) : null} - {isDone && builtApp && ((nextSteps && nextSteps.length > 0) || !publishFromShellBar) ? ( - // objectui#12724 — what to say next (the envelope's `nextSteps`) and - // the posture of every later change, under the finished build. - // objectstack#34610 — under the shell's Publish the posture sentence - // ("click Publish here in the chat") is not drawn: there is no - // Publish here, and the drafts line points to the bar. -

- {nextSteps && nextSteps.length > 0 ? ( - - {t('chatbot.build.nextStepsLead', { - steps: nextSteps - .map((step) => t('chatbot.build.nextStepQuote', { step, defaultValue: '“{{step}}”' })) - .join(' '), - defaultValue: 'Next, you can say: {{steps}}', - })}{' '} - - ) : null} - {publishFromShellBar ? null : ( - - {t('chatbot.build.draftPosture', { - defaultValue: 'Later changes are saved as drafts; click Publish here in the chat to make them live.', - })} - - )} -

- ) : null} -
- ); -} - /** * objectui#12724 — one step of a phase's collapsed line: a tool, folded over * every call of it in the turn, in the order the turn first called it. @@ -7133,9 +2888,7 @@ function usePhaseElapsed(key: string, running: boolean): number | undefined { * objectui#12724 — a turn's tool activity as ONE collapsed line per phase * (「设计方案 · 4 步 · 0:48 · 读取编写规范 · 列出对象 ×3 …」), with a chevron * that expands the per-tool rows (`ToolActivitySummary`). Repeated calls of a - * tool fold into one step with a count. The phase is named for the build tool - * the turn called (`propose_blueprint` designs the plan, `apply_blueprint` - * builds); any other turn's line opens on its step count. The rows open on their + * tool fold into one step with a count. The line opens on its step count. The rows open on their * own while a step runs, waits or failed, so a live timer or an error is never * hidden behind the chevron; the user's own toggle wins after that. */ @@ -7182,14 +2935,7 @@ function ToolPhaseSummary({ const [toggled, setToggled] = React.useState(null); const expanded = toggled ?? lineState !== 'completed'; const elapsed = usePhaseElapsed(phaseKey, streaming || lineState === 'running'); - const names = phaseTools.map((tool) => tool.toolName); - const phaseLabel = names.includes('apply_blueprint') - ? t('chatbot.phase.build', { defaultValue: 'Build' }) - : names.includes('propose_blueprint') - ? t('chatbot.phase.design', { defaultValue: 'Design the plan' }) - : undefined; const headline = [ - ...(phaseLabel ? [phaseLabel] : []), t('chatbot.phase.stepCount', { count: steps.length, defaultValue: '{{count}} steps' }), ...(elapsed !== undefined ? [formatElapsed(elapsed)] : []), ].join(' · '); @@ -7248,8 +2994,6 @@ interface ToolActivitySummaryLabels { toolAwaitingApproval: string; toolFailed: string; connectionOfflineLabel: string; - designingPlanLabel: string; - designingPlanHints: string[]; } function ToolActivitySummary({ @@ -7281,21 +3025,9 @@ function ToolActivitySummary({ ) : null}
{group.state === 'running' ? ( - // A running tool (e.g. "Propose blueprint") shows a LIVE elapsed - // timer instead of a static "Running", and a red offline cue if - // the network drops (issue #432). The build agent's plan-design - // step is special-cased: that one call is a long, atomic LLM - // request with no token stream, so a bare timer felt stuck — give - // it a friendly "Designing your app…" lead-in with rotating hints. - group.rawName === 'propose_blueprint' ? ( - - ) : ( - - ) + // A running tool shows a LIVE elapsed timer instead of a static + // "Running", and a red offline cue if the network drops (issue #432). + ) : ( void; -}) { - const copy = useAiQuotaCopy(error); - if (!copy) return null; - return ( - <> - - {copy.text} - - {onUpgrade && copy.cta ? ( - - ) : null} - - ); -} - function ErrorBanner({ error, onReload, diff --git a/ui/packages/plugin-chatbot/src/__tests__/ChatbotEnhanced.appliedCardPreview-12968.test.tsx b/ui/packages/plugin-chatbot/src/__tests__/ChatbotEnhanced.appliedCardPreview-12968.test.tsx deleted file mode 100644 index 19f07507b7b..00000000000 --- a/ui/packages/plugin-chatbot/src/__tests__/ChatbotEnhanced.appliedCardPreview-12968.test.tsx +++ /dev/null @@ -1,126 +0,0 @@ -/** - * ObjectUI - * Copyright (c) 2024-present ObjectStack Inc. - * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. - * - * objectui#12968 (objectstack#24324 ruling A, preview-first) — the confirm - * path previews too. A change confirmed on the change card and saved as a - * draft answers with a `drafted` replay envelope; `detectReplayOutcome` lifts - * the items that replay drafted, and the applied card draws Preview through - * the same `onPreviewDraft` door the drafted result uses. - * - * Pinned: - * - the lift: a drafted replay carries its `drafted[]` items (not the - * package's whole `draftState.items`), and a published one carries none; - * - the applied card draws Preview and the click hands the host the items - * and the package id; the bare drafted badge (an older cloud with no - * applied card) does the same; - * - CONTROL: a host with no `onPreviewDraft` draws no Preview, and the card's - * other doors are unchanged. - * - * Every message goes through the real mapper from a raw tool part. - */ -import '@testing-library/jest-dom/vitest'; -import { afterEach, describe, expect, it, vi } from 'vitest'; -import { cleanup, fireEvent, render, screen } from '@testing-library/react'; -import { I18nProvider } from '@object-ui/i18n'; -import { ChatbotEnhanced } from '../ChatbotEnhanced'; -import { detectReplayOutcome, uiMessageToChatMessage } from '../mapMessages'; -import { BORROWING, PACKAGE_ID, draftedEnvelope, proposedEnvelope } from './fixtures/changePosture.fixtures'; - -afterEach(() => { - cleanup(); -}); - -const proposalTurn = (envelope: unknown) => - uiMessageToChatMessage({ - id: 'a1', - role: 'assistant', - parts: [ - { type: 'tool-apply_edit', toolCallId: 'call_1', state: 'output-available', input: {}, output: envelope }, - ], - }); - -const replayTurn = (envelope: unknown) => - uiMessageToChatMessage({ - id: 'a2', - role: 'assistant', - parts: [ - { type: 'tool-apply_edit', toolCallId: 'replay_t2_0', state: 'output-available', input: {}, output: envelope }, - ], - }); - -const renderApplied = (replay: unknown, props: Partial> = {}) => - render( - - - , - ); - -describe('detectReplayOutcome lifts the drafted items (objectui#12968)', () => { - it('a drafted replay carries the items it drafted, not every pending draft of the package', () => { - const outcome = detectReplayOutcome('replay_t2_0', draftedEnvelope('en', { others: 2 })); - expect(outcome?.kind).toBe('drafted'); - expect(outcome?.items).toEqual([{ type: 'object', name: BORROWING }]); - expect(outcome?.draftState?.items).toHaveLength(3); - }); - - it('a one-item stage reports its type and name, and those are the item', () => { - const outcome = detectReplayOutcome('replay_t2_0', { - status: 'drafted', - type: 'view', - name: `${BORROWING}.board`, - packageId: PACKAGE_ID, - }); - expect(outcome?.items).toEqual([{ type: 'view', name: `${BORROWING}.board` }]); - }); - - it('a published replay carries no items', () => { - expect(detectReplayOutcome('replay_t2_0', { status: 'published', drafted: [{ type: 'object', name: BORROWING }] })).toEqual({ - kind: 'published', - }); - }); -}); - -describe('the confirm-gated applied card draws Preview (objectui#12968)', () => { - it('the applied card draws Preview, and the click hands the host the drafted items and the package id', () => { - const onPreviewDraft = vi.fn(); - const onReviewDrafts = vi.fn(); - renderApplied(draftedEnvelope('en', { others: 2 }), { onPreviewDraft, onReviewDrafts, onDiscardDrafts: vi.fn() }); - const preview = screen.getByTestId('applied-card-preview'); - expect(preview).toHaveTextContent('Preview'); - fireEvent.click(preview); - expect(onPreviewDraft).toHaveBeenCalledTimes(1); - expect(onPreviewDraft).toHaveBeenCalledWith([{ type: 'object', name: BORROWING }], { appSegment: PACKAGE_ID }); - // Preview publishes and reviews nothing. - expect(onReviewDrafts).not.toHaveBeenCalled(); - // The card's other doors are where they were. - expect(screen.getByTestId('applied-card-review')).toBeInTheDocument(); - expect(screen.getByTestId('applied-card-discard')).toBeInTheDocument(); - }); - - it('an older cloud (no applied card): the drafted badge draws Preview through the same door', () => { - const onPreviewDraft = vi.fn(); - renderApplied(draftedEnvelope('en', { withCard: false }), { onPreviewDraft, onPublishDrafts: vi.fn() }); - expect(screen.queryByTestId('applied-card')).not.toBeInTheDocument(); - expect(screen.getByTestId('proposed-changes-drafted')).toBeInTheDocument(); - fireEvent.click(screen.getByTestId('proposed-changes-preview')); - expect(onPreviewDraft).toHaveBeenCalledWith([{ type: 'object', name: BORROWING }], { appSegment: PACKAGE_ID }); - }); - - it('CONTROL: a host with no onPreviewDraft draws no Preview on either rendering', () => { - renderApplied(draftedEnvelope('en'), { onReviewDrafts: vi.fn(), onDiscardDrafts: vi.fn() }); - expect(screen.getByTestId('applied-card')).toBeInTheDocument(); - expect(screen.queryByTestId('applied-card-preview')).not.toBeInTheDocument(); - cleanup(); - renderApplied(draftedEnvelope('en', { withCard: false }), { onPublishDrafts: vi.fn() }); - expect(screen.getByTestId('proposed-changes-drafted')).toBeInTheDocument(); - expect(screen.queryByTestId('proposed-changes-preview')).not.toBeInTheDocument(); - }); -}); diff --git a/ui/packages/plugin-chatbot/src/__tests__/ChatbotEnhanced.awaitingConfirmBuild-8343.test.tsx b/ui/packages/plugin-chatbot/src/__tests__/ChatbotEnhanced.awaitingConfirmBuild-8343.test.tsx deleted file mode 100644 index 6d32222acc5..00000000000 --- a/ui/packages/plugin-chatbot/src/__tests__/ChatbotEnhanced.awaitingConfirmBuild-8343.test.tsx +++ /dev/null @@ -1,235 +0,0 @@ -/** - * ObjectUI - * Copyright (c) 2024-present ObjectStack Inc. - * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. - * - * objectui#8343 — an `apply_blueprint` that returned `awaiting_confirmation` - * built NOTHING, so the plan card before it must keep its live "Build it". - * - * `builtPlanIds` used to key on the tool NAME alone - * (`if (tool.toolName === 'apply_blueprint') lastBuildOrder = order`), which - * cannot tell "the build ran" from "the build refused to run and is itself - * waiting for the user". On the second (iteration) turn the build agent calls - * `apply_blueprint`, hits its own confirm gate and returns - * `{"status":"awaiting_confirmation", …}`. The earlier `propose_blueprint` - * card was then marked 已搭建, collapsing its "Build it" button away — while - * the `apply_blueprint` card itself has no button either. Measured in the - * browser: the whole turn had no confirm affordance at all, and the only way - * out was guessing the magic phrase "确认" into the composer. - * - * Both envelopes below are the real wire shapes, fed through the real mapper - * (`uiMessagesToChatMessages`) so the detector chain runs exactly as it does - * in the console. - */ -import '@testing-library/jest-dom/vitest'; -import { describe, it, expect, vi } from 'vitest'; -import { render, screen } from '@testing-library/react'; -import { ChatbotEnhanced } from '../ChatbotEnhanced'; -import { uiMessagesToChatMessages } from '../mapMessages'; - -/** `propose_blueprint` result — the plan the user is asked to confirm. */ -const BLUEPRINT_PROPOSED = { - status: 'blueprint_proposed', - summary: 'Add a vaccination-record table to the existing clinic app', - blueprint: { - objects: [ - { - name: 'vaccination_record', - label: 'Vaccination record', - fields: [{ name: 'pet' }, { name: 'vaccine' }, { name: 'given_on' }], - }, - ], - }, - counts: { objects: 1, views: 1, dashboards: 0, seedData: 1 }, - questions: [], - assumptions: [], -}; - -/** - * `apply_blueprint` result when the user did NOT say the magic "直接搭建" — - * the tool shows a confirm card and stops. Nothing was created. - */ -const AWAITING_CONFIRMATION = { - status: 'awaiting_confirmation', - message: - 'A confirm card for this blueprint was just shown to the user — STOP and let them review it.', -}; - -/** `apply_blueprint` result when the build actually ran (ADR-0033 draft envelope). */ -const BUILD_DRAFTED = { - status: 'drafted', - summary: 'Created 1 object, 1 view', - drafted: [ - { type: 'object', name: 'vaccination_record' }, - { type: 'app', name: 'clinic' }, - ], -}; - -/** The two-turn transcript: propose, then an apply_blueprint with `applyResult`. */ -function transcript(applyResult: unknown) { - return uiMessagesToChatMessages([ - { - id: 'a1', - role: 'assistant', - parts: [ - { - type: 'tool-propose_blueprint', - toolCallId: 'plan-1', - state: 'output-available', - output: { type: 'text', value: JSON.stringify(BLUEPRINT_PROPOSED) }, - }, - ], - }, - { - id: 'a2', - role: 'assistant', - parts: [ - { - type: 'tool-apply_blueprint', - toolCallId: 'apply-1', - state: 'output-available', - output: { type: 'text', value: JSON.stringify(applyResult) }, - }, - { type: 'text', text: 'Please confirm the plan card so the build can run.' }, - ], - }, - ]); -} - -describe('ChatbotEnhanced — apply_blueprint that only asked for confirmation (#8343)', () => { - it('sanity: the transcript really produces a plan card the mapper recognised', () => { - const messages = transcript(AWAITING_CONFIRMATION); - expect(messages[0].toolInvocations?.[0].proposedPlan).toBeTruthy(); - expect(messages[1].toolInvocations?.[0].toolName).toBe('apply_blueprint'); - // The apply call carries no plan/changes card of its own — which is why - // the propose card is the ONLY confirm affordance in this turn. - expect(messages[1].toolInvocations?.[0].proposedPlan).toBeUndefined(); - expect(messages[1].toolInvocations?.[0].proposedChanges).toBeUndefined(); - }); - - it('keeps the plan card pending, with a live Build it button', () => { - render(); - - // The bug: this used to be the inert 已搭建 badge and the buttons were gone, - // leaving the whole turn with nothing to click. - expect(screen.queryByTestId('proposed-plan-built')).not.toBeInTheDocument(); - expect(screen.getByTestId('proposed-plan-approve')).toBeInTheDocument(); - expect(screen.getByTestId('proposed-plan-adjust')).toBeInTheDocument(); - }); - - it('still collapses the plan card to Built once the build actually ran', () => { - render(); - - // The #432 behaviour this fix must not regress: a plan whose build HAS run - // may not keep offering a button that re-triggers the whole build. - expect(screen.getByTestId('proposed-plan-built')).toBeInTheDocument(); - expect(screen.queryByTestId('proposed-plan-approve')).not.toBeInTheDocument(); - }); - - // objectstack#32984 — running is not built: the card says 正在搭建… while - // the turn is live, and still offers no second Build it (#432). - it('reads Building (no button) while the real build is still running (no result yet)', () => { - const messages = uiMessagesToChatMessages([ - { - id: 'a1', - role: 'assistant', - parts: [ - { - type: 'tool-propose_blueprint', - toolCallId: 'plan-1', - state: 'output-available', - output: { type: 'text', value: JSON.stringify(BLUEPRINT_PROPOSED) }, - }, - ], - }, - { - id: 'a2', - role: 'assistant', - parts: [ - { type: 'tool-apply_blueprint', toolCallId: 'apply-1', state: 'input-available' }, - ], - }, - ]); - render(); - - // An in-flight build must not be offered a second "Build it" that would - // re-trigger it — and it is not 已搭建 either: nothing is built yet. - expect(screen.getByTestId('proposed-plan-building')).toBeInTheDocument(); - expect(screen.queryByTestId('proposed-plan-built')).not.toBeInTheDocument(); - expect(screen.queryByTestId('proposed-plan-approve')).not.toBeInTheDocument(); - }); -}); - -/** - * The sibling memo, `confirmedChangeIds`, was reported on the issue as already - * having the right shape. Measured: it does NOT. It inferred "this later call - * committed" from the ABSENCE of a rich `proposedChanges` card, and that - * detector needs a `changes_proposed` status AND ≥1 parseable change row — so a - * later same-tool call that WAS a preview but rendered no card settled the - * pending card just the same. Same defect, one memo down. - */ -const CHANGES_PROPOSED = { - status: 'changes_proposed', - applied: false, - summary: 'Confirm this change before it is applied.', - changes: [{ verb: 'add_field', object: 'task', field: 'priority', type: 'select' }], -}; - -function changeTranscript(secondResult: unknown) { - return uiMessagesToChatMessages([ - { - id: 'c1', - role: 'assistant', - parts: [ - { - type: 'tool-update_metadata', - toolCallId: 'change-1', - state: 'output-available', - output: { type: 'text', value: JSON.stringify(CHANGES_PROPOSED) }, - }, - ], - }, - { - id: 'c2', - role: 'assistant', - parts: [ - { - type: 'tool-update_metadata', - toolCallId: 'change-2', - state: 'output-available', - output: { type: 'text', value: JSON.stringify(secondResult) }, - }, - ], - }, - ]); -} - -describe('ChatbotEnhanced — a later preview is not a commit (#8343)', () => { - it('keeps the 确认修改 card pending when the later same-tool call was itself a preview', () => { - // `changes: []` — the shape `apply_edit` returns when the gate previewed an - // op list the row formatter could not turn into a card. - render( - , - ); - - expect(screen.queryByTestId('proposed-changes-confirmed')).not.toBeInTheDocument(); - expect(screen.getByTestId('proposed-changes-confirm')).toBeInTheDocument(); - }); - - it('still collapses the 确认修改 card once the same tool really committed', () => { - render( - , - ); - - expect(screen.getByTestId('proposed-changes-confirmed')).toBeInTheDocument(); - expect(screen.queryByTestId('proposed-changes-confirm')).not.toBeInTheDocument(); - }); -}); diff --git a/ui/packages/plugin-chatbot/src/__tests__/ChatbotEnhanced.buildCardsV2-12724.test.tsx b/ui/packages/plugin-chatbot/src/__tests__/ChatbotEnhanced.buildCardsV2-12724.test.tsx deleted file mode 100644 index b54e2e3b135..00000000000 --- a/ui/packages/plugin-chatbot/src/__tests__/ChatbotEnhanced.buildCardsV2-12724.test.tsx +++ /dev/null @@ -1,328 +0,0 @@ -/** - * ObjectUI - * Copyright (c) 2024-present ObjectStack Inc. - * - * objectui#12724, phase 2 — the AiBuild artboard's v2 rows, drawn from the keys - * objectstack-ai/cloud declares (`build-cards.schema.json`, vendored as - * `fixtures/build-cards.schema.ts`; every fixture here is checked against it by - * `buildCards.contract-12724.test.ts`): - * - * - the plan card, from `propose_blueprint`'s `planCard`: field chips with the - * format constraint in mono type and a dashed 「补充」 chip for a suggested - * field, 「名称:FIELD」 from `nameField`, one intent line per view, the - * assumptions as a list, and the sample-data line; - * - the result card, from `apply_blueprint` / `verify_build`'s `checklist`: - * the 核对通过 chip, the verified lines in two columns, and 打开应用 / 在 - * Studio 中查看 fed by `checklist.app` and `checklist.packageId`; - * - the 「接下来可以说」 line from `nextSteps`, on both envelopes a build really - * sends (drafted, and drafted with `materialized: true` when it was - * published in the turn). - * - * And every row degrades to phase 1's shape when its key is absent: a tenant - * on an older cloud build sends none of them. - * - * Each message goes through the real mapper (`uiMessageToChatMessage`) from a - * raw tool part, so the lift is under test, not a hand-built invocation. - */ -import '@testing-library/jest-dom/vitest'; -import { describe, expect, it, vi } from 'vitest'; -import { fireEvent, render, screen, within } from '@testing-library/react'; -import { I18nProvider } from '@object-ui/i18n'; -import { ChatbotEnhanced } from '../ChatbotEnhanced'; -import { uiMessageToChatMessage } from '../mapMessages'; -import { applyEnvelope, checklistOf, planEnvelope, verifyEnvelope } from './fixtures/buildCards.fixtures'; - -function inLocale(lang: 'zh' | 'en', ui: React.ReactElement) { - return ( - {ui} - ); -} - -/** One assistant turn whose tool parts finished with these envelopes. */ -const turn = (id: string, ...tools: Array<[string, unknown]>) => - uiMessageToChatMessage({ - id, - role: 'assistant', - parts: tools.map(([toolName, output], i) => ({ - type: `tool-${toolName}`, - toolCallId: `${id}-${i}`, - state: 'output-available', - input: {}, - output, - })), - }); - -const chipsOf = (objectName: string) => - within(screen.getByTestId(`proposed-plan-object-${objectName}`)) - .getAllByTestId('proposed-plan-field') - .map((c) => c.textContent); - -describe('objectui#12724 phase 2 — the plan card draws planCard', () => { - const renderPlan = (envelope: unknown, lang: 'zh' | 'en' = 'zh') => - render( - inLocale( - lang, - , - ), - ); - - it('zh: one chip per field, the format in mono type, the suggested field dashed with 「补充」', () => { - renderPlan(planEnvelope('zh')); - expect(chipsOf('book')).toEqual(['书名', '作者', 'ISBN13 位数字', '馆藏数量', '分类· 补充']); - expect(chipsOf('reader')).toEqual(['姓名', '邮箱邮箱格式', '电话电话格式']); - const book = screen.getByTestId('proposed-plan-object-book'); - const isbn = within(book).getAllByTestId('proposed-plan-field')[2]; - expect(within(isbn).getByTestId('proposed-plan-field-format')).toHaveTextContent('13 位数字'); - expect(within(isbn).getByTestId('proposed-plan-field-format').className).toContain('font-mono'); - const category = within(book).getAllByTestId('proposed-plan-field')[4]; - expect(category).toHaveAttribute('data-suggested', 'true'); - expect(category.className).toContain('border-dashed'); - // A field with neither key draws a plain chip. - const author = within(book).getAllByTestId('proposed-plan-field')[1]; - expect(author).not.toHaveAttribute('data-suggested'); - expect(within(author).queryByTestId('proposed-plan-field-format')).not.toBeInTheDocument(); - }); - - it('zh: 「名称:FIELD」 under an object that declares its name field, and none under one that does not', () => { - renderPlan(planEnvelope('zh')); - const nameOf = (o: string) => - within(screen.getByTestId(`proposed-plan-object-${o}`)).queryByTestId('proposed-plan-name-field'); - expect(nameOf('book')).toHaveTextContent(/^名称:书名$/); - expect(nameOf('reader')).toHaveTextContent(/^名称:姓名$/); - expect(nameOf('loan')).not.toBeInTheDocument(); - }); - - it('zh: each view with its intent line, the assumptions as a list, and the sample-data line', () => { - renderPlan(planEnvelope('zh')); - expect(screen.getAllByTestId('proposed-plan-view-line').map((l) => l.textContent)).toEqual([ - '看板 · 按 状态 分组 · 卡片:图书、读者、应还日期', - '列表 · 筛选 状态 = 逾期 且 归还日期 为空 · 按应还日期升序', - '列表 · 显示全部记录', - ]); - const items = within(screen.getByTestId('proposed-plan-assumptions')).getAllByRole('listitem'); - expect(items.map((li) => li.textContent)).toEqual([ - '只建这三部分,不建仪表盘、预约、罚款;补充的字段(分类)可以去掉。', - '归还后状态置为已还;逾期由应还日期已过且未归还判定。', - ]); - expect(screen.getByTestId('proposed-plan-counts')).toHaveTextContent( - /^3 个对象 · 3 个视图 · 示例数据 12 条\/对象$/, - ); - }); - - it('en: the same rows in English', () => { - renderPlan(planEnvelope('en'), 'en'); - expect(chipsOf('book')).toEqual(['Title', 'Author', 'ISBN13 digits', 'Copies', 'Category· suggested']); - expect(within(screen.getByTestId('proposed-plan-object-book')).getByTestId('proposed-plan-name-field')).toHaveTextContent( - /^Name: Title$/, - ); - expect(screen.getByTestId('proposed-plan-counts')).toHaveTextContent( - /^3 objects · 3 views · Sample data: 12 rows per object$/, - ); - }); -}); - -describe('objectui#12724 phase 2 — each plan row degrades to phase 1 when its key is absent', () => { - const withoutCard = () => { - const { planCard: _card, viewIntents: _intents, ...rest } = planEnvelope('zh'); - return rest; - }; - - it('no planCard: field chips from the blueprint with no format or suggested mark, no name line, view names only, the blueprint`s assumptions, no sample-data line', () => { - render(); - expect(chipsOf('book')).toEqual(['书名', '作者', 'ISBN', '馆藏数量', '分类']); - expect(screen.queryByTestId('proposed-plan-field-format')).not.toBeInTheDocument(); - expect(document.querySelector('[data-suggested]')).toBeNull(); - expect(screen.queryByTestId('proposed-plan-name-field')).not.toBeInTheDocument(); - expect(screen.getAllByTestId('proposed-plan-view').map((v) => v.textContent)).toEqual([ - '·借阅看板', - '·逾期未还记录', - '·图书', - ]); - expect(screen.queryByTestId('proposed-plan-view-line')).not.toBeInTheDocument(); - expect(within(screen.getByTestId('proposed-plan-assumptions')).getAllByRole('listitem').map((li) => li.textContent)).toEqual([ - 'blueprint assumption the plan card does not repeat', - ]); - expect(screen.getByTestId('proposed-plan-counts')).toHaveTextContent(/^3 objects · 3 views$/); - }); - - it('no planCard but viewIntents (a producer between the two): the intent lines come from viewIntents', () => { - const { planCard: _card, ...rest } = planEnvelope('zh'); - render(); - expect(screen.getAllByTestId('proposed-plan-view-line')).toHaveLength(3); - expect(screen.getAllByTestId('proposed-plan-view-line')[1]).toHaveTextContent( - '列表 · 筛选 状态 = 逾期 且 归还日期 为空 · 按应还日期升序', - ); - expect(screen.queryByTestId('proposed-plan-name-field')).not.toBeInTheDocument(); - }); - - it('a planCard without sampleData: the count line keeps the bare sample-data bit', () => { - const plan = planEnvelope('zh'); - const { sampleData: _sample, ...card } = plan.planCard; - const envelope = { ...plan, counts: { ...plan.counts, seedData: 3 }, planCard: card }; - render( - inLocale('zh', ), - ); - expect(screen.getByTestId('proposed-plan-counts')).toHaveTextContent(/^3 个对象 · 3 个视图 · 示例数据$/); - // The rest of the card still reads planCard. - expect(screen.getAllByTestId('proposed-plan-view-line')).toHaveLength(3); - }); -}); - -describe('objectui#12724 phase 2 — the result card draws the checklist', () => { - it('zh: 核对通过 7/7, the verified lines in two columns, in place of the artifact list', () => { - render( - inLocale( - 'zh', - , - ), - ); - const chip = screen.getByTestId('build-checklist-chip'); - expect(chip).toHaveTextContent(/^核对通过 7\/7$/); - expect(chip).toHaveAttribute('data-status', 'passed'); - const col = (id: string) => - within(screen.getByTestId(id)).getAllByTestId('build-checklist-line').map((l) => l.textContent); - expect(col('build-checklist-objects')).toEqual([ - '图书 · 5 个字段 · 12 条示例', - '读者 · 3 个字段 · 12 条示例', - '借阅记录 · 6 个字段 · 12 条示例', - ]); - expect(col('build-checklist-checks')).toEqual([ - '借阅看板 · 按状态分组 · 5 / 4 / 3', - '逾期未还记录 · 筛选生效 · 命中 3 条', - '图书 · 显示全部记录 · 12 条', - '示例数据 · 无重复 · ISBN / 邮箱格式通过', - ]); - expect(screen.getByTestId('build-checklist').firstElementChild?.className).toContain('@md:grid-cols-2'); - // The checklist's app label names the card. - expect(screen.getByTestId('build-progress-title')).toHaveTextContent('图书借阅管理'); - // No staged-artifact list beside what was verified. - expect(screen.queryByText('library_app')).not.toBeInTheDocument(); - }); - - it('打开应用 and 在 Studio 中查看 open what checklist.app and checklist.packageId name', () => { - const onOpenBuiltApp = vi.fn(); - const onDesignBuiltApp = vi.fn(); - // An extend build: the checklist names the app the build LANDED in, which - // is not the app artifact the envelope staged. - const envelope = { - ...applyEnvelope('zh'), - checklist: { ...checklistOf('zh'), app: { name: 'campus_app', label: '校园' }, packageId: 'app.campus' }, - }; - render( - , - ); - fireEvent.click(screen.getByTestId('build-progress-open-app')); - expect(onOpenBuiltApp).toHaveBeenCalledWith('campus_app'); - fireEvent.click(screen.getByTestId('build-progress-design-app')); - expect(onDesignBuiltApp).toHaveBeenCalledWith('campus_app', 'app.campus'); - }); - - it('a verify_build later in the turn supersedes apply_blueprint`s checklist', () => { - render( - inLocale( - 'zh', - , - ), - ); - const chip = screen.getByTestId('build-checklist-chip'); - expect(chip).toHaveTextContent(/^核对通过 6\/7$/); - expect(chip).toHaveAttribute('data-status', 'failed'); - const failed = screen - .getAllByTestId('build-checklist-line') - .filter((l) => l.getAttribute('data-status') === 'failed'); - expect(failed.map((l) => l.textContent)).toEqual(['逾期未还记录 · 筛选生效 · 命中 3 条']); - }); - - it('en: Checks passed 7/7', () => { - render( - inLocale( - 'en', - , - ), - ); - expect(screen.getByTestId('build-checklist-chip')).toHaveTextContent(/^Checks passed 7\/7$/); - expect(screen.getAllByTestId('build-checklist-line')[0]).toHaveTextContent('Book · 5 fields · 12 sample rows'); - }); - - it('no checklist (an older producer): no chip, the artifact list, and the doors read the staged app and the envelope`s package', () => { - const onOpenBuiltApp = vi.fn(); - const onDesignBuiltApp = vi.fn(); - const { checklist: _c, ...envelope } = applyEnvelope('zh'); - render( - , - ); - expect(screen.queryByTestId('build-checklist-chip')).not.toBeInTheDocument(); - expect(screen.queryByTestId('build-checklist')).not.toBeInTheDocument(); - expect(screen.getByTestId('build-progress')).toHaveTextContent('library_app'); - fireEvent.click(screen.getByTestId('build-progress-open-app')); - expect(onOpenBuiltApp).toHaveBeenCalledWith('library_app'); - fireEvent.click(screen.getByTestId('build-progress-design-app')); - expect(onDesignBuiltApp).toHaveBeenCalledWith('library_app', 'app.hcpl'); - }); -}); - -describe('objectui#12724 phase 2 — 「接下来可以说」 on both envelopes a build sends', () => { - const NEXT = '接下来可以说:「给借阅记录加续借次数」 「做一个本月借出统计的仪表盘」 「只允许管理员删除图书」'; - - it.each([ - ['drafted', applyEnvelope('zh')], - ['drafted and materialized (published in the turn)', applyEnvelope('zh', { materialized: true })], - ])('%s: the line quotes the envelope`s nextSteps', (_name, envelope) => { - render( - inLocale('zh', ), - ); - expect(screen.getByTestId('build-result-next-steps')).toHaveTextContent(NEXT); - }); - - it('no nextSteps: no line, the posture sentence stays', () => { - const { nextSteps: _n, ...envelope } = applyEnvelope('zh'); - render( - inLocale('zh', ), - ); - expect(screen.queryByTestId('build-result-next-steps')).not.toBeInTheDocument(); - expect(screen.getByTestId('build-result-posture')).toBeInTheDocument(); - }); - - // objectstack#34610 — under the shell's Publish the chat draws none, so the - // footer never says to click Publish here; the next-steps line stays. - it('publishFromShellBar: no posture sentence; the next-steps line stays, and with none the footer is not drawn', () => { - const { unmount } = render( - inLocale( - 'zh', - , - ), - ); - expect(screen.getByTestId('build-result-next-steps')).toHaveTextContent(NEXT); - expect(screen.queryByTestId('build-result-posture')).not.toBeInTheDocument(); - unmount(); - const { nextSteps: _n, ...envelope } = applyEnvelope('zh'); - render( - inLocale( - 'zh', - , - ), - ); - expect(screen.queryByTestId('build-result-footer')).not.toBeInTheDocument(); - }); -}); diff --git a/ui/packages/plugin-chatbot/src/__tests__/ChatbotEnhanced.buildChat-12724.test.tsx b/ui/packages/plugin-chatbot/src/__tests__/ChatbotEnhanced.buildChat-12724.test.tsx deleted file mode 100644 index 1a652280267..00000000000 --- a/ui/packages/plugin-chatbot/src/__tests__/ChatbotEnhanced.buildChat-12724.test.tsx +++ /dev/null @@ -1,314 +0,0 @@ -/** - * ObjectUI - * Copyright (c) 2024-present ObjectStack Inc. - * - * objectui#12724 — the build conversation per the AiBuild artboard, the - * halves that need no new payload: - * - * 1. Progress: ONE collapsed line per phase (「设计方案 · 4 步 · 0:48 · 查阅编写 - * 规范 · 列出已有对象 ×3 …」), repeated calls folded into one step with a - * count, and a chevron that expands the per-tool rows. - * 2. The finished build card: the 「已搭建并上线 · APP」 header when the build - * is live, 打开应用 (primary) and 在 Studio 中查看, the 「接下来可以说」 line - * from the envelope's `nextSteps`, and the draft-posture sentence. - * 3. The plan card: field chips from `blueprint.objects[].fields`, view rows, - * the app name in the header — and today's object chips when the plan - * carries no field rows. - * - * Rendered through a real `I18nProvider` where the wording is the point, so - * the zh strings are the shipped pack's, not this file's. - */ -import '@testing-library/jest-dom/vitest'; -import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; -import { act, fireEvent, render, screen, within } from '@testing-library/react'; -import { I18nProvider } from '@object-ui/i18n'; -import { ChatbotEnhanced, type ChatbotEnhancedMessage } from '../ChatbotEnhanced'; -import { detectProposedPlan } from '../mapMessages'; - -function inLocale(lang: 'zh' | 'en', ui: React.ReactElement) { - return ( - {ui} - ); -} - -const done = (toolCallId: string, toolName: string) => ({ - toolCallId, - toolName, - state: 'output-available' as const, - result: { ok: true }, -}); - -/** The design turn the artboard draws: rules, objects ×3, todos ×2, then the plan. */ -const designTurn = (streaming: boolean): ChatbotEnhancedMessage => ({ - id: 'design-1', - role: 'assistant', - content: '', - streaming, - toolInvocations: [ - done('a', 'get_authoring_rules'), - done('b', 'list_objects'), - done('c', 'list_objects'), - done('d', 'todo_write'), - done('e', 'list_objects'), - done('f', 'todo_write'), - done('g', 'propose_blueprint'), - ], -}); - -describe('objectui#12724 — the progress collapses to one line per phase', () => { - beforeEach(() => { - vi.useFakeTimers(); - }); - afterEach(() => { - vi.useRealTimers(); - }); - - it('zh: one line with the phase, its folded step count, the elapsed time and the folded steps', () => { - const { rerender } = render(inLocale('zh', )); - act(() => { - vi.advanceTimersByTime(48_000); - }); - rerender(inLocale('zh', )); - expect(screen.getAllByTestId('tool-phase')).toHaveLength(1); - expect(screen.getByTestId('tool-phase-headline')).toHaveTextContent(/^设计方案 · 4 步 · 0:48$/); - expect(screen.getByTestId('tool-phase-steps')).toHaveTextContent( - /^查阅编写规范 · 列出已有对象 ×3 · 记下后续检查项 ×2 · 拟定应用方案$/, - ); - }); - - it('a settled phase is collapsed; the chevron expands the steps and collapses them again', () => { - render(); - const toggle = screen.getByTestId('tool-phase-toggle'); - expect(toggle).toHaveAttribute('aria-expanded', 'false'); - expect(screen.queryByTestId('tool-phase-steps-expanded')).not.toBeInTheDocument(); - fireEvent.click(toggle); - expect(toggle).toHaveAttribute('aria-expanded', 'true'); - const rows = screen.getByTestId('tool-phase-steps-expanded'); - expect(within(rows).getByText('List objects')).toBeInTheDocument(); - expect(within(rows).getByText('x3')).toBeInTheDocument(); - fireEvent.click(toggle); - expect(screen.queryByTestId('tool-phase-steps-expanded')).not.toBeInTheDocument(); - }); - - it('a plan that waits on the user does not hold the line open — its own card says so', () => { - const turn = designTurn(false); - const plan = { - status: 'blueprint_proposed', - blueprint: { objects: [{ name: 'book', label: 'Book', fields: [{ name: 'title' }] }] }, - }; - turn.toolInvocations = turn.toolInvocations!.map((tool) => - tool.toolName === 'propose_blueprint' - ? { ...tool, result: plan, proposedPlan: detectProposedPlan(plan) } - : tool, - ); - render(); - expect(screen.getByTestId('tool-phase-toggle')).toHaveAttribute('aria-expanded', 'false'); - expect(screen.getByTestId('tool-phase-headline')).toHaveTextContent(/^Design the plan · 4 steps/); - expect(screen.getByTestId('proposed-plan-awaiting')).toBeInTheDocument(); - }); - - it('a reopened phase (never measured here) omits the time instead of inventing one', () => { - render(); - expect(screen.getByTestId('tool-phase-headline')).toHaveTextContent(/^Design the plan · 4 steps$/); - }); - - it('a running step keeps the rows open, so its live timer is not hidden', () => { - const { container } = render( - , - ); - expect(screen.getByTestId('tool-phase-headline')).toHaveTextContent(/^Build · 2 steps/); - expect(screen.getByTestId('tool-phase-toggle')).toHaveAttribute('aria-expanded', 'true'); - expect(container.querySelector('[data-tool-running-timer]')).not.toBeNull(); - }); -}); - -const builtMessage = (opts: { published?: boolean; nextSteps?: string[] }): ChatbotEnhancedMessage => ({ - id: 'built-1', - role: 'assistant', - content: '', - buildProgress: { - phase: 'done', - appLabel: '图书借阅管理', - items: [ - { type: 'object', name: 'book' }, - { type: 'app', name: 'library_app' }, - ], - done: 2, - total: 2, - }, - toolInvocations: [ - { - toolCallId: 'apply-1', - toolName: 'apply_blueprint', - state: 'output-available', - result: { - status: opts.published ? 'published' : 'drafted', - packageId: 'app.hcpl', - drafted: [ - { type: 'object', name: 'book' }, - { type: 'app', name: 'library_app' }, - ], - }, - ...(opts.published - ? {} - : { - draftReview: { - packageId: 'app.hcpl', - items: [ - { type: 'object', name: 'book' }, - { type: 'app', name: 'library_app' }, - ], - ...(opts.nextSteps ? { nextSteps: opts.nextSteps } : {}), - }, - }), - }, - ], -}); - -describe('objectui#12724 — the finished build card', () => { - it('zh: a live build reads「已搭建并上线 · APP」, with both doors, the next-steps line and the posture', () => { - const onOpenBuiltApp = vi.fn(); - const onDesignBuiltApp = vi.fn(); - render( - inLocale( - 'zh', - , - ), - ); - expect(screen.getByTestId('build-progress-title')).toHaveTextContent('已搭建并上线 · 图书借阅管理'); - const open = screen.getByTestId('build-progress-open-app'); - const studio = screen.getByTestId('build-progress-design-app'); - expect(open).toHaveTextContent('打开应用'); - expect(open.className).toContain('bg-primary'); - expect(studio).toHaveTextContent('在 Studio 中查看'); - fireEvent.click(open); - expect(onOpenBuiltApp).toHaveBeenCalledWith('library_app'); - fireEvent.click(studio); - // The published envelope lifts no draft review; the package is its own. - expect(onDesignBuiltApp).toHaveBeenCalledWith('library_app', 'app.hcpl'); - expect(screen.getByTestId('build-result-posture')).toHaveTextContent( - '之后的修改先存草稿,在对话里点「发布」即可上线。', - ); - }); - - it('zh: the next-steps line quotes each of the envelope\'s `nextSteps`', () => { - render( - inLocale( - 'zh', - , - ), - ); - expect(screen.getByTestId('build-result-next-steps')).toHaveTextContent( - '接下来可以说:「给借阅记录加续借次数」 「只允许管理员删除图书」', - ); - // Said once: the draft card below no longer repeats them as a list. - expect(screen.queryByTestId('draft-next-steps')).not.toBeInTheDocument(); - }); - - it('a build with no publish signal only says it was built — never "live"', () => { - render(); - expect(screen.getByTestId('build-progress-title')).toHaveTextContent(/^Built 图书借阅管理$/); - expect(screen.queryByTestId('build-result-next-steps')).not.toBeInTheDocument(); - expect(screen.getByTestId('build-result-posture')).toBeInTheDocument(); - }); -}); - -/** A plan envelope shaped as the spec's `SolutionBlueprintSchema` declares it. */ -const planEnvelope = { - status: 'blueprint_proposed', - summary: '独立的图书借阅管理应用', - counts: { objects: 2, views: 1, dashboards: 0, seedData: 0 }, - blueprint: { - app: { name: 'library_app', label: '图书借阅管理' }, - objects: [ - { - name: 'book', - label: '图书', - fields: [ - { name: 'title', label: '书名', type: 'text' }, - { name: 'isbn', label: 'ISBN', type: 'text' }, - ], - }, - { name: 'reader', label: '读者', fields: [{ name: 'full_name', label: '姓名', type: 'text' }] }, - ], - views: [{ object: 'book', name: 'loan_board', label: '借阅看板', type: 'kanban', groupBy: 'status' }], - assumptions: ['只建这三部分'], - }, -}; - -const planMessage = (envelope: unknown): ChatbotEnhancedMessage => ({ - id: 'plan-1', - role: 'assistant', - content: '', - toolInvocations: [ - { - toolCallId: 'p1', - toolName: 'propose_blueprint', - state: 'output-available', - result: envelope, - proposedPlan: detectProposedPlan(envelope), - }, - ], -}); - -describe('objectui#12724 — the plan card from what the envelope declares', () => { - it('zh: the header names the app, each object row draws a chip per field, views get rows', () => { - render( - inLocale( - 'zh', - , - ), - ); - expect(screen.getByTestId('proposed-plan-title')).toHaveTextContent(/^方案 · 图书借阅管理$/); - expect(screen.getByTestId('proposed-plan-awaiting')).toHaveTextContent('等待确认'); - const book = screen.getByTestId('proposed-plan-object-book'); - expect(within(book).getAllByTestId('proposed-plan-field').map((c) => c.textContent)).toEqual([ - '书名', - 'ISBN', - ]); - const reader = screen.getByTestId('proposed-plan-object-reader'); - expect(within(reader).getAllByTestId('proposed-plan-field').map((c) => c.textContent)).toEqual(['姓名']); - expect(screen.getAllByTestId('proposed-plan-view').map((v) => v.textContent)).toEqual(['·借阅看板']); - expect(screen.getByTestId('proposed-plan-reply-hint')).toBeInTheDocument(); - expect(screen.queryByTestId('proposed-plan-object-chips')).not.toBeInTheDocument(); - }); - - it('degrades to today\'s object chips when the plan carries no field rows (the cache copy)', () => { - const countOnly = { - status: 'blueprint_proposed', - blueprint: { objects: [{ name: 'book', label: '图书', fields: [null, null, null, null] }] }, - }; - render(); - const chips = screen.getByTestId('proposed-plan-object-chips'); - expect(chips).toHaveTextContent('图书· 4'); - expect(screen.queryByTestId('proposed-plan-objects')).not.toBeInTheDocument(); - expect(screen.queryByTestId('proposed-plan-field')).not.toBeInTheDocument(); - expect(screen.queryByTestId('proposed-plan-views')).not.toBeInTheDocument(); - expect(screen.getByTestId('proposed-plan-title')).toHaveTextContent(/^Proposed plan$/); - }); -}); diff --git a/ui/packages/plugin-chatbot/src/__tests__/ChatbotEnhanced.buildChat-32984.test.tsx b/ui/packages/plugin-chatbot/src/__tests__/ChatbotEnhanced.buildChat-32984.test.tsx deleted file mode 100644 index 2730ea178dd..00000000000 --- a/ui/packages/plugin-chatbot/src/__tests__/ChatbotEnhanced.buildChat-32984.test.tsx +++ /dev/null @@ -1,337 +0,0 @@ -/** - * ObjectUI - * Copyright (c) 2024-present ObjectStack Inc. - * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. - * - * objectstack#32984 — the AI build chat, as a customer met it on cloud - * staging. Four of the card's five items live in this component (the fifth, - * the draft preview's list, is pinned in app-shell beside `ObjectView`): - * - * 1. the plan card said 已搭建 the moment a plan was confirmed, and kept - * saying it through six `apply_blueprint` refusals with nothing built; - * 2. a message typed while a turn ran went nowhere; - * 4. the build card printed the agent's own repair instruction verbatim; - * 5. the change card named objects and fields by their machine names. - * - * Every transcript goes through the real mapper from raw tool parts, and every - * interaction through the rendered component (Enter in the textarea, a click - * on the button), so the detector chain and the input pipeline run as they do - * in the console. - */ -import '@testing-library/jest-dom/vitest'; -import { describe, it, expect, vi } from 'vitest'; -import { act, fireEvent, render, screen, waitFor, within } from '@testing-library/react'; -import { ChatbotEnhanced } from '../ChatbotEnhanced'; -import { uiMessagesToChatMessages } from '../mapMessages'; - -const BLUEPRINT_PROPOSED = { - status: 'blueprint_proposed', - summary: 'A quoting app for a construction firm', - blueprint: { - objects: [{ name: 'b6bl_customer', label: 'Customer', fields: [{ name: 'name' }] }], - }, - counts: { objects: 1, views: 1, dashboards: 0, seedData: 1 }, - questions: [], - assumptions: [], -}; - -/** - * What the build gate answered on staging when the turn carried no confirmed - * blueprint identity. The producer is cloud's `apply_blueprint`; this repo - * holds no copy of its envelope, so the shape is the refusal's essentials: a - * status that is not a build, and the code the card quoted. - */ -const NOT_CONFIRMED = { - status: 'refused', - code: 'blueprint_not_confirmed', - message: 'The blueprint has not been confirmed by the user.', -}; - -const BUILD_DRAFTED = { - status: 'drafted', - summary: 'Created 1 object, 1 view', - drafted: [ - { type: 'object', name: 'b6bl_customer' }, - { type: 'app', name: 'b6bl' }, - ], -}; - -type ApplyPart = - | { output: unknown } - | { running: true } - | { errorText: string }; - -/** Propose, then one `apply_blueprint` per entry of `applies`, in order. */ -function transcript(applies: ApplyPart[]) { - return uiMessagesToChatMessages([ - { - id: 'a1', - role: 'assistant', - parts: [ - { - type: 'tool-propose_blueprint', - toolCallId: 'plan-1', - state: 'output-available', - output: { type: 'text', value: JSON.stringify(BLUEPRINT_PROPOSED) }, - }, - ], - }, - ...applies.map((apply, i) => ({ - id: `a${i + 2}`, - role: 'assistant' as const, - parts: [ - 'running' in apply - ? { type: 'tool-apply_blueprint', toolCallId: `apply-${i}`, state: 'input-available' } - : 'errorText' in apply - ? { - type: 'tool-apply_blueprint', - toolCallId: `apply-${i}`, - state: 'output-error', - errorText: apply.errorText, - } - : { - type: 'tool-apply_blueprint', - toolCallId: `apply-${i}`, - state: 'output-available', - output: { type: 'text', value: JSON.stringify(apply.output) }, - }, - ], - })), - ] as never); -} - -describe('objectstack#32984 item 1 — the plan card says what the build did', () => { - it('six refused applies: 未搭建成功, never 已搭建, and Build it is offered again', () => { - const refused = Array.from({ length: 6 }, () => ({ output: NOT_CONFIRMED })); - render(); - - expect(screen.queryByTestId('proposed-plan-built')).not.toBeInTheDocument(); - expect(screen.getByTestId('proposed-plan-build-failed')).toBeInTheDocument(); - expect(screen.getByTestId('proposed-plan-approve')).toBeInTheDocument(); - }); - - it('an apply that errored reads failed too', () => { - render( - , - ); - expect(screen.queryByTestId('proposed-plan-built')).not.toBeInTheDocument(); - expect(screen.getByTestId('proposed-plan-build-failed')).toBeInTheDocument(); - }); - - it('a running apply reads 正在搭建… while the turn is live, with no second Build it', () => { - render( - , - ); - expect(screen.getByTestId('proposed-plan-building')).toBeInTheDocument(); - expect(screen.queryByTestId('proposed-plan-built')).not.toBeInTheDocument(); - expect(screen.queryByTestId('proposed-plan-approve')).not.toBeInTheDocument(); - }); - - it('a running apply the turn never answered reads failed once the turn has ended', () => { - render(); - expect(screen.getByTestId('proposed-plan-build-failed')).toBeInTheDocument(); - expect(screen.queryByTestId('proposed-plan-built')).not.toBeInTheDocument(); - }); - - it('refused, then built: 已搭建 (the build outranks the earlier refusals)', () => { - render( - , - ); - expect(screen.getByTestId('proposed-plan-built')).toBeInTheDocument(); - expect(screen.queryByTestId('proposed-plan-build-failed')).not.toBeInTheDocument(); - }); - - it('a click after a refusal reads 已确认 until the next attempt speaks', () => { - const onSendMessage = vi.fn(); - const { rerender } = render( - , - ); - fireEvent.click(screen.getByTestId('proposed-plan-approve')); - expect(onSendMessage).toHaveBeenCalledTimes(1); - expect(screen.getByTestId('proposed-plan-confirmed')).toBeInTheDocument(); - expect(screen.queryByTestId('proposed-plan-build-failed')).not.toBeInTheDocument(); - - // The next attempt starts: it speaks over the click. - rerender( - , - ); - expect(screen.getByTestId('proposed-plan-building')).toBeInTheDocument(); - }); -}); - -describe('objectstack#32984 item 2 — a message typed during a turn is never dropped', () => { - it('Enter during a turn queues it in sight, and it is sent when the turn ends', async () => { - const onSendMessage = vi.fn(); - const { rerender } = render( - , - ); - const textarea = screen.getByPlaceholderText('Ask…') as HTMLTextAreaElement; - // The composer is live during the turn: the user can type. - expect(textarea).not.toBeDisabled(); - fireEvent.change(textarea, { target: { value: '在哪里打开这个应用?' } }); - fireEvent.keyDown(textarea, { key: 'Enter' }); - - const queued = await screen.findByTestId('composer-queued-item'); - expect(queued).toHaveTextContent('在哪里打开这个应用?'); - expect(queued).toHaveTextContent('Sends when the current reply finishes'); - expect(onSendMessage).not.toHaveBeenCalled(); - - // The turn ends: the queued message goes out, once, and leaves the queue. - rerender(); - await waitFor(() => expect(onSendMessage).toHaveBeenCalledTimes(1)); - expect(onSendMessage).toHaveBeenCalledWith('在哪里打开这个应用?', undefined); - expect(screen.queryByTestId('composer-queued-item')).not.toBeInTheDocument(); - }); - - it('Cancel takes it out of the queue and puts the text back in the box', async () => { - const onSendMessage = vi.fn(); - const { rerender } = render( - , - ); - const textarea = screen.getByPlaceholderText('Ask…') as HTMLTextAreaElement; - fireEvent.change(textarea, { target: { value: 'never mind' } }); - fireEvent.keyDown(textarea, { key: 'Enter' }); - fireEvent.click(await screen.findByTestId('composer-queued-cancel')); - - expect(screen.queryByTestId('composer-queued-item')).not.toBeInTheDocument(); - expect(textarea.value).toBe('never mind'); - rerender(); - await act(async () => { - await new Promise((r) => setTimeout(r, 10)); - }); - expect(onSendMessage).not.toHaveBeenCalled(); - }); - - it('control: with no turn running, Enter sends at once', async () => { - const onSendMessage = vi.fn(); - render(); - const textarea = screen.getByPlaceholderText('Ask…') as HTMLTextAreaElement; - fireEvent.change(textarea, { target: { value: 'hello' } }); - fireEvent.keyDown(textarea, { key: 'Enter' }); - await waitFor(() => expect(onSendMessage).toHaveBeenCalledTimes(1)); - expect(onSendMessage.mock.calls[0][0]).toBe('hello'); - expect(screen.queryByTestId('composer-queued-item')).not.toBeInTheDocument(); - }); -}); - -describe('objectstack#32984 item 4 — the build card speaks to the customer', () => { - const AGENT_TEXT = - 'Seed "b6bl_construction_project_sample" sets "quote" on none of its 12 row(s). Do NOT publish this seed with the column empty.'; - const withIssue = () => - uiMessagesToChatMessages([ - { - id: 'a1', - role: 'assistant', - parts: [ - { - type: 'tool-apply_blueprint', - toolCallId: 'apply-1', - state: 'output-available', - output: { - type: 'text', - value: JSON.stringify({ - ...BUILD_DRAFTED, - packageId: 'app.b6bl', - verification: { errors: 1, warnings: 0 }, - issues: [{ severity: 'error', code: 'seed_column_empty', message: AGENT_TEXT }], - }), - }, - }, - ], - }, - ] as never); - - it('shows a customer sentence; the agent text only behind Technical details', () => { - // The console wires the review door; the build card draws with it. - render(); - - const issues = screen.getByTestId('draft-issues'); - expect(within(issues).getByTestId('draft-issues-summary')).toHaveTextContent( - 'Some parts of this build need fixing before it is ready.', - ); - expect(within(issues).getByTestId('draft-issues-summary')).not.toHaveTextContent('Do NOT publish'); - // The agent's sentence is not the card's own line: it sits in a closed - // disclosure, and nowhere else on the card. - const details = within(issues).getByTestId('draft-issues-details') as HTMLDetailsElement; - expect(details.open).toBe(false); - expect(details).toHaveTextContent('Do NOT publish'); - const outside = Array.from(issues.children).filter((c) => c !== details); - for (const node of outside) expect(node).not.toHaveTextContent('Do NOT publish'); - // The chip says the count through the pack, not a hard-coded English plural. - expect(screen.getByTestId('draft-verification-chip')).toHaveTextContent('1 to fix'); - }); -}); - -describe('objectstack#32984 item 5 — the change card names things by label', () => { - const proposal = () => - uiMessagesToChatMessages([ - { - id: 'a1', - role: 'assistant', - parts: [ - { - type: 'tool-apply_edit', - toolCallId: 'call_1', - state: 'output-available', - input: {}, - output: { - status: 'changes_proposed', - posture: { mode: 'draft' }, - primaryAction: 'save_draft', - summary: '改动先存为草稿', - changes: [ - { - verb: 'modify_field', - object: 'b6bl_quote_item', - field: 'line_total', - type: 'currency', - details: '小计 · 不必填', - }, - ], - }, - }, - ], - }, - ] as never); - - it('object, field and type by their labels; the machine names stay on the tooltip', () => { - render( - (name === 'b6bl_quote_item' ? '报价明细' : undefined)} - resolveFieldLabel={(o, f) => (o === 'b6bl_quote_item' && f === 'line_total' ? '小计' : undefined)} - resolveFieldTypeLabel={(type) => (type === 'currency' ? '货币' : undefined)} - />, - ); - const target = screen.getByTestId('proposed-change-target'); - expect(target).toHaveTextContent('报价明细 · 小计'); - expect(target).not.toHaveTextContent('b6bl_quote_item'); - expect(target).toHaveAttribute('title', 'b6bl_quote_item.line_total'); - const params = screen.getByTestId('proposed-change-params'); - expect(params).toHaveTextContent('货币 · 小计 · 不必填'); - expect(params).not.toHaveTextContent('currency'); - }); - - it('control: a name the host does not know (about to be created) shows as given', () => { - render( - undefined} - resolveFieldLabel={() => undefined} - resolveFieldTypeLabel={() => undefined} - />, - ); - expect(screen.getByTestId('proposed-change-target')).toHaveTextContent('b6bl_quote_item · line_total'); - }); -}); diff --git a/ui/packages/plugin-chatbot/src/__tests__/ChatbotEnhanced.buildResultHeader-26469.test.tsx b/ui/packages/plugin-chatbot/src/__tests__/ChatbotEnhanced.buildResultHeader-26469.test.tsx deleted file mode 100644 index 934daa1e8db..00000000000 --- a/ui/packages/plugin-chatbot/src/__tests__/ChatbotEnhanced.buildResultHeader-26469.test.tsx +++ /dev/null @@ -1,196 +0,0 @@ -/** - * ObjectUI - * Copyright (c) 2024-present ObjectStack Inc. - * - * objectstack#26469 — the AI build page's progress panel and the build card's - * answer the Live Canvas header reads. - * - * 1. Progress items show the frame's `label` when it carries one and fall - * back to the machine name without it (the cloud half that adds `label` - * may land later; the panel must read right before and after). - * 2. `onBuildResult` hands the host the card's own answer — the app, the - * label its title names and whether its title says live — and fires again - * when that answer changes (the build is published). - * 3. A materialized build whose envelope says `appHidden: false` is listed, - * i.e. published, so the card reads live; `appHidden: true` does not. - * 4. The posture footnote names Publish in the chat, not Studio. - */ -import '@testing-library/jest-dom/vitest'; -import { describe, expect, it, vi } from 'vitest'; -import { render, screen } from '@testing-library/react'; -import { I18nProvider } from '@object-ui/i18n'; -import { ChatbotEnhanced, type ChatbotEnhancedMessage } from '../ChatbotEnhanced'; -import { detectDraftResult, uiMessageToChatMessage } from '../mapMessages'; - -function inLocale(lang: 'zh' | 'en', ui: React.ReactElement) { - return ( - {ui} - ); -} - -const building = (items: Array<{ type: string; name: string; label?: string }>): ChatbotEnhancedMessage => ({ - id: 'building-1', - role: 'assistant', - content: '', - streaming: true, - buildProgress: { phase: 'structure', appLabel: '家装项目管理', items, done: items.length, total: 8 }, -}); - -const items = [ - { type: 'object', name: 'u9ba_customer' }, - { type: 'app', name: 'home_renovation_management' }, -]; - -/** A finished whole-app build; the envelope varies per case. */ -const built = (envelope: Record): ChatbotEnhancedMessage => { - const result = { packageId: 'app.u9ba', drafted: items, ...envelope }; - const draftReview = detectDraftResult(result); - return { - id: 'built-1', - role: 'assistant', - content: '', - buildProgress: { phase: 'done', appLabel: '家装项目管理', items, done: 2, total: 2 }, - toolInvocations: [ - { - toolCallId: 'apply-1', - toolName: 'apply_blueprint', - state: 'output-available', - result, - ...(draftReview ? { draftReview } : {}), - }, - ], - }; -}; - -describe('objectstack#26469 — progress items show labels', () => { - it('a frame item with a label shows the label; one without falls back to the machine name', () => { - render( - , - ); - const panel = screen.getByTestId('build-progress'); - expect(panel).toHaveTextContent('客户'); - expect(panel).not.toHaveTextContent('u9ba_customer'); - expect(panel).toHaveTextContent('u9ba_project.project_list'); - }); - - it('the stream reader keeps an item label and leaves it off when the frame has none', () => { - const out = uiMessageToChatMessage({ - id: 'm1', - role: 'assistant', - parts: [ - { - type: 'data-build-progress', - id: 'build-progress', - data: { - phase: 'structure', - items: [ - { type: 'object', name: 'u9ba_customer', label: '客户' }, - { type: 'object', name: 'u9ba_project' }, - ], - }, - }, - ], - }); - expect(out.buildProgress?.items).toEqual([ - { type: 'object', name: 'u9ba_customer', label: '客户' }, - { type: 'object', name: 'u9ba_project' }, - ]); - }); -}); - -describe('objectstack#26469 — the card hands its answer to the host', () => { - it('a published build reports its label and live', () => { - const onBuildResult = vi.fn(); - render(); - expect(onBuildResult).toHaveBeenLastCalledWith({ - appName: 'home_renovation_management', - label: '家装项目管理', - live: true, - }); - }); - - it('an unpublished build reports not live, and reports again once it is published', () => { - const onBuildResult = vi.fn(); - const { rerender } = render( - , - ); - expect(onBuildResult).toHaveBeenLastCalledWith({ - appName: 'home_renovation_management', - label: '家装项目管理', - live: false, - }); - rerender(); - expect(onBuildResult).toHaveBeenLastCalledWith({ - appName: 'home_renovation_management', - label: '家装项目管理', - live: true, - }); - }); - - it('the checklist label wins over the stream label, as on the card title', () => { - const onBuildResult = vi.fn(); - const message = built({ - status: 'published', - checklist: { - status: 'passed', - passed: 1, - total: 1, - app: { name: 'home_renovation_management', label: '家装项目' }, - lines: [{ kind: 'object', status: 'passed', line: '对象 1 个' }], - }, - }); - render(); - expect(screen.getByTestId('build-progress-title')).toHaveTextContent(/· 家装项目$/); - expect(onBuildResult).toHaveBeenLastCalledWith({ - appName: 'home_renovation_management', - label: '家装项目', - live: true, - }); - }); -}); - -describe('objectstack#26469 — a listed materialized build is live', () => { - it('materialized with appHidden: false reads live on the card and in the report', () => { - const onBuildResult = vi.fn(); - render( - , - ); - expect(screen.getByTestId('build-progress-title')).toHaveTextContent(/^Built and live · 家装项目管理$/); - expect(onBuildResult).toHaveBeenLastCalledWith(expect.objectContaining({ live: true })); - }); - - it('materialized with appHidden: true is not live', () => { - const onBuildResult = vi.fn(); - render( - , - ); - expect(screen.getByTestId('build-progress-title')).toHaveTextContent(/^Built 家装项目管理$/); - expect(onBuildResult).toHaveBeenLastCalledWith(expect.objectContaining({ live: false })); - }); - - it('the draft review lifts appHidden only when the envelope says it', () => { - expect(detectDraftResult({ status: 'drafted', drafted: items, appHidden: false })?.appHidden).toBe(false); - expect(detectDraftResult({ status: 'drafted', drafted: items })).not.toHaveProperty('appHidden'); - }); -}); - -describe('objectstack#26469 — the posture footnote names Publish in the chat', () => { - it('zh', () => { - render(inLocale('zh', )); - expect(screen.getByTestId('build-result-posture')).toHaveTextContent('之后的修改先存草稿,在对话里点「发布」即可上线。'); - }); -}); diff --git a/ui/packages/plugin-chatbot/src/__tests__/ChatbotEnhanced.changeCardV2-12894.test.tsx b/ui/packages/plugin-chatbot/src/__tests__/ChatbotEnhanced.changeCardV2-12894.test.tsx deleted file mode 100644 index 34468a0d8c3..00000000000 --- a/ui/packages/plugin-chatbot/src/__tests__/ChatbotEnhanced.changeCardV2-12894.test.tsx +++ /dev/null @@ -1,340 +0,0 @@ -/** - * ObjectUI - * Copyright (c) 2024-present ObjectStack Inc. - * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. - * - * objectui#12894 (with objectui#12725's item 4) — the copilot's change card - * and applied card draw the draft posture cloud#2924 sends (the - * StudioRailCopilot artboard): - * - * - the change card: 「修改方案 · N 项」, one row per change (the + / ✎ / - - * symbol, the kind, `object · field`, the type and the row's `details` in - * small type), the posture note in amber for a live app with records, and - * the primary button labelled by `primaryAction` (存为草稿 for - * `save_draft`, the host's label for `confirm`); - * - the applied card: `appliedCard.title` and its lines, 查看变更并发布 (the - * host's review door) and 撤销 (the host's discard door, which drops EVERY - * pending draft of the package, so the card says so and asks first whenever - * other drafts are pending). - * - * An envelope from an older cloud carries none of the new keys and the card - * draws as before. Every message goes through the real mapper from a raw tool - * part, so the lift is under test too. - */ -import '@testing-library/jest-dom/vitest'; -import { describe, expect, it, vi } from 'vitest'; -import { act, fireEvent, render, screen, within } from '@testing-library/react'; -import { I18nProvider } from '@object-ui/i18n'; -import { ChatbotEnhanced } from '../ChatbotEnhanced'; -import { uiMessageToChatMessage } from '../mapMessages'; -import { PACKAGE_ID, draftedEnvelope, proposedEnvelope, type Lang } from './fixtures/changePosture.fixtures'; - -function inLocale(lang: Lang, ui: React.ReactElement) { - return ( - {ui} - ); -} - -/** The proposal turn: `apply_edit` answered with a `changes_proposed` envelope. */ -const proposalTurn = (envelope: unknown) => - uiMessageToChatMessage({ - id: 'a1', - role: 'assistant', - parts: [ - { type: 'tool-apply_edit', toolCallId: 'call_1', state: 'output-available', input: {}, output: envelope }, - ], - }); - -/** The confirm replay of that proposal (`replay_…`), answered with the applied envelope. */ -const replayTurn = (envelope: unknown) => - uiMessageToChatMessage({ - id: 'a2', - role: 'assistant', - parts: [ - { type: 'tool-apply_edit', toolCallId: 'replay_t2_0', state: 'output-available', input: {}, output: envelope }, - ], - }); - -describe('objectui#12894 — the change card draws the posture', () => { - it('zh: 「修改方案 · 2 项」, the rows, the amber note, and 存为草稿 as the primary action', () => { - render( - inLocale( - 'zh', - , - ), - ); - expect(screen.getByTestId('proposed-changes-title')).toHaveTextContent('修改方案 · 2 项'); - const note = screen.getByTestId('proposed-changes-posture-note'); - expect(note).toHaveTextContent('这个应用已上线,有 12 条记录在用。改动先存为草稿'); - expect(note.className).toContain('bg-amber-50'); - expect(screen.getByTestId('proposed-changes-confirm')).toHaveTextContent('存为草稿'); - expect(screen.getByTestId('proposed-changes-confirm')).not.toHaveTextContent('确认修改'); - expect(screen.getByTestId('proposed-changes-adjust')).toHaveTextContent('调整'); - }); - - it('zh: one row per change — symbol, kind, object · field, and the type and details in small type', () => { - render( - inLocale('zh', ), - ); - const rows = screen.getAllByTestId('proposed-change-row'); - expect(rows).toHaveLength(2); - const [field, view] = rows.map((r) => within(r)); - expect(rows[0]).toHaveAttribute('data-change', 'add'); - expect(field.getByTestId('proposed-change-symbol')).toHaveTextContent('+'); - expect(field.getByTestId('proposed-change-kind')).toHaveTextContent('字段'); - expect(field.getByTestId('proposed-change-target')).toHaveTextContent('lib_borrowing_record · renewal_count'); - const params = field.getByTestId('proposed-change-params'); - expect(params).toHaveTextContent('number · 续借次数 · 默认 0 · 不必填'); - expect(params.className).toContain('font-mono'); - expect(rows[1]).toHaveAttribute('data-change', 'modify'); - expect(view.getByTestId('proposed-change-symbol')).toHaveTextContent('✎'); - expect(view.getByTestId('proposed-change-kind')).toHaveTextContent('视图'); - expect(view.getByTestId('proposed-change-target')).toHaveTextContent('borrowing_board'); - }); - - it('en: the same card in English', () => { - render( - inLocale('en', ), - ); - expect(screen.getByTestId('proposed-changes-title')).toHaveTextContent('Change plan · 2 changes'); - expect(screen.getByTestId('proposed-changes-confirm')).toHaveTextContent('Save as draft'); - const [field, view] = screen.getAllByTestId('proposed-change-row').map((r) => within(r)); - expect(field.getByTestId('proposed-change-kind')).toHaveTextContent('Field'); - expect(field.getByTestId('proposed-change-params')).toHaveTextContent('number · Renewals · default 0 · optional'); - expect(view.getByTestId('proposed-change-kind')).toHaveTextContent('View'); - }); - - it('a removal row draws the remove symbol', () => { - const env = { - ...proposedEnvelope('en', 'draft'), - changes: [{ verb: 'delete_field', object: 'lib_borrowing_record', field: 'due_date' }], - }; - render(inLocale('en', )); - const row = screen.getByTestId('proposed-change-row'); - expect(row).toHaveAttribute('data-change', 'remove'); - expect(within(row).getByTestId('proposed-change-symbol')).toHaveTextContent('-'); - expect(screen.getByTestId('proposed-changes-title')).toHaveTextContent('Change plan · 1 change'); - }); - - it('`confirm` keeps the host label, and the publish posture reads its summary as plain text', () => { - render( - inLocale( - 'zh', - , - ), - ); - expect(screen.getByTestId('proposed-changes-confirm')).toHaveTextContent('确认修改'); - expect(screen.queryByTestId('proposed-changes-posture-note')).not.toBeInTheDocument(); - expect(screen.getByTestId('proposed-changes-summary')).toHaveTextContent('应用前请确认这次改动。'); - expect(screen.getByTestId('proposed-changes-title')).toHaveTextContent('修改方案 · 2 项'); - }); - - it('存为草稿 sends the same approval the host gave for Confirm: the cloud gate reads that text', () => { - const onSendMessage = vi.fn(); - render( - inLocale( - 'zh', - , - ), - ); - fireEvent.click(screen.getByTestId('proposed-changes-confirm')); - expect(onSendMessage).toHaveBeenCalledWith('确认修改,应用你刚才提议的改动。'); - }); - - it('an older cloud (no posture) draws the card as before: the host title, the v1 rows, the host label', () => { - render( - , - ); - const card = screen.getByTestId('proposed-changes'); - expect(card).toHaveTextContent('Confirm changes'); - expect(card).toHaveTextContent('Add field lib_borrowing_record.renewal_count (number) Renewals · default 0 · optional'); - expect(screen.queryByTestId('proposed-changes-title')).not.toBeInTheDocument(); - expect(screen.queryByTestId('proposed-change-row')).not.toBeInTheDocument(); - expect(screen.getByTestId('proposed-changes-confirm')).toHaveTextContent('Confirm'); - }); -}); - -describe('objectui#12894 — the applied card of a change saved as a draft', () => { - const renderApplied = ( - lang: Lang, - replay: unknown, - props: Partial> = {}, - ) => - render( - inLocale( - lang, - , - ), - ); - - it('zh: the title and lines as the producer wrote them, 查看变更并发布 and 撤销', () => { - const onReviewDrafts = vi.fn(); - const onDiscardDrafts = vi.fn(async () => true); - renderApplied('zh', draftedEnvelope('zh'), { onReviewDrafts, onDiscardDrafts, onPublishDrafts: vi.fn() }); - expect(screen.getByTestId('applied-card-title')).toHaveTextContent('已存为草稿 · 1 项未发布'); - expect(screen.getAllByTestId('applied-card-line').map((l) => l.textContent)).toEqual([ - '已有 12 条记录的续借次数为空', - '核对:结构 ✓', - ]); - expect(screen.getByTestId('applied-card-review')).toHaveTextContent('查看变更并发布'); - expect(screen.getByTestId('applied-card-discard')).toHaveTextContent('撤销'); - // The review door takes the inline publish button's place. - expect(screen.queryByTestId('proposed-changes-publish')).not.toBeInTheDocument(); - // …and the drafted badge's: the card's title says what happened. - expect(screen.queryByTestId('proposed-changes-drafted')).not.toBeInTheDocument(); - fireEvent.click(screen.getByTestId('applied-card-review')); - expect(onReviewDrafts).toHaveBeenCalledWith(PACKAGE_ID); - }); - - it('en: the same card in English', () => { - renderApplied('en', draftedEnvelope('en'), { onReviewDrafts: vi.fn(), onDiscardDrafts: vi.fn() }); - expect(screen.getByTestId('applied-card-title')).toHaveTextContent('Saved as a draft · 1 unpublished change(s)'); - expect(screen.getByTestId('applied-card-review')).toHaveTextContent('Review changes and publish'); - expect(screen.getByTestId('applied-card-discard')).toHaveTextContent('Undo'); - }); - - it('撤销 with no other draft pending runs the discard door at once, with the package id', async () => { - const onDiscardDrafts = vi.fn(async () => ({ ok: true })); - renderApplied('zh', draftedEnvelope('zh', { others: 0 }), { onDiscardDrafts }); - await act(async () => { - fireEvent.click(screen.getByTestId('applied-card-discard')); - }); - expect(onDiscardDrafts).toHaveBeenCalledTimes(1); - expect(onDiscardDrafts).toHaveBeenCalledWith(PACKAGE_ID); - expect(screen.getByTestId('applied-card-discarded')).toHaveTextContent('已撤销'); - expect(screen.queryByTestId('applied-card-discard')).not.toBeInTheDocument(); - }); - - it('撤销 with other drafts pending says so, and asks with the counts before it runs', async () => { - const onDiscardDrafts = vi.fn(async () => true); - renderApplied('zh', draftedEnvelope('zh', { others: 2 }), { onDiscardDrafts }); - expect(screen.getByTestId('applied-card-discard')).toHaveTextContent('撤销(连同另外 2 项草稿)'); - await act(async () => { - fireEvent.click(screen.getByTestId('applied-card-discard')); - }); - expect(onDiscardDrafts).not.toHaveBeenCalled(); - expect(screen.getByTestId('applied-card-discard-confirm-text')).toHaveTextContent( - '撤销会丢弃这个应用包全部 3 项未发布的草稿,其中 2 项不属于这次修改。', - ); - await act(async () => { - fireEvent.click(screen.getByTestId('applied-card-discard-confirm-run')); - }); - expect(onDiscardDrafts).toHaveBeenCalledWith(PACKAGE_ID); - expect(screen.getByTestId('applied-card-discarded')).toBeInTheDocument(); - }); - - it('en: the button and the confirm name the other drafts in English; cancelling runs nothing', async () => { - const onDiscardDrafts = vi.fn(); - renderApplied('en', draftedEnvelope('en', { others: 1 }), { onDiscardDrafts }); - expect(screen.getByTestId('applied-card-discard')).toHaveTextContent('Undo (and 1 other draft)'); - await act(async () => { - fireEvent.click(screen.getByTestId('applied-card-discard')); - }); - expect(screen.getByTestId('applied-card-discard-confirm-text')).toHaveTextContent( - 'Undo discards all 2 unpublished drafts of this package, including 1 that is not part of this change.', - ); - fireEvent.click(screen.getByTestId('applied-card-discard-cancel')); - expect(screen.queryByTestId('applied-card-discard-confirm')).not.toBeInTheDocument(); - expect(screen.getByTestId('applied-card-discard')).toBeInTheDocument(); - expect(onDiscardDrafts).not.toHaveBeenCalled(); - }); - - it('the live count wins over the snapshot: a later change staged more drafts, so 撤销 asks', async () => { - const onDiscardDrafts = vi.fn(async () => true); - // The snapshot says only this change was pending; the package holds 3 now. - const fetchPendingDraftCount = vi.fn(async () => 3); - renderApplied('zh', draftedEnvelope('zh', { others: 0 }), { onDiscardDrafts, fetchPendingDraftCount }); - await act(async () => { - fireEvent.click(screen.getByTestId('applied-card-discard')); - }); - expect(fetchPendingDraftCount).toHaveBeenCalledWith(PACKAGE_ID); - expect(onDiscardDrafts).not.toHaveBeenCalled(); - expect(screen.getByTestId('applied-card-discard-confirm-text')).toHaveTextContent( - '撤销会丢弃这个应用包全部 3 项未发布的草稿,其中 2 项不属于这次修改。', - ); - }); - - it('the live count confirming only this change is pending runs at once', async () => { - const onDiscardDrafts = vi.fn(async () => true); - renderApplied('zh', draftedEnvelope('zh', { others: 0 }), { - onDiscardDrafts, - fetchPendingDraftCount: vi.fn(async () => 1), - }); - await act(async () => { - fireEvent.click(screen.getByTestId('applied-card-discard')); - }); - expect(onDiscardDrafts).toHaveBeenCalledWith(PACKAGE_ID); - }); - - it('no draft state and no live count: 撤销 cannot tell what else is pending, so it asks', async () => { - const onDiscardDrafts = vi.fn(async () => true); - renderApplied('zh', draftedEnvelope('zh', { withDraftState: false }), { onDiscardDrafts }); - await act(async () => { - fireEvent.click(screen.getByTestId('applied-card-discard')); - }); - expect(onDiscardDrafts).not.toHaveBeenCalled(); - expect(screen.getByTestId('applied-card-discard-confirm-text')).toHaveTextContent( - '撤销会丢弃这个应用包里全部未发布的草稿,不只是这次修改。', - ); - }); - - it('a refused discard says so, with the host reason, and keeps 撤销', async () => { - const onDiscardDrafts = vi.fn(async () => ({ ok: false, error: 'forbidden' })); - renderApplied('zh', draftedEnvelope('zh'), { onDiscardDrafts }); - await act(async () => { - fireEvent.click(screen.getByTestId('applied-card-discard')); - }); - const failed = screen.getByTestId('applied-card-discard-failed'); - expect(failed).toHaveTextContent('撤销失败'); - expect(failed).toHaveTextContent('forbidden'); - expect(screen.getByTestId('applied-card-discard')).toBeInTheDocument(); - expect(screen.queryByTestId('applied-card-discarded')).not.toBeInTheDocument(); - }); - - it('without a review door the inline Publish keeps its place; without a discard door there is no 撤销', () => { - const onPublishDrafts = vi.fn(async () => true); - renderApplied('zh', draftedEnvelope('zh'), { onPublishDrafts, publishDraftsLabel: '发布' }); - expect(screen.getByTestId('applied-card-title')).toBeInTheDocument(); - expect(screen.queryByTestId('applied-card-review')).not.toBeInTheDocument(); - expect(screen.queryByTestId('applied-card-discard')).not.toBeInTheDocument(); - fireEvent.click(screen.getByTestId('proposed-changes-publish')); - expect(onPublishDrafts).toHaveBeenCalledWith(PACKAGE_ID); - }); - - it('an older cloud drafted replay draws the drafted badge and Publish, as before', () => { - const onPublishDrafts = vi.fn(async () => true); - renderApplied('en', draftedEnvelope('en', { withCard: false }), { - onPublishDrafts, - onReviewDrafts: vi.fn(), - onDiscardDrafts: vi.fn(), - }); - expect(screen.queryByTestId('applied-card')).not.toBeInTheDocument(); - expect(screen.getByTestId('proposed-changes-drafted')).toHaveTextContent('Saved as draft'); - fireEvent.click(screen.getByTestId('proposed-changes-publish')); - expect(onPublishDrafts).toHaveBeenCalledWith(PACKAGE_ID); - }); -}); diff --git a/ui/packages/plugin-chatbot/src/__tests__/ChatbotEnhanced.changesActionsWaitForTurn-10965.test.tsx b/ui/packages/plugin-chatbot/src/__tests__/ChatbotEnhanced.changesActionsWaitForTurn-10965.test.tsx deleted file mode 100644 index d2303ea3bc8..00000000000 --- a/ui/packages/plugin-chatbot/src/__tests__/ChatbotEnhanced.changesActionsWaitForTurn-10965.test.tsx +++ /dev/null @@ -1,297 +0,0 @@ -/** - * ObjectUI - * Copyright (c) 2024-present ObjectStack Inc. - * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. - * - * objectui#10965 — the confirm-changes card's actions wait for the turn to end. - * - * `update_metadata` returns `changes_proposed` mid-turn, and the card renders - * as soon as that result lands, but the proposing turn keeps streaming while - * the server stores each remaining step. A Confirm clicked in that window sent - * the next turn while the previous one was still being stored — the overlap - * objectui#10925 closed for the proposed-plan card. This card now waits on the - * same signal (`planActionsLocked`, i.e. `isLoading`). - * - * Every case feeds the wire shape through the real mapper with the flags - * `useObjectChat` derives from the AI SDK status: `isLoading` is - * `submitted | streaming`, and `uiMessagesToChatMessages` marks the trailing - * assistant message `streaming` from that same value. The harness mirrors - * `ChatbotEnhanced.planActionsWaitForTurn-10925.test.tsx`. - */ -import '@testing-library/jest-dom/vitest'; -import { describe, it, expect, vi } from 'vitest'; -import { render, screen, fireEvent, waitFor } from '@testing-library/react'; -import { ChatbotEnhanced } from '../ChatbotEnhanced'; -import { uiMessagesToChatMessages } from '../mapMessages'; - -type ChatStatus = 'submitted' | 'streaming' | 'ready'; -type WireMessage = Parameters[0][number]; - -const CONFIRM = 'CONFIRM_CHANGES'; - -/** `update_metadata` result: a proposal, not a commit. */ -const CHANGES = { - status: 'changes_proposed', - summary: 'Add a priority field to task', - changes: [{ verb: 'add_field', object: 'task', field: 'priority', type: 'select' }], -}; - -const wrap = (value: unknown) => ({ type: 'text' as const, value: JSON.stringify(value) }); - -/** - * The proposing turn as it looks mid-stream: the proposal has returned and the - * turn goes on with its closing prose. - */ -const proposingTurn: WireMessage = { - id: 'a1', - role: 'assistant', - parts: [ - { - type: 'tool-update_metadata', - toolCallId: 'chg-1', - state: 'output-available', - output: wrap(CHANGES), - }, - { type: 'text', text: 'Here is the change. Confirm it when you are ready.' }, - ], -} as WireMessage; - -const userTurn = (text: string): WireMessage => - ({ id: 'u2', role: 'user', parts: [{ type: 'text', text }] }) as WireMessage; - -/** Props exactly as `useObjectChat` hands them to the host for `status`. */ -function chatProps(wire: WireMessage[], status: ChatStatus) { - const isLoading = status === 'submitted' || status === 'streaming'; - return { - messages: uiMessagesToChatMessages(wire, { isStreaming: isLoading }), - isLoading, - }; -} - -/** The wire shape of the cloud AI quota refusal (objectui#7253), refused before any token streamed. */ -function quotaRefusal(): Error { - const e = new Error( - JSON.stringify({ - success: false, - error: { - code: 'AI_DESIGN_QUOTA_EXHAUSTED', - message: 'Quota used up.', - category: 'rate_limit', - details: { messageEn: 'Quota used up.', upgrade: true, resetsTonight: true }, - }, - }), - ) as Error & { notSent?: boolean; status?: number }; - e.notSent = true; - e.status = 429; - return e; -} - -function expectNoActions() { - expect(screen.queryByTestId('proposed-changes-confirm')).not.toBeInTheDocument(); - expect(screen.queryByTestId('proposed-changes-adjust')).not.toBeInTheDocument(); -} - -describe('ChatbotEnhanced — confirm-changes card actions wait for the proposing turn (objectui#10965)', () => { - it('disables Confirm and Adjust while the proposing turn streams, and a click sends nothing', () => { - const onSendMessage = vi.fn(); - const props = chatProps([proposingTurn], 'streaming'); - // Sanity: the card is on the turn that is still streaming. - expect(props.messages[0].streaming).toBe(true); - expect(props.messages[0].toolInvocations?.[0].proposedChanges).toBeTruthy(); - - render( - , - ); - - const confirm = screen.getByTestId('proposed-changes-confirm'); - const adjust = screen.getByTestId('proposed-changes-adjust'); - expect(confirm).toBeDisabled(); - expect(adjust).toBeDisabled(); - - fireEvent.click(confirm); - fireEvent.click(adjust); - expect(onSendMessage).not.toHaveBeenCalled(); - // The click did not flip the card to its optimistic Applying badge either. - expect(screen.queryByTestId('proposed-changes-applying')).not.toBeInTheDocument(); - }); - - it('enables them once that turn finishes, and Confirm then sends the confirmation', () => { - const onSendMessage = vi.fn(); - const wire = [proposingTurn]; - const { rerender } = render( - , - ); - expect(screen.getByTestId('proposed-changes-confirm')).toBeDisabled(); - - rerender( - , - ); - - const confirm = screen.getByTestId('proposed-changes-confirm'); - expect(confirm).toBeEnabled(); - expect(screen.getByTestId('proposed-changes-adjust')).toBeEnabled(); - - fireEvent.click(confirm); - expect(onSendMessage).toHaveBeenCalledTimes(1); - expect(onSendMessage).toHaveBeenCalledWith(CONFIRM); - }); - - it('holds an older card while a newer turn is in flight, though its own message is not streaming', () => { - const onSendMessage = vi.fn(); - const newerAssistantTurn: WireMessage = { - id: 'a3', - role: 'assistant', - parts: [{ type: 'text', text: 'Looking at the task object first' }], - } as WireMessage; - const typed = userTurn('Show me the task object first.'); - - // `submitted`: the request is out and no chunk has arrived, so NO message - // carries the streaming flag. - const submitted = chatProps([proposingTurn, typed], 'submitted'); - expect(submitted.messages.some((m) => m.streaming)).toBe(false); - const { rerender } = render( - , - ); - expect(screen.getByTestId('proposed-changes-confirm')).toBeDisabled(); - expect(screen.getByTestId('proposed-changes-adjust')).toBeDisabled(); - - // `streaming`: the newer turn streams below the older card. - const streaming = chatProps([proposingTurn, typed, newerAssistantTurn], 'streaming'); - expect(streaming.messages[0].streaming).toBe(false); - rerender( - , - ); - expect(screen.getByTestId('proposed-changes-confirm')).toBeDisabled(); - fireEvent.click(screen.getByTestId('proposed-changes-confirm')); - expect(onSendMessage).not.toHaveBeenCalled(); - - rerender( - , - ); - expect(screen.getByTestId('proposed-changes-confirm')).toBeEnabled(); - expect(screen.getByTestId('proposed-changes-adjust')).toBeEnabled(); - }); - - it("leaves the card's own states as they were: applying, quota-blocked, confirmed and the read-only hint", async () => { - // ① applying, optimistic — Confirm at `ready` flips the card, and the - // badge stays while the confirming turn is in flight. - const onSendMessage = vi.fn(); - const confirmed = [proposingTurn, userTurn(CONFIRM)]; - const first = render( - , - ); - fireEvent.click(screen.getByTestId('proposed-changes-confirm')); - expect(screen.getByTestId('proposed-changes-applying')).toBeInTheDocument(); - first.rerender( - , - ); - expect(screen.getByTestId('proposed-changes-applying')).toBeInTheDocument(); - expectNoActions(); - first.unmount(); - - // ② applying, from the replay — the runtime's `replay_` re-dispatch of the - // same tool is still running on the streaming tail. - const replayRunning: WireMessage = { - id: 'a3', - role: 'assistant', - parts: [{ type: 'tool-update_metadata', toolCallId: 'replay_u2_0', state: 'input-available' }], - } as WireMessage; - const second = render( - , - ); - expect(screen.getByTestId('proposed-changes-applying')).toBeInTheDocument(); - expectNoActions(); - second.unmount(); - - // ③ quota-blocked — a Confirm refused with a 429 parks the card, and it - // stays parked, with its next step, while a later turn is in flight. - const third = render( - , - ); - fireEvent.click(screen.getByTestId('proposed-changes-confirm')); - third.rerender( - , - ); - await waitFor(() => - expect(screen.getByTestId('proposed-changes-quota-blocked')).toBeInTheDocument(), - ); - third.rerender( - , - ); - expect(screen.getByTestId('proposed-changes-quota-blocked')).toBeInTheDocument(); - expect(screen.getByTestId('proposed-changes-quota-reason')).toBeInTheDocument(); - expectNoActions(); - third.unmount(); - - // ④ confirmed — the legacy collapse: a later same-tool call that is not a - // proposal, here on the turn that is still streaming. - const commitTurn: WireMessage = { - id: 'a3', - role: 'assistant', - parts: [ - { - type: 'tool-update_metadata', - toolCallId: 'chg-2', - state: 'output-available', - output: wrap({ success: true }), - }, - ], - } as WireMessage; - const fourth = render( - , - ); - expect(screen.getByTestId('proposed-changes-confirmed')).toBeInTheDocument(); - expectNoActions(); - fourth.unmount(); - - // ⑤ the read-only hint — no `onSendMessage`, no buttons, in flight or not. - render(); - expect(screen.getByTestId('proposed-changes')).toHaveTextContent( - 'Reply to confirm or adjust this change.', - ); - expectNoActions(); - }); -}); diff --git a/ui/packages/plugin-chatbot/src/__tests__/ChatbotEnhanced.changesCard.test.tsx b/ui/packages/plugin-chatbot/src/__tests__/ChatbotEnhanced.changesCard.test.tsx deleted file mode 100644 index a69bc2a1dea..00000000000 --- a/ui/packages/plugin-chatbot/src/__tests__/ChatbotEnhanced.changesCard.test.tsx +++ /dev/null @@ -1,116 +0,0 @@ -/** - * ObjectUI - * Copyright (c) 2024-present ObjectStack Inc. - * - * The granular confirm-before-change card (`status:'changes_proposed'`). - * - * Every string on this card — heading, buttons, hint, and the verb column of - * each change row — was a hard-coded Chinese literal until objectui#2884, so an - * English user read the whole confirm gate in Chinese. Worse, the confirm - * button SENT a Chinese sentence to the agent, which flips the agent's reply - * language for the rest of the thread. - */ -import '@testing-library/jest-dom/vitest'; -import { describe, it, expect, vi } from 'vitest'; -import { render, screen, fireEvent } from '@testing-library/react'; -import { ChatbotEnhanced, type ChatbotEnhancedMessage } from '../ChatbotEnhanced'; - -const CJK = /[一-鿿]/; - -function changesMessage(): ChatbotEnhancedMessage[] { - return [ - { - id: 'a1', - role: 'assistant', - content: '', - toolInvocations: [ - { - toolCallId: 't1', - toolName: 'update_metadata', - state: 'output-available', - proposedChanges: { - summary: 'Two edits to the task object', - changes: [ - { verb: 'add_field', object: 'task', field: 'priority', type: 'select' }, - { verb: 'delete_field', object: 'task', field: 'legacy_code' }, - ], - }, - }, - ], - }, - ]; -} - -describe('ChatbotEnhanced — confirm-before-change card', () => { - it('renders every label in English by default, with no CJK anywhere on the card', () => { - render(); - - const card = screen.getByTestId('proposed-changes'); - expect(card).toBeInTheDocument(); - expect(screen.getByText('Confirm changes')).toBeInTheDocument(); - expect(screen.getByTestId('proposed-changes-confirm')).toHaveTextContent('Confirm'); - expect(screen.getByTestId('proposed-changes-adjust')).toHaveTextContent('Adjust'); - - // The verb column — the part that used to read 新增字段 / 删除字段. - expect(card).toHaveTextContent('Add field task.priority (select)'); - expect(card).toHaveTextContent('Delete field task.legacy_code'); - - expect(card.textContent ?? '').not.toMatch(CJK); - }); - - it('sends an English confirmation, not a Chinese one, from an English surface', () => { - const onSendMessage = vi.fn(); - render(); - - fireEvent.click(screen.getByTestId('proposed-changes-confirm')); - - expect(onSendMessage).toHaveBeenCalledTimes(1); - const sent = onSendMessage.mock.calls[0][0] as string; - // The bug: this used to be '确认修改,应用你刚才提议的改动。' unconditionally, - // so clicking Confirm in an English session told the agent — in Chinese — - // to apply the changes, and the agent answered in Chinese from then on. - expect(sent).not.toMatch(CJK); - expect(sent).toMatch(/^Confirm\b/i); - }); - - it('honours caller-supplied labels and confirm message (the console passes translated ones)', () => { - const onSendMessage = vi.fn(); - render( - , - ); - - const card = screen.getByTestId('proposed-changes'); - expect(card).toHaveTextContent('新增字段 task.priority'); - expect(screen.getByTestId('proposed-changes-confirm')).toHaveTextContent('确认修改'); - - fireEvent.click(screen.getByTestId('proposed-changes-confirm')); - expect(onSendMessage).toHaveBeenCalledWith('确认修改,应用你刚才提议的改动。'); - }); - - it('falls back to the English verb name for a verb the caller did not translate', () => { - render( - , - ); - // `delete_field` is absent from the supplied map — it must not render as - // the raw `delete_field` token. - expect(screen.getByTestId('proposed-changes')).toHaveTextContent('Delete field task.legacy_code'); - }); - - it('shows the reply hint instead of buttons when there is no send handler', () => { - render(); - expect(screen.queryByTestId('proposed-changes-actions')).not.toBeInTheDocument(); - expect(screen.getByText('Reply to confirm or adjust this change.')).toBeInTheDocument(); - }); -}); diff --git a/ui/packages/plugin-chatbot/src/__tests__/ChatbotEnhanced.checklistVerification-34627.test.tsx b/ui/packages/plugin-chatbot/src/__tests__/ChatbotEnhanced.checklistVerification-34627.test.tsx deleted file mode 100644 index 814ae4c41ef..00000000000 --- a/ui/packages/plugin-chatbot/src/__tests__/ChatbotEnhanced.checklistVerification-34627.test.tsx +++ /dev/null @@ -1,159 +0,0 @@ -/** - * ObjectUI - * Copyright (c) 2024-present ObjectStack Inc. - * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. - * - * objectstack#34627 — the result card's checklist gains cloud's - * `ChecklistVerificationLine` (`{ kind: 'verification', status: 'failed', - * label, count }`), appended when the build's verdict has errors, with - * `status` and `passed/total` following the verdict. The console draws it as - * a red row (the producer's label, then the issue count), and a failed - * checklist is the one place the turn states the failure: the build's draft - * card draws neither its issue-count chip nor the red summary beside it. - * - * A line of any other kind that carries a valid `status` and a string `line` - * (cloud's `publish` line is the next one) is drawn by those two fields. - * - * The verification line's shape is the producer's `build-cards.schema.json` - * as the card names it; the vendored copy in `fixtures/build-cards.schema.ts` - * predates it, so these fixtures are not routed through the contract test. - * - * Each message goes through the real mapper (`uiMessageToChatMessage`) from a - * raw tool part, so the lift is under test, not a hand-built invocation. - */ -import '@testing-library/jest-dom/vitest'; -import { describe, expect, it, vi } from 'vitest'; -import { render, screen, within } from '@testing-library/react'; -import { I18nProvider } from '@object-ui/i18n'; -import { ChatbotEnhanced } from '../ChatbotEnhanced'; -import { detectBuildChecklist, uiMessageToChatMessage } from '../mapMessages'; -import { applyEnvelope, checklistOf } from './fixtures/buildCards.fixtures'; - -const VERIFICATION = { kind: 'verification', status: 'failed', label: '校验未通过', count: 3 } as const; - -/** Three objects and the board view, all passed, then the verification line: 4/5, failed. */ -function failedChecklist() { - const base = checklistOf('zh'); - return { ...base, status: 'failed', passed: 4, total: 5, lines: [...base.lines.slice(0, 4), VERIFICATION] }; -} - -const ISSUES = [ - { severity: 'error', code: 'seed_column_empty', message: 'Seed "loan_sample" sets "due_date" on none of its rows.' }, - { severity: 'error', code: 'view_filter_field', message: 'View "loan.overdue_loans" filters on an unknown field.' }, - { severity: 'error', code: 'seed_lookup', message: 'Seed "loan_sample" points at a missing reader.' }, -]; - -/** `apply_blueprint`'s envelope with the verdict's errors, and the checklist given. */ -const failedBuild = (checklist: unknown) => { - const { checklist: _served, ...envelope } = applyEnvelope('zh'); - return { - ...envelope, - verification: { errors: 3, warnings: 0 }, - issues: ISSUES, - ...(checklist === undefined ? {} : { checklist }), - }; -}; - -const turn = (output: unknown) => - uiMessageToChatMessage({ - id: 'built', - role: 'assistant', - parts: [{ type: 'tool-apply_blueprint', toolCallId: 'apply-1', state: 'output-available', input: {}, output }], - }); - -const renderBuild = (output: unknown) => - render( - - - , - ); - -describe('objectstack#34627 — detectBuildChecklist keeps the verification line and any new kind', () => { - it('a verification line is kept with its label and count', () => { - const checklist = detectBuildChecklist(failedBuild(failedChecklist()))!; - expect([checklist.status, checklist.passed, checklist.total]).toEqual(['failed', 4, 5]); - expect(checklist.lines).toHaveLength(5); - expect(checklist.lines[4]).toEqual({ kind: 'verification', status: 'failed', label: '校验未通过', count: 3 }); - }); - - it('a verification line without its label or count, or not failed, is dropped', () => { - for (const bad of [ - { ...VERIFICATION, label: '' }, - { ...VERIFICATION, count: -1 }, - { ...VERIFICATION, count: '3' }, - { ...VERIFICATION, status: 'passed' }, - { kind: 'verification', status: 'failed', line: '校验未通过 · 3' }, - ]) { - const checklist = detectBuildChecklist(failedBuild({ ...failedChecklist(), lines: [bad] }))!; - expect(checklist.lines).toEqual([]); - } - }); - - it('a line of another kind is kept by its status and line; one without them is dropped', () => { - const publish = { kind: 'publish', status: 'failed', outcome: 'rolled_back', reason: 'x', line: '发布已回滚' }; - const checklist = detectBuildChecklist( - failedBuild({ ...failedChecklist(), lines: [publish, { kind: 'publish', status: 'failed' }, { kind: 'publish', status: 'maybe', line: 'x' }] }), - )!; - expect(checklist.lines).toEqual([{ kind: 'other', servedKind: 'publish', status: 'failed', line: '发布已回滚' }]); - }); - - it('CONTROL: a checklist without the new line maps as before', () => { - expect(detectBuildChecklist(applyEnvelope('zh'))!.lines).toEqual( - checklistOf('zh').lines.map((l) => ({ kind: l.kind, status: l.status, line: l.line })), - ); - }); -}); - -describe('objectstack#34627 — a failed build: 4/5 over five rows, the failure stated once', () => { - it('the chip reads 4/5, five rows, one red row with the label and the issue count', () => { - renderBuild(failedBuild(failedChecklist())); - const chip = screen.getByTestId('build-checklist-chip'); - expect(chip).toHaveTextContent(/^核对通过 4\/5$/); - expect(chip).toHaveAttribute('data-status', 'failed'); - const rows = screen.getAllByTestId('build-checklist-line'); - expect(rows).toHaveLength(5); - const failed = rows.filter((r) => r.getAttribute('data-status') === 'failed'); - expect(failed).toHaveLength(1); - expect(failed[0]).toHaveAttribute('data-kind', 'verification'); - expect(failed[0]).toHaveTextContent(/^校验未通过 · 3 处待修复$/); - expect(failed[0].className).toContain('text-red-600'); - expect(within(failed[0]).getByTestId('build-checklist-verification-count')).toHaveTextContent('3 处待修复'); - }); - - it('the draft card draws no issue-count chip and no red summary; the findings stay behind Technical details', () => { - renderBuild(failedBuild(failedChecklist())); - expect(screen.queryByTestId('draft-verification-chip')).not.toBeInTheDocument(); - expect(screen.queryByTestId('draft-issues-summary')).not.toBeInTheDocument(); - expect(screen.getByTestId('draft-issues-details')).toBeInTheDocument(); - }); - - it('a new kind renders by its status and line beside the others', () => { - const publish = { kind: 'publish', status: 'failed', outcome: 'rolled_back', reason: 'x', line: '发布已回滚,应用保持原样' }; - const base = checklistOf('zh'); - renderBuild(failedBuild({ ...base, status: 'failed', passed: 7, total: 8, lines: [...base.lines, publish] })); - const rows = screen.getAllByTestId('build-checklist-line'); - expect(rows).toHaveLength(8); - expect(rows[7]).toHaveTextContent(/^发布已回滚,应用保持原样$/); - expect(rows[7]).toHaveAttribute('data-status', 'failed'); - expect(rows[7]).not.toHaveAttribute('data-kind'); - }); - - it('CONTROL: a passed checklist without the new line draws as before, and the draft card keeps its chip and summary', () => { - renderBuild(failedBuild(checklistOf('zh'))); - expect(screen.getByTestId('build-checklist-chip')).toHaveTextContent(/^核对通过 7\/7$/); - const rows = screen.getAllByTestId('build-checklist-line'); - expect(rows).toHaveLength(7); - for (const r of rows) expect(r).not.toHaveAttribute('data-kind'); - expect(screen.getByTestId('draft-verification-chip')).toHaveTextContent('3 处待修复'); - expect(screen.getByTestId('draft-issues-summary')).toBeInTheDocument(); - }); - - it('CONTROL: no checklist (an older producer): the draft card keeps its chip and summary', () => { - renderBuild(failedBuild(undefined)); - expect(screen.queryByTestId('build-checklist')).not.toBeInTheDocument(); - expect(screen.getByTestId('draft-verification-chip')).toHaveTextContent('3 处待修复'); - expect(screen.getByTestId('draft-issues-summary')).toBeInTheDocument(); - }); -}); diff --git a/ui/packages/plugin-chatbot/src/__tests__/ChatbotEnhanced.draftPreviewAny-12968.test.tsx b/ui/packages/plugin-chatbot/src/__tests__/ChatbotEnhanced.draftPreviewAny-12968.test.tsx deleted file mode 100644 index 8b586ef106e..00000000000 --- a/ui/packages/plugin-chatbot/src/__tests__/ChatbotEnhanced.draftPreviewAny-12968.test.tsx +++ /dev/null @@ -1,152 +0,0 @@ -/** - * ObjectUI - * Copyright (c) 2024-present ObjectStack Inc. - * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. - */ - -/** - * objectui#12968 (objectstack#24324 ruling A, preview-first) — the drafted - * result's Preview button appears for ANY draft kind, not only when the draft - * set includes an app. - * - * The drafted results here go through the chat's own lift - * (`detectDraftResult`), so each fixture is the envelope an authoring tool - * answers, not a hand-built `draftReview`. - * - * Pinned: - * - a field, view or page draft draws Preview, and the click hands the host - * the drafted items and the package's route segment (`onPreviewDraft`); - * - an app draft keeps today's button and callback (`onPreviewDraftApp`), - * unchanged; - * - CONTROL: a host that passes no `onPreviewDraft` (the read-only share page, - * any host that never opted in) draws no Preview for a non-app draft, and a - * published draft draws none at all; - * - Preview publishes nothing: no publish callback, no request. - */ -import '@testing-library/jest-dom/vitest'; -import { afterEach, describe, expect, it, vi } from 'vitest'; -import { cleanup, fireEvent, render, screen } from '@testing-library/react'; -import { ChatbotEnhanced, type ChatbotEnhancedMessage } from '../ChatbotEnhanced'; -import { detectDraftResult } from '../mapMessages'; - -afterEach(() => { - cleanup(); - vi.restoreAllMocks(); -}); - -/** One assistant message whose single tool part drafted `envelope`. */ -function draftedMessage(toolName: string, envelope: Record): ChatbotEnhancedMessage { - const draftReview = detectDraftResult(envelope); - if (!draftReview) throw new Error(`fixture is not a drafted envelope: ${JSON.stringify(envelope)}`); - return { - id: 'a1', - role: 'assistant', - content: '', - toolInvocations: [{ toolCallId: 't1', toolName, state: 'output-available', draftReview }], - }; -} - -/** `add_field` on an existing object: the draft is the OBJECT, its fields changed. */ -const FIELD_DRAFT = { - status: 'drafted', - type: 'object', - name: 'crm_account', - summary: 'Added field Priority', - changedKeys: ['fields'], - packageId: 'app.crm', -}; -const VIEW_DRAFT = { status: 'drafted', type: 'view', name: 'crm_account.pipeline', packageId: 'app.crm' }; -const PAGE_DRAFT = { status: 'drafted', type: 'page', name: 'crm_home', packageId: 'app.crm' }; - -describe('the drafted result Preview button (objectui#12968)', () => { - it.each([ - ['a field draft on an existing object', 'add_field', FIELD_DRAFT, [{ type: 'object', name: 'crm_account' }]], - ['a view draft', 'create_metadata', VIEW_DRAFT, [{ type: 'view', name: 'crm_account.pipeline' }]], - ['a page draft', 'create_metadata', PAGE_DRAFT, [{ type: 'page', name: 'crm_home' }]], - ])('%s draws Preview, and the click hands the host the drafted items and route segment', (_label, toolName, envelope, items) => { - const onPreviewDraft = vi.fn(); - const onPreviewDraftApp = vi.fn(); - render( - , - ); - fireEvent.click(screen.getByTestId('draft-preview')); - expect(onPreviewDraft).toHaveBeenCalledTimes(1); - expect(onPreviewDraft).toHaveBeenCalledWith(items, { appSegment: 'app.crm' }); - // Not the app door: a non-app draft has no app name to hand it. - expect(onPreviewDraftApp).not.toHaveBeenCalled(); - expect(screen.queryByTestId('draft-preview-app')).not.toBeInTheDocument(); - }); - - it('an app draft keeps the app button and its callback, unchanged', () => { - const onPreviewDraft = vi.fn(); - const onPreviewDraftApp = vi.fn(); - render( - , - ); - expect(screen.queryByTestId('draft-preview')).not.toBeInTheDocument(); - fireEvent.click(screen.getByTestId('draft-preview-app')); - expect(onPreviewDraftApp).toHaveBeenCalledWith('library', { materialized: false, appSegment: 'app.fh79' }); - expect(onPreviewDraft).not.toHaveBeenCalled(); - }); - - it('CONTROL: without onPreviewDraft a non-app draft draws no Preview, as before', () => { - render( - , - ); - expect(screen.getByTestId('draft-publish')).toBeInTheDocument(); - expect(screen.queryByTestId('draft-preview')).not.toBeInTheDocument(); - expect(screen.queryByTestId('draft-preview-app')).not.toBeInTheDocument(); - }); - - it('CONTROL: a draft without an owning package has no route segment, so no Preview', () => { - const { packageId: _dropped, ...noPackage } = FIELD_DRAFT; - render( - , - ); - expect(screen.queryByTestId('draft-preview')).not.toBeInTheDocument(); - }); - - it('Preview publishes nothing: no publish callback, no request', () => { - const onPublishDrafts = vi.fn(); - const fetchSpy = vi.spyOn(globalThis, 'fetch').mockResolvedValue(new Response('{}')); - render( - , - ); - fireEvent.click(screen.getByTestId('draft-preview')); - expect(onPublishDrafts).not.toHaveBeenCalled(); - expect(fetchSpy).not.toHaveBeenCalled(); - }); -}); diff --git a/ui/packages/plugin-chatbot/src/__tests__/ChatbotEnhanced.extendChip-11658.test.tsx b/ui/packages/plugin-chatbot/src/__tests__/ChatbotEnhanced.extendChip-11658.test.tsx deleted file mode 100644 index e5d46b33cac..00000000000 --- a/ui/packages/plugin-chatbot/src/__tests__/ChatbotEnhanced.extendChip-11658.test.tsx +++ /dev/null @@ -1,110 +0,0 @@ -/** - * ObjectUI - * Copyright (c) 2024-present ObjectStack Inc. - * - * objectui#11658 item 5 — the extend-mode scope chip ("+ Adding to existing - * app …") is localized and names the target app by its LABEL. - * - * Measured on the 2026-10-05 cloud acceptance run: a zh-CN user's plan card read - * `+ Adding to existing app "customer_management"` — an English literal the - * component defaulted to, around the app's machine name. Both chip sites carry - * it: the proposed-plan card and the live design panel (`BlueprintProgressPanel`). - * - * The predicate pinned is the class the acceptance names: under a non-English - * locale the chip carries NO ASCII-only literal. The target label below is - * Chinese on purpose, so any Latin letter left in the zh chip is an English - * word the component (or a missing pack key) put there. The machine name stays - * reachable, on the chip's tooltip. - */ -import '@testing-library/jest-dom/vitest'; -import { describe, it, expect, afterEach } from 'vitest'; -import { render, screen, cleanup } from '@testing-library/react'; -import { I18nProvider } from '@object-ui/i18n'; -import { ChatbotEnhanced, type ChatbotEnhancedMessage } from '../ChatbotEnhanced'; - -const TARGET = 'customer_management'; -const TARGET_LABEL = '客户管理'; -const resolveAppLabel = (name: string) => (name === TARGET ? TARGET_LABEL : undefined); - -function renderIn(language: string, ui: React.ReactElement) { - return render( - {ui}, - ); -} - -const planMessages = (targetApp: string): ChatbotEnhancedMessage[] => [ - { - id: 'a1', - role: 'assistant', - content: '', - toolInvocations: [ - { - toolCallId: 't1', - toolName: 'propose_blueprint', - state: 'output-available', - proposedPlan: { - summary: '跟进记录', - objects: [{ name: 'follow_up', label: '跟进', fieldCount: 3 }], - counts: { objects: 1, views: 0, dashboards: 0, seedData: 0 }, - questions: [], - assumptions: [], - targetApp, - }, - }, - ], - }, -]; - -const designingMessages = (targetApp: string): ChatbotEnhancedMessage[] => [ - { id: 'u1', role: 'user', content: '加一张跟进表' }, - { - id: 'a1', - role: 'assistant', - content: '', - streaming: true, - toolInvocations: [{ toolCallId: 't1', toolName: 'propose_blueprint', state: 'input-available' }], - blueprintProgress: { - phase: 'designing', - targetApp, - objects: [{ name: 'follow_up', label: '跟进', fields: 3 }], - }, - }, -]; - -/** Every Latin-letter run in a string — an English word, in a zh chip. */ -const latinWords = (text: string) => text.match(/[A-Za-z]+/g) ?? []; - -afterEach(cleanup); - -describe('the extend-mode scope chip (objectui#11658 item 5)', () => { - describe.each([ - ['the proposed-plan card', 'proposed-plan-extend', planMessages], - ['the live design panel', 'blueprint-progress-extend', designingMessages], - ] as const)('%s', (_where, testId, messages) => { - it('zh: carries no ASCII-only literal and names the app by its label', () => { - renderIn('zh', ); - const chip = screen.getByTestId(testId); - expect(chip.textContent).toContain(TARGET_LABEL); - expect(latinWords(chip.textContent ?? '')).toEqual([]); - expect(chip.textContent).not.toContain('Adding to existing app'); - // The machine name is not the chip's text; it stays on the tooltip. - expect(chip.textContent).not.toContain(TARGET); - expect(chip).toHaveAttribute('title', TARGET); - }); - - it('en: reads the English sentence around the label (control)', () => { - renderIn('en', ); - const chip = screen.getByTestId(testId); - expect(chip.textContent).toContain('Adding to existing app'); - expect(chip.textContent).toContain(TARGET_LABEL); - expect(chip.textContent).not.toContain(TARGET); - }); - - it('an app the resolver does not know is shown by the name given', () => { - renderIn('zh', ); - const chip = screen.getByTestId(testId); - expect(chip.textContent).toContain('orders'); - expect(latinWords(chip.textContent ?? '')).toEqual(['orders']); - }); - }); -}); diff --git a/ui/packages/plugin-chatbot/src/__tests__/ChatbotEnhanced.iterateOrNew-27480.test.tsx b/ui/packages/plugin-chatbot/src/__tests__/ChatbotEnhanced.iterateOrNew-27480.test.tsx deleted file mode 100644 index 77fd0db5fa5..00000000000 --- a/ui/packages/plugin-chatbot/src/__tests__/ChatbotEnhanced.iterateOrNew-27480.test.tsx +++ /dev/null @@ -1,181 +0,0 @@ -/** - * ObjectUI - * Copyright (c) 2024-present ObjectStack Inc. - * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. - * - * objectstack#27480 — a plan whose `decision` is `iterate_or_new` overlaps an - * app the user already has. The card drew it as an ordinary plan with a - * "Build it" button, so one click could build a duplicate of that app. It now - * asks the extend-or-new question in place of the plan's actions: the question - * names the existing app, and each of its two choices sends its answer. - * - * Every case feeds the wire shape through the real mapper, so what is pinned is - * the envelope the producer sends, not a hand-built `proposedPlan`. The plain - * proposal is the control: its "Build it" gate is untouched. - */ -import '@testing-library/jest-dom/vitest'; -import { describe, it, expect, vi, afterEach } from 'vitest'; -import { render, screen, fireEvent, cleanup } from '@testing-library/react'; -import { I18nProvider } from '@object-ui/i18n'; -import { ChatbotEnhanced } from '../ChatbotEnhanced'; -import { uiMessagesToChatMessages } from '../mapMessages'; - -type WireMessage = Parameters[0][number]; - -const PLAIN = { - status: 'blueprint_proposed', - summary: 'A reading-list app', - blueprint: { - objects: [{ name: 'book', label: 'Book', fields: [{ name: 'title' }, { name: 'author' }] }], - }, - counts: { objects: 1, views: 0, dashboards: 0, seedData: 0 }, - questions: [], -}; - -const ITERATE_OR_NEW = { - ...PLAIN, - decision: 'iterate_or_new', - existingAppOverlap: { name: 'library', label: '图书馆' }, -}; - -function proposal(result: unknown): WireMessage[] { - return [ - { id: 'u1', role: 'user', parts: [{ type: 'text', text: 'Build me a library app' }] }, - { - id: 'a1', - role: 'assistant', - parts: [ - { - type: 'tool-propose_blueprint', - toolCallId: 'plan-1', - state: 'output-available', - output: { type: 'text', value: JSON.stringify(result) }, - }, - ], - }, - ] as WireMessage[]; -} - -const messagesOf = (wire: WireMessage[]) => uiMessagesToChatMessages(wire, { isStreaming: false }); - -afterEach(cleanup); - -describe('the iterate_or_new plan asks extend-or-new instead of offering Build it (objectstack#27480)', () => { - it('renders the question naming the existing app, and no approve button', () => { - render(); - // The card's done-when first: no approval gate of any kind. - expect(screen.queryByTestId('proposed-plan-approve')).toBeNull(); - expect(screen.queryByTestId('proposed-plan-adjust')).toBeNull(); - expect(screen.queryByTestId('proposed-plan-fallback')).toBeNull(); - expect(screen.queryByText('Build it')).toBeNull(); - expect(screen.getByTestId('proposed-plan-iterate-or-new-question').textContent).toContain('图书馆'); - // The plan's own rows stay, so the user sees what would be built either way. - expect(screen.getByTestId('proposed-plan')).toBeInTheDocument(); - }); - - it('a plain proposal is unchanged: Build it, Adjust, and no question (control)', () => { - render(); - expect(screen.getByTestId('proposed-plan-approve')).toBeInTheDocument(); - expect(screen.getByTestId('proposed-plan-adjust')).toBeInTheDocument(); - expect(screen.queryByTestId('proposed-plan-iterate-or-new')).toBeNull(); - }); - - it('each choice sends its answer', () => { - const onSendMessage = vi.fn(); - render(); - fireEvent.click(screen.getByTestId('proposed-plan-extend-existing')); - expect(onSendMessage).toHaveBeenLastCalledWith('Keep improving "图书馆" instead of building a new app.'); - fireEvent.click(screen.getByTestId('proposed-plan-build-new')); - expect(onSendMessage).toHaveBeenLastCalledWith('Build a separate, new app.'); - expect(onSendMessage).toHaveBeenCalledTimes(2); - }); - - it("sends the host's outbound text when the host supplies it", () => { - const onSendMessage = vi.fn(); - render( - `在「${app}」上继续完善,不另建应用。`} - planBuildNewAppMessage="另建一个独立应用。" - />, - ); - fireEvent.click(screen.getByTestId('proposed-plan-extend-existing')); - expect(onSendMessage).toHaveBeenLastCalledWith('在「图书馆」上继续完善,不另建应用。'); - fireEvent.click(screen.getByTestId('proposed-plan-build-new')); - expect(onSendMessage).toHaveBeenLastCalledWith('另建一个独立应用。'); - }); - - it('zh: the question and both choices read in Chinese and name the app', () => { - render( - - - , - ); - expect(screen.getByTestId('proposed-plan-iterate-or-new-question').textContent).toContain('「图书馆」'); - expect(screen.getByTestId('proposed-plan-extend-existing').textContent).toBe('在「图书馆」上继续完善'); - expect(screen.getByTestId('proposed-plan-build-new').textContent).toBe('另建一个独立应用'); - }); - - it('still asks, and draws no fallback Build it, when the envelope names no object', () => { - const noObjects = { ...ITERATE_OR_NEW, blueprint: { objects: [] } }; - render(); - expect(screen.getByTestId('proposed-plan-iterate-or-new')).toBeInTheDocument(); - expect(screen.queryByTestId('proposed-plan-fallback')).toBeNull(); - expect(screen.queryByTestId('proposed-plan-approve')).toBeNull(); - }); - - it("names the app by the host's label when the envelope carries only its name", () => { - const nameOnly = { ...ITERATE_OR_NEW, existingAppOverlap: { name: 'library' } }; - render( - (name === 'library' ? 'Library' : undefined)} - />, - ); - expect(screen.getByTestId('proposed-plan-extend-existing').textContent).toBe('Keep improving "Library"'); - }); - - it('an overlap that names no app asks without a name, with a reply hint and no one-click choice', () => { - const unnamed = { ...ITERATE_OR_NEW, existingAppOverlap: {} }; - render(); - expect(screen.getByTestId('proposed-plan-iterate-or-new-question').textContent).toContain( - 'an app you already have', - ); - expect(screen.getByTestId('proposed-plan-iterate-or-new-hint')).toBeInTheDocument(); - expect(screen.queryByTestId('proposed-plan-iterate-or-new-choices')).toBeNull(); - expect(screen.queryByTestId('proposed-plan-approve')).toBeNull(); - }); - - it('a host that wires no message sending gets the question and a reply hint', () => { - render(); - expect(screen.getByTestId('proposed-plan-iterate-or-new-hint')).toBeInTheDocument(); - expect(screen.queryByTestId('proposed-plan-iterate-or-new-choices')).toBeNull(); - }); - - it('once a build has run after it, the question stays and its choices go', () => { - const wire: WireMessage[] = [ - ...proposal(ITERATE_OR_NEW), - { id: 'u2', role: 'user', parts: [{ type: 'text', text: 'Build a separate, new app.' }] }, - { - id: 'a2', - role: 'assistant', - parts: [ - { - type: 'tool-apply_blueprint', - toolCallId: 'build-1', - state: 'output-available', - output: { status: 'drafted', drafted: [{ type: 'object', name: 'book' }] }, - }, - ], - }, - ] as WireMessage[]; - render(); - expect(screen.getByTestId('proposed-plan-iterate-or-new-question')).toBeInTheDocument(); - expect(screen.queryByTestId('proposed-plan-iterate-or-new-choices')).toBeNull(); - expect(screen.queryByTestId('proposed-plan-iterate-or-new-hint')).toBeNull(); - }); -}); diff --git a/ui/packages/plugin-chatbot/src/__tests__/ChatbotEnhanced.needsAttention-32984.test.tsx b/ui/packages/plugin-chatbot/src/__tests__/ChatbotEnhanced.needsAttention-32984.test.tsx deleted file mode 100644 index 32c2f41530d..00000000000 --- a/ui/packages/plugin-chatbot/src/__tests__/ChatbotEnhanced.needsAttention-32984.test.tsx +++ /dev/null @@ -1,236 +0,0 @@ -/** - * ObjectUI - * Copyright (c) 2024-present ObjectStack Inc. - * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. - * - * objectstack#32984 — the published draft badge's failed-item suffix - * ("· N need attention") was hard-coded English, with an `s` picked on `=== 1`, - * in every locale. It now goes through the pack as a count family, so a zh - * console reads 「2 项需要处理」 and English agrees with its number. - * - * The publish-health line under the Published badge ("N sample rows live", - * "N views verified") spoke the same hard-coded English; it reads the pack too. - * Its findings (ruling B: the producer writes the customer sentence) show a - * finding's `userMessage` on the line; without one, the generic sentence the - * draft-issues block says. The agent text (`message`, `fix`) and the seed - * loader's engine text move under the folded "Technical details". - * - * Its own file: `I18nProvider` installs a module-level i18next global, which - * would leak into the provider-less renders of the other #32984 pins. - */ -import '@testing-library/jest-dom/vitest'; -import { describe, it, expect, vi } from 'vitest'; -import { render, screen, waitFor } from '@testing-library/react'; -import { I18nProvider } from '@object-ui/i18n'; -import { ChatbotEnhanced } from '../ChatbotEnhanced'; -import type { ChatbotEnhancedMessage, PublishHealth } from '../ChatbotEnhanced'; - -/** A drafted build whose package is already published, with `failed` items. */ -function publishedWithFailures(failedCount: number): ChatbotEnhancedMessage[] { - return [ - { - id: 'a1', - role: 'assistant', - content: '', - toolInvocations: [ - { - toolCallId: 't1', - toolName: 'apply_blueprint', - state: 'output-available', - draftReview: { - items: [{ type: 'object', name: 'customer' }], - packageId: 'app.crm', - failedCount, - }, - }, - ], - } as unknown as ChatbotEnhancedMessage, - ]; -} - -function renderIn(language: string, failedCount: number) { - return render( - - 0} - /> - , - ); -} - -describe('objectstack#32984 — the published badge counts failed items through the pack', () => { - it('zh-Hans reads the pack, not English', async () => { - renderIn('zh-Hans', 2); - expect(await screen.findByText(/PUBLISHED · 2 项需要处理/)).toBeInTheDocument(); - expect(screen.queryByText(/attention/)).not.toBeInTheDocument(); - }); - - it('en agrees with its number: one needs, two need', async () => { - const { unmount } = renderIn('en', 1); - expect(await screen.findByText(/PUBLISHED · 1 needs attention/)).toBeInTheDocument(); - unmount(); - renderIn('en', 2); - expect(await screen.findByText(/PUBLISHED · 2 need attention/)).toBeInTheDocument(); - }); - - it('control: no failed items, no suffix', async () => { - renderIn('en', 0); - expect(await screen.findByText('PUBLISHED')).toBeInTheDocument(); - expect(screen.queryByText(/attention/)).not.toBeInTheDocument(); - }); -}); - -/** Auto-publish a drafted build whose host answers `health`, under `language`. */ -async function publishHealthIn(language: string, health: PublishHealth) { - const user = { id: 'u1', role: 'user', content: 'build it' } as ChatbotEnhancedMessage; - const drafted = { - id: 'a1', - role: 'assistant', - content: 'Built your app.', - toolInvocations: [ - { - toolCallId: 'tc-health', - toolName: 'apply_blueprint', - state: 'output-available', - draftReview: { items: [{ type: 'object', name: 'task' }], packageId: 'app.todo', autoPublishable: true }, - }, - ], - } as unknown as ChatbotEnhancedMessage; - const onPublishDrafts = vi.fn().mockResolvedValue({ ok: true, health }); - const wrap = (messages: ChatbotEnhancedMessage[], isLoading: boolean) => ( - - - - ); - const view = render(wrap([user], true)); - view.rerender(wrap([user, drafted], false)); - await waitFor(() => expect(screen.getByTestId('publish-health')).toBeInTheDocument()); - return view; -} - -describe('objectstack#32984 — the publish-health line reads the pack', () => { - it('zh-Hans: the counts and the verified claim are Chinese, not English', async () => { - await publishHealthIn('zh-Hans', { seededRows: 6, checked: { seeds: 1, views: 2, widgets: 3 }, issues: [] }); - expect(screen.getByTestId('publish-health')).toHaveTextContent( - '6 条示例数据已上线 · 已核对 2 个视图 · 3 个仪表盘组件 · 1 组示例数据', - ); - expect(screen.queryByText(/sample|verified|view/)).not.toBeInTheDocument(); - }); - - it('ru: each count agrees with its number (one, few, many)', async () => { - await publishHealthIn('ru', { seededRows: 1, checked: { seeds: 5, views: 3, widgets: 21 }, issues: [] }); - expect(screen.getByTestId('publish-health')).toHaveTextContent( - 'опубликована 1 строка примеров · Проверено: 3 представления · 21 виджет · 5 наборов примеров', - ); - }); - - it('en agrees with its number: one row, two views', async () => { - await publishHealthIn('en', { seededRows: 1, checked: { seeds: 0, views: 2, widgets: 1 }, issues: [] }); - expect(screen.getByTestId('publish-health')).toHaveTextContent('1 sample row live · 2 views · 1 widget verified'); - }); - - it('control: an error withholds the verified claim, in Chinese as in English', async () => { - await publishHealthIn('zh-Hans', { - seededRows: 4, - checked: { seeds: 1, views: 1, widgets: 0 }, - issues: [{ severity: 'error', code: 'empty_query', message: 'widget "w1" returns NO data' }], - }); - expect(screen.getByText('4 条示例数据已上线')).toBeInTheDocument(); - expect(screen.queryByText(/已核对/)).not.toBeInTheDocument(); - }); -}); - -/** The text of the line itself: everything in it except the folded details. */ -function lineText(): string { - const root = screen.getByTestId('publish-health').cloneNode(true) as HTMLElement; - root.querySelectorAll('details').forEach((d) => d.remove()); - return root.textContent ?? ''; -} - -/** The folded technical details, which must stay closed until opened. */ -function detailsText(): string { - const details = screen.getByTestId('publish-health-details'); - expect(details).not.toHaveAttribute('open'); - return details.textContent ?? ''; -} - -describe('objectstack#32984 — a finding speaks on the line only through its producer\'s customer sentence', () => { - const AGENT = 'Seed "b6bl_project_sample" loaded 0 rows into object "b6bl_project"'; - const FIX = 'Check the publish response\'s seedApplied for the load error, and republish the seed.'; - - it('a finding with a userMessage shows it, and its agent text leaves the line', async () => { - await publishHealthIn('zh-Hans', { - checked: { seeds: 1, views: 0, widgets: 0 }, - issues: [ - { severity: 'error', code: 'seed_no_rows', message: AGENT, fix: FIX, userMessage: '「项目」的示例数据没有加载成功。' }, - ], - }); - expect(screen.getByTestId('publish-health-finding')).toHaveTextContent('「项目」的示例数据没有加载成功。'); - const line = lineText(); - expect(line).not.toContain(AGENT); - expect(line).not.toContain(FIX); - // Every finding here speaks for itself, so no generic sentence joins it. - expect(screen.queryByTestId('publish-health-summary')).not.toBeInTheDocument(); - expect(detailsText()).toContain(`${AGENT} — ${FIX}`); - expect(screen.getByText('技术详情')).toBeInTheDocument(); - }); - - it('a finding without one shows the generic sentence, and its agent text only under the details', async () => { - await publishHealthIn('zh-Hans', { - checked: { seeds: 1, views: 0, widgets: 0 }, - issues: [{ severity: 'error', code: 'seed_no_rows', message: AGENT, fix: FIX }], - }); - expect(screen.getByTestId('publish-health-summary')).toHaveTextContent( - '这次搭建有部分内容需要修复后才能使用。回复「修复这些问题」,助手会帮你处理。', - ); - expect(screen.queryByTestId('publish-health-finding')).not.toBeInTheDocument(); - expect(lineText()).not.toContain(AGENT); - expect(detailsText()).toContain(`${AGENT} — ${FIX}`); - }); - - it('warnings alone take the warnings sentence', async () => { - await publishHealthIn('en', { - checked: { seeds: 0, views: 1, widgets: 1 }, - issues: [{ severity: 'warning', code: 'probes_unavailable', message: '1 widget not probed' }], - }); - expect(screen.getByTestId('publish-health-summary')).toHaveTextContent(/The build is ready, with a few things worth checking/); - expect(lineText()).not.toContain('not probed'); - }); - - it('mixed: a voiced finding and an unvoiced one show the sentence and the generic line, both texts under the details', async () => { - await publishHealthIn('en', { - checked: { seeds: 1, views: 1, widgets: 0 }, - issues: [ - { severity: 'error', code: 'seed_no_rows', message: AGENT, userMessage: 'The sample projects did not load.' }, - { severity: 'warning', code: 'probes_unavailable', message: '1 widget not probed' }, - ], - }); - expect(screen.getByTestId('publish-health-finding')).toHaveTextContent('The sample projects did not load.'); - // An error is in the set, so the generic sentence is the errors one. - expect(screen.getByTestId('publish-health-summary')).toHaveTextContent(/need fixing/); - const details = detailsText(); - expect(details).toContain(AGENT); - expect(details).toContain('1 widget not probed'); - }); - - it('a failed seed reads the pack in a non-en locale, and the loader text is a detail', async () => { - await publishHealthIn('ja', { seedFailed: true, seedError: "seed apply stopped at the seed for object 'b6bl_project': boom" }); - expect(screen.getByTestId('publish-health-seed')).toHaveTextContent('サンプルデータを読み込めませんでした。'); - expect(lineText()).not.toMatch(/seed apply|Sample data/); - expect(detailsText()).toContain("seed apply stopped at the seed for object 'b6bl_project': boom"); - }); - - it('a failed seed with no producer text: the pack sentence, no English, no details', async () => { - await publishHealthIn('zh-Hans', { seedFailed: true }); - expect(screen.getByTestId('publish-health-seed')).toHaveTextContent('示例数据未能加载。'); - expect(screen.queryByText(/Sample data/)).not.toBeInTheDocument(); - expect(screen.queryByTestId('publish-health-details')).not.toBeInTheDocument(); - }); -}); diff --git a/ui/packages/plugin-chatbot/src/__tests__/ChatbotEnhanced.pendingCountPulse-26471.test.tsx b/ui/packages/plugin-chatbot/src/__tests__/ChatbotEnhanced.pendingCountPulse-26471.test.tsx deleted file mode 100644 index 45aa97c3628..00000000000 --- a/ui/packages/plugin-chatbot/src/__tests__/ChatbotEnhanced.pendingCountPulse-26471.test.tsx +++ /dev/null @@ -1,135 +0,0 @@ -/** - * ObjectUI - * Copyright (c) 2024-present ObjectStack Inc. - * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. - */ - -/** - * objectstack#26471 — a draft card's 发布 (N) follows a publish it did not - * run. The chat banner (and Studio) publish the package, then fire the host's - * live-metadata pulse; the card re-reads its package's pending count from the - * same `fetchPendingDraftCount` its first read used, and a count of 0 draws - * the Published badge instead of the button. - * - * Pinned: - * - 发布 (2) → pulse → the fetch now answers 0 → no 发布, Published shown; - * - a re-render alone fetches nothing (the count is re-read on a pulse, not - * per render); - * - unmount unsubscribes, and a later pulse fetches nothing. - */ -import '@testing-library/jest-dom/vitest'; -import { afterEach, describe, expect, it, vi } from 'vitest'; -import { act, cleanup, render, screen, waitFor } from '@testing-library/react'; -import { ChatbotEnhanced, type ChatbotEnhancedMessage } from '../ChatbotEnhanced'; -import { detectDraftResult } from '../mapMessages'; - -afterEach(() => { - cleanup(); -}); - -const PACKAGE_ID = 'app.crm'; - -/** One assistant message whose single tool part drafted a field into `app.crm`. */ -function draftedMessage(): ChatbotEnhancedMessage { - const draftReview = detectDraftResult({ - status: 'drafted', - type: 'object', - name: 'crm_account', - summary: 'Added field Priority', - changedKeys: ['fields'], - packageId: PACKAGE_ID, - }); - if (!draftReview) throw new Error('fixture is not a drafted envelope'); - return { - id: 'a1', - role: 'assistant', - content: '', - toolInvocations: [{ toolCallId: 't1', toolName: 'add_field', state: 'output-available', draftReview }], - }; -} - -/** The host's pulse, shaped like app-shell's `subscribeMetadataRefresh` / `emitMetadataRefresh`. */ -function makePulse() { - const listeners = new Set<() => void>(); - return { - listeners, - subscribe: (listener: () => void) => { - listeners.add(listener); - return () => { - listeners.delete(listener); - }; - }, - emit: () => { - for (const l of listeners) l(); - }, - }; -} - -function chat(pulse: ReturnType, fetchPendingDraftCount: (pkg: string) => Promise) { - return ( - - ); -} - -/** - * The button draws with the card, before the first count read answers; the - * count lands on a later render. `findByTestId` resolves on the button alone, - * so a one-shot text check after it races that render (objectstack#26647): - * wait for the render that carries the count. - */ -async function expectPublishButtonText(text: string) { - await waitFor(() => expect(screen.getByTestId('draft-publish')).toHaveTextContent(text)); -} - -describe('objectstack#26471 — the draft card re-reads its pending count on the metadata pulse', () => { - it('发布 (2), then a publish elsewhere fires the pulse and the card stops offering 发布', async () => { - const pulse = makePulse(); - let pending = 2; - const fetchPendingDraftCount = vi.fn(async (_pkg: string) => pending); - const { rerender } = render(chat(pulse, fetchPendingDraftCount)); - - await expectPublishButtonText('发布 (2)'); - expect(fetchPendingDraftCount).toHaveBeenCalledTimes(1); - expect(fetchPendingDraftCount).toHaveBeenCalledWith(PACKAGE_ID); - - // A re-render with nothing new is not a reason to read again. - rerender(chat(pulse, fetchPendingDraftCount)); - expect(fetchPendingDraftCount).toHaveBeenCalledTimes(1); - - // The banner published the package and pulsed; the server now has 0 pending. - pending = 0; - await act(async () => { - pulse.emit(); - }); - - expect(fetchPendingDraftCount).toHaveBeenCalledTimes(2); - expect(fetchPendingDraftCount).toHaveBeenLastCalledWith(PACKAGE_ID); - expect(screen.queryByTestId('draft-publish')).not.toBeInTheDocument(); - expect(screen.getByText('已发布')).toBeInTheDocument(); - }); - - it('unmount unsubscribes: a later pulse reads nothing', async () => { - const pulse = makePulse(); - const fetchPendingDraftCount = vi.fn(async (_pkg: string) => 2); - const { unmount } = render(chat(pulse, fetchPendingDraftCount)); - - await expectPublishButtonText('发布 (2)'); - expect(pulse.listeners.size).toBe(1); - - unmount(); - expect(pulse.listeners.size).toBe(0); - - pulse.emit(); - expect(fetchPendingDraftCount).toHaveBeenCalledTimes(1); - }); -}); diff --git a/ui/packages/plugin-chatbot/src/__tests__/ChatbotEnhanced.planActionsWaitForTurn-10925.test.tsx b/ui/packages/plugin-chatbot/src/__tests__/ChatbotEnhanced.planActionsWaitForTurn-10925.test.tsx deleted file mode 100644 index e09346edfbe..00000000000 --- a/ui/packages/plugin-chatbot/src/__tests__/ChatbotEnhanced.planActionsWaitForTurn-10925.test.tsx +++ /dev/null @@ -1,224 +0,0 @@ -/** - * ObjectUI - * Copyright (c) 2024-present ObjectStack Inc. - * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. - * - * objectui#10925 — the proposed-plan card's actions wait for the turn to end. - * - * The plan card renders as soon as `propose_blueprint` returns, but the - * proposing turn keeps streaming after that (a `todo_write`, the closing - * prose) while the server stores each step. In the 2026-09-28 cloud E2E the - * user clicked 「确认,开始搭建」 inside that window: the next turn was sent while - * the previous one was still being stored, and the stored history interleaved - * the two turns (root cause read on PR objectui#10924). - * - * Every case feeds the wire shape through the real mapper with the flags - * `useObjectChat` derives from the AI SDK status: `isLoading` is - * `submitted | streaming`, and `uiMessagesToChatMessages` marks the trailing - * assistant message `streaming` from that same value. - */ -import '@testing-library/jest-dom/vitest'; -import { describe, it, expect, vi } from 'vitest'; -import { render, screen, fireEvent } from '@testing-library/react'; -import { ChatbotEnhanced } from '../ChatbotEnhanced'; -import { uiMessagesToChatMessages } from '../mapMessages'; - -type ChatStatus = 'submitted' | 'streaming' | 'ready'; -type WireMessage = Parameters[0][number]; - -const Q_INTERVIEW = 'Track interviews as a separate object or a stage field?'; - -/** `propose_blueprint` result with no open questions. */ -const PLAN = { - status: 'blueprint_proposed', - summary: 'A reading-list app', - blueprint: { - objects: [{ name: 'book', label: 'Book', fields: [{ name: 'title' }, { name: 'author' }] }], - }, - counts: { objects: 1, views: 1, dashboards: 0, seedData: 0 }, - questions: [], - assumptions: [], -}; - -/** `propose_blueprint` result whose open question carries one-click answers. */ -const PLAN_WITH_CHOICE = { - ...PLAN, - questions: [Q_INTERVIEW], - questionChoices: [{ text: Q_INTERVIEW, options: ['Separate object', 'Stage field'] }], -}; - -/** - * The proposing turn as it looks mid-stream: the plan has returned, the turn - * goes on with a `todo_write` and its closing prose. - */ -function proposingTurn(planResult: unknown, output?: { type: 'text'; value: string }): WireMessage { - return { - id: 'a1', - role: 'assistant', - parts: [ - { - type: 'tool-propose_blueprint', - toolCallId: 'plan-1', - state: 'output-available', - output: output ?? { type: 'text', value: JSON.stringify(planResult) }, - }, - { type: 'tool-todo_write', toolCallId: 'todo-1', state: 'input-available' }, - { type: 'text', text: 'Here is the plan. Build it when you are ready.' }, - ], - } as WireMessage; -} - -/** Props exactly as `useObjectChat` hands them to the host for `status`. */ -function chatProps(wire: WireMessage[], status: ChatStatus) { - const isLoading = status === 'submitted' || status === 'streaming'; - return { - messages: uiMessagesToChatMessages(wire, { isStreaming: isLoading }), - isLoading, - }; -} - -const LABELS = { - planApproveMessage: 'APPROVE_PLAIN', - planApproveDefaultsMessage: 'APPROVE_DEFAULTS', - planAnswerMessage: (q: string, o: string) => `ANSWER:${q}=${o}`, -}; - -describe('ChatbotEnhanced — plan card actions wait for the proposing turn (objectui#10925)', () => { - it('disables Build it and Adjust while the proposing turn streams, and a click sends nothing', () => { - const onSendMessage = vi.fn(); - const props = chatProps([proposingTurn(PLAN)], 'streaming'); - // Sanity: the card is on the turn that is still streaming. - expect(props.messages[0].streaming).toBe(true); - expect(props.messages[0].toolInvocations?.[0].proposedPlan).toBeTruthy(); - - render(); - - const approve = screen.getByTestId('proposed-plan-approve'); - const adjust = screen.getByTestId('proposed-plan-adjust'); - expect(approve).toBeDisabled(); - expect(adjust).toBeDisabled(); - - fireEvent.click(approve); - expect(onSendMessage).not.toHaveBeenCalled(); - // The click did not flip the card to its optimistic Building badge either. - expect(screen.queryByTestId('proposed-plan-building')).not.toBeInTheDocument(); - }); - - it('enables them once that turn finishes, and Build it then sends the approval', () => { - const onSendMessage = vi.fn(); - const wire = [proposingTurn(PLAN)]; - const { rerender } = render( - , - ); - expect(screen.getByTestId('proposed-plan-approve')).toBeDisabled(); - - rerender(); - - const approve = screen.getByTestId('proposed-plan-approve'); - expect(approve).toBeEnabled(); - expect(screen.getByTestId('proposed-plan-adjust')).toBeEnabled(); - - fireEvent.click(approve); - expect(onSendMessage).toHaveBeenCalledTimes(1); - expect(onSendMessage).toHaveBeenCalledWith('APPROVE_PLAIN'); - }); - - it('holds the one-click answer chips the same way', () => { - const onSendMessage = vi.fn(); - const wire = [proposingTurn(PLAN_WITH_CHOICE)]; - const { rerender } = render( - , - ); - - const chip = screen.getByRole('button', { name: 'Stage field' }); - expect(chip).toBeDisabled(); - fireEvent.click(chip); - expect(onSendMessage).not.toHaveBeenCalled(); - - rerender(); - - const readyChip = screen.getByRole('button', { name: 'Stage field' }); - expect(readyChip).toBeEnabled(); - fireEvent.click(readyChip); - expect(onSendMessage).toHaveBeenCalledWith(`ANSWER:${Q_INTERVIEW}=Stage field`); - }); - - it('holds the fallback confirm card (a plan that did not parse) the same way', () => { - const onSendMessage = vi.fn(); - const wire = [ - proposingTurn(undefined, { type: 'text', value: 'I propose a small reading-list app.' }), - ]; - const streaming = chatProps(wire, 'streaming'); - // Sanity: no structured plan, so the fallback card is the one rendered. - expect(streaming.messages[0].toolInvocations?.[0].proposedPlan).toBeUndefined(); - - const { rerender } = render( - , - ); - expect(screen.getByTestId('proposed-plan-fallback')).toBeInTheDocument(); - expect(screen.getByTestId('proposed-plan-approve')).toBeDisabled(); - expect(screen.getByTestId('proposed-plan-adjust')).toBeDisabled(); - fireEvent.click(screen.getByTestId('proposed-plan-approve')); - expect(onSendMessage).not.toHaveBeenCalled(); - - rerender(); - expect(screen.getByTestId('proposed-plan-approve')).toBeEnabled(); - expect(screen.getByTestId('proposed-plan-adjust')).toBeEnabled(); - fireEvent.click(screen.getByTestId('proposed-plan-approve')); - expect(onSendMessage).toHaveBeenCalledWith('APPROVE_PLAIN'); - }); - - it('holds an older plan card while a newer turn is in flight, though its own message is not streaming', () => { - const onSendMessage = vi.fn(); - const finishedPlanTurn: WireMessage = { - id: 'a1', - role: 'assistant', - parts: [ - { - type: 'tool-propose_blueprint', - toolCallId: 'plan-1', - state: 'output-available', - output: { type: 'text', value: JSON.stringify(PLAN) }, - }, - ], - } as WireMessage; - const userTurn: WireMessage = { - id: 'u2', - role: 'user', - parts: [{ type: 'text', text: 'Add a rating field first.' }], - } as WireMessage; - const newerAssistantTurn: WireMessage = { - id: 'a3', - role: 'assistant', - parts: [{ type: 'text', text: 'Adding a rating field' }], - } as WireMessage; - - // `submitted`: the request is out and no chunk has arrived, so NO message - // carries the streaming flag. - const submitted = chatProps([finishedPlanTurn, userTurn], 'submitted'); - expect(submitted.messages.some((m) => m.streaming)).toBe(false); - const { rerender } = render( - , - ); - expect(screen.getByTestId('proposed-plan-approve')).toBeDisabled(); - - // `streaming`: the newer turn streams below the older card. - const streaming = chatProps([finishedPlanTurn, userTurn, newerAssistantTurn], 'streaming'); - expect(streaming.messages[0].streaming).toBe(false); - rerender(); - expect(screen.getByTestId('proposed-plan-approve')).toBeDisabled(); - fireEvent.click(screen.getByTestId('proposed-plan-approve')); - expect(onSendMessage).not.toHaveBeenCalled(); - - rerender( - , - ); - expect(screen.getByTestId('proposed-plan-approve')).toBeEnabled(); - }); -}); diff --git a/ui/packages/plugin-chatbot/src/__tests__/ChatbotEnhanced.planApprovalCount-25943.test.tsx b/ui/packages/plugin-chatbot/src/__tests__/ChatbotEnhanced.planApprovalCount-25943.test.tsx deleted file mode 100644 index 1bc47920695..00000000000 --- a/ui/packages/plugin-chatbot/src/__tests__/ChatbotEnhanced.planApprovalCount-25943.test.tsx +++ /dev/null @@ -1,151 +0,0 @@ -/** - * ObjectUI - * Copyright (c) 2024-present ObjectStack Inc. - * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. - * - * objectstack#25943 — `onPlanApprovalPendingChange(pending, count)` also says - * how many items the newest proposal asks the user to confirm, so Studio's - * right slot can show 「AI 副驾 · N 项待确认」 beside the folded copilot. - * - * - a change plan (the copilot's 「修改方案 · N 项」 card) is a proposal: it is - * pending while its card offers 存为草稿 / Confirm, and `count` is its rows; - * - a proposed plan counts 1, as before it read `true`; - * - nothing pending is `(false, 0)`. - * - * Every case asserts the reading AND the card it mirrors. The envelopes are the - * real wire shapes, fed through the real mapper. - */ -import '@testing-library/jest-dom/vitest'; -import { describe, expect, it, vi } from 'vitest'; -import { fireEvent, render, screen } from '@testing-library/react'; -import { ChatbotEnhanced } from '../ChatbotEnhanced'; -import { uiMessageToChatMessage, uiMessagesToChatMessages } from '../mapMessages'; -import { changeRows, draftedEnvelope, proposedEnvelope } from './fixtures/changePosture.fixtures'; - -/** The proposal turn: `apply_edit` answered with a `changes_proposed` envelope. */ -const proposalTurn = (envelope: unknown, id = 'a1', toolCallId = 'call_1') => - uiMessageToChatMessage({ - id, - role: 'assistant', - parts: [{ type: 'tool-apply_edit', toolCallId, state: 'output-available', input: {}, output: envelope }], - }); - -/** The confirm replay of that proposal (`replay_…`), answered with the applied envelope. */ -const replayTurn = (envelope: unknown) => - uiMessageToChatMessage({ - id: 'a2', - role: 'assistant', - parts: [{ type: 'tool-apply_edit', toolCallId: 'replay_t2_0', state: 'output-available', input: {}, output: envelope }], - }); - -/** A `propose_blueprint` turn: a proposed plan whose card offers "Build it". */ -const planTurn = (id = 'p1') => - uiMessagesToChatMessages([ - { - id, - role: 'assistant' as const, - parts: [ - { - type: 'tool-propose_blueprint', - toolCallId: `plan-${id}`, - state: 'output-available', - output: { - type: 'text', - value: JSON.stringify({ - status: 'blueprint_proposed', - summary: 'Helpdesk', - blueprint: { objects: [{ name: 'ticket', label: 'Ticket', fields: [{ name: 'subject' }] }] }, - counts: { objects: 1, views: 1, dashboards: 0, seedData: 0 }, - questions: [], - assumptions: [], - }), - }, - }, - ], - }, - ])[0]; - -/** The last reading the host was told, as `[pending, count]`. */ -const lastReading = (spy: ReturnType) => spy.mock.calls.at(-1); - -describe('ChatbotEnhanced — onPlanApprovalPendingChange carries the count (objectstack#25943)', () => { - it('a change plan awaiting 存为草稿 reads (true, its rows)', () => { - const spy = vi.fn(); - render( - , - ); - expect(screen.getByTestId('proposed-changes-confirm')).toBeInTheDocument(); - expect(screen.getAllByTestId('proposed-change-row')).toHaveLength(2); - expect(lastReading(spy)).toEqual([true, 2]); - }); - - it('the click ends the wait at once (the applying flip), before any replay lands', () => { - const spy = vi.fn(); - render( - , - ); - fireEvent.click(screen.getByTestId('proposed-changes-confirm')); - expect(screen.getByTestId('proposed-changes-applying')).toBeInTheDocument(); - expect(lastReading(spy)).toEqual([false, 0]); - }); - - it('a change the replay saved as a draft is no longer pending', () => { - const spy = vi.fn(); - render( - , - ); - expect(screen.queryByTestId('proposed-changes-confirm')).toBeNull(); - expect(lastReading(spy)).toEqual([false, 0]); - }); - - it('a proposed plan counts 1, and a newer change plan supersedes it with its own rows', () => { - const spy = vi.fn(); - const { rerender } = render( - , - ); - expect(screen.getByTestId('proposed-plan-approve')).toBeInTheDocument(); - expect(lastReading(spy)).toEqual([true, 1]); - - const single = { ...proposedEnvelope('en', 'draft'), changes: changeRows('en').slice(0, 1) }; - rerender( - , - ); - expect(screen.getAllByTestId('proposed-change-row')).toHaveLength(1); - expect(lastReading(spy)).toEqual([true, 1]); - expect(spy).toHaveBeenCalledTimes(1); - - rerender( - , - ); - expect(lastReading(spy)).toEqual([true, 2]); - }); - - it('nothing proposed reads (false, 0)', () => { - const spy = vi.fn(); - render(); - expect(spy).toHaveBeenCalledTimes(1); - expect(lastReading(spy)).toEqual([false, 0]); - }); -}); diff --git a/ui/packages/plugin-chatbot/src/__tests__/ChatbotEnhanced.planApprovalPending-11666.test.tsx b/ui/packages/plugin-chatbot/src/__tests__/ChatbotEnhanced.planApprovalPending-11666.test.tsx deleted file mode 100644 index 80169d0776b..00000000000 --- a/ui/packages/plugin-chatbot/src/__tests__/ChatbotEnhanced.planApprovalPending-11666.test.tsx +++ /dev/null @@ -1,204 +0,0 @@ -/** - * ObjectUI - * Copyright (c) 2024-present ObjectStack Inc. - * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. - * - * objectui#11666 — `onPlanApprovalPendingChange` reports whether the thread's - * NEWEST proposed plan still waits for the user, so a host can mirror it - * outside the chat (the console's launchers show a marker while the chat is - * closed). - * - * The reading must be the plan card's own: `pending` from - * `resolveProposalCardState`, i.e. exactly when the card offers "Build it". - * Every case below asserts the callback AND the card it mirrors, so the two can - * never be pinned apart. The envelopes are the real wire shapes, fed through - * the real mapper (`uiMessagesToChatMessages`), as in the objectui#8343 suite. - */ -import '@testing-library/jest-dom/vitest'; -import { describe, it, expect, vi } from 'vitest'; -import { render, screen, fireEvent } from '@testing-library/react'; -import { ChatbotEnhanced } from '../ChatbotEnhanced'; -import { uiMessagesToChatMessages } from '../mapMessages'; - -function proposal(summary: string) { - return { - status: 'blueprint_proposed', - summary, - blueprint: { - objects: [{ name: 'ticket', label: 'Ticket', fields: [{ name: 'subject' }] }], - }, - counts: { objects: 1, views: 1, dashboards: 0, seedData: 0 }, - questions: [], - assumptions: [], - }; -} - -const BUILD_DRAFTED = { - status: 'drafted', - summary: 'Created 1 object', - drafted: [{ type: 'object', name: 'ticket' }], -}; - -const AWAITING_CONFIRMATION = { - status: 'awaiting_confirmation', - message: 'A confirm card for this blueprint was just shown to the user.', -}; - -type Part = { type: string; toolCallId?: string; state?: string; output?: unknown; text?: string }; - -function toolPart(tool: string, toolCallId: string, result: unknown): Part { - return { - type: `tool-${tool}`, - toolCallId, - state: 'output-available', - output: { type: 'text', value: JSON.stringify(result) }, - }; -} - -function thread(...turns: Part[][]) { - return uiMessagesToChatMessages( - turns.map((parts, i) => ({ id: `a${i + 1}`, role: 'assistant' as const, parts })), - ); -} - -/** The last value the host was told. */ -function lastReading(spy: ReturnType): unknown { - return spy.mock.calls.at(-1)?.[0]; -} - -describe('ChatbotEnhanced — onPlanApprovalPendingChange (objectui#11666)', () => { - it('reports true while the proposed plan offers "Build it"', () => { - const spy = vi.fn(); - render( - , - ); - expect(screen.getByTestId('proposed-plan-approve')).toBeInTheDocument(); - expect(lastReading(spy)).toBe(true); - }); - - it('reports false for a thread with no proposed plan', () => { - const spy = vi.fn(); - render( - , - ); - expect(spy).toHaveBeenCalledTimes(1); - expect(lastReading(spy)).toBe(false); - }); - - it('turns false the moment the user approves (the optimistic "Building…" flip)', () => { - const spy = vi.fn(); - render( - , - ); - expect(lastReading(spy)).toBe(true); - - fireEvent.click(screen.getByTestId('proposed-plan-approve')); - - expect(screen.getByTestId('proposed-plan-confirmed')).toBeInTheDocument(); - expect(lastReading(spy)).toBe(false); - }); - - it('turns false once the build ran, and stays true while the build only asked to confirm (#8343)', () => { - const plan = toolPart('propose_blueprint', 'plan-1', proposal('Helpdesk')); - const spy = vi.fn(); - const { rerender } = render( - , - ); - // A confirm-gate preview built nothing — the plan is still the user's to approve. - expect(screen.getByTestId('proposed-plan-approve')).toBeInTheDocument(); - expect(lastReading(spy)).toBe(true); - - rerender( - , - ); - expect(screen.getByTestId('proposed-plan-built')).toBeInTheDocument(); - expect(lastReading(spy)).toBe(false); - }); - - it('follows the NEWEST plan: a newer proposal supersedes the one before it', () => { - const first = toolPart('propose_blueprint', 'plan-1', proposal('Helpdesk')); - const build = toolPart('apply_blueprint', 'apply-1', BUILD_DRAFTED); - const second = toolPart('propose_blueprint', 'plan-2', proposal('Helpdesk with SLAs')); - const spy = vi.fn(); - const { rerender } = render( - , - ); - expect(lastReading(spy)).toBe(false); - - // A newer proposal after a built one: the newer card is the one awaiting. - rerender( - , - ); - expect(screen.getAllByTestId('proposed-plan-approve')).toHaveLength(1); - expect(lastReading(spy)).toBe(true); - }); - - it('an older plan a newer one superseded does not keep the reading alive', () => { - const spy = vi.fn(); - // The two plans sit in two turns, a user message between them: within ONE - // turn the older plan draws no card at all (one plan card per build turn). - render( - , - ); - expect(lastReading(spy)).toBe(true); - - // Approving the newer plan ends the wait, even though the superseded card - // above it still renders its own (stale) "Build it". - fireEvent.click(screen.getAllByTestId('proposed-plan-approve')[1]); - expect(screen.getAllByTestId('proposed-plan-approve')).toHaveLength(1); - expect(lastReading(spy)).toBe(false); - }); - - it('announces a change once — a fresh callback identity does not re-announce an unchanged reading', () => { - const messages = thread([toolPart('propose_blueprint', 'plan-1', proposal('Helpdesk'))]); - const first = vi.fn(); - const { rerender } = render( - , - ); - expect(first).toHaveBeenCalledTimes(1); - - const second = vi.fn(); - rerender( - , - ); - expect(first).toHaveBeenCalledTimes(1); - expect(second).not.toHaveBeenCalled(); - }); -}); diff --git a/ui/packages/plugin-chatbot/src/__tests__/ChatbotEnhanced.planCardGeneratedName-13004.test.tsx b/ui/packages/plugin-chatbot/src/__tests__/ChatbotEnhanced.planCardGeneratedName-13004.test.tsx deleted file mode 100644 index 126ceae9ae8..00000000000 --- a/ui/packages/plugin-chatbot/src/__tests__/ChatbotEnhanced.planCardGeneratedName-13004.test.tsx +++ /dev/null @@ -1,77 +0,0 @@ -/** - * ObjectUI - * Copyright (c) 2024-present ObjectStack Inc. - * - * objectui#13004 — the plan card draws a composed record title's line (the - * AiBuild artboard's 「名称:自动生成「{图书} · {读者} · {借出日期}」,表单里不出现」) - * from the `planCard.objects[].nameField.generated` key objectstack-ai/cloud - * declares (`build-cards.schema.json`, vendored as `fixtures/build-cards.schema.ts`), - * in place of the plain 「名称:LABEL」 line. An object without the key draws as before. - * - * Each message goes through the real mapper (`uiMessageToChatMessage`) from a - * raw tool part, so the lift is under test, not a hand-built invocation. - */ -import '@testing-library/jest-dom/vitest'; -import { describe, expect, it, vi } from 'vitest'; -import { render, screen, within } from '@testing-library/react'; -import { I18nProvider } from '@object-ui/i18n'; -import { ChatbotEnhanced } from '../ChatbotEnhanced'; -import { uiMessageToChatMessage } from '../mapMessages'; -import { planEnvelope } from './fixtures/buildCards.fixtures'; - -const turn = (output: unknown) => - uiMessageToChatMessage({ - id: 'plan', - role: 'assistant', - parts: [{ type: 'tool-propose_blueprint', toolCallId: 'plan-0', state: 'output-available', input: {}, output }], - }); - -const renderPlan = (envelope: unknown, lang: 'zh' | 'en' = 'zh') => - render( - - - , - ); - -const nameLineOf = (objectName: string) => - within(screen.getByTestId(`proposed-plan-object-${objectName}`)).queryByTestId('proposed-plan-name-field'); - -describe('objectui#13004 — the plan card draws a generated record title`s line', () => { - it('zh: the loan draws the producer`s line, not 「名称:借阅标题」', () => { - renderPlan(planEnvelope('zh', { generatedTitle: true })); - const line = nameLineOf('loan'); - expect(line).toHaveTextContent(/^名称:自动生成「\{图书\} · \{读者\} · \{借出日期\}」,表单里不出现$/); - expect(line).toHaveAttribute('data-generated', 'true'); - expect(line).not.toHaveTextContent('借阅标题'); - }); - - it('en: the same line in English', () => { - renderPlan(planEnvelope('en', { generatedTitle: true }), 'en'); - expect(nameLineOf('loan')).toHaveTextContent(/^Name: generated as “\{Book\} · \{Reader\} · \{Loan date\}”, not on the form$/); - }); - - it('the chips are drawn from `fields[]` as given: the producer left the title field out', () => { - renderPlan(planEnvelope('zh', { generatedTitle: true })); - const chips = within(screen.getByTestId('proposed-plan-object-loan')).getAllByTestId('proposed-plan-field'); - expect(chips.map((c) => c.getAttribute('title'))).toEqual(['book', 'reader', 'loan_date', 'due_date', 'return_date', 'status']); - }); - - it('CONTROL: an object whose `nameField` has no `generated` draws its plain 「名称:LABEL」 line', () => { - renderPlan(planEnvelope('zh', { generatedTitle: true })); - expect(nameLineOf('book')).toHaveTextContent(/^名称:书名$/); - expect(nameLineOf('book')).not.toHaveAttribute('data-generated'); - expect(nameLineOf('reader')).toHaveTextContent(/^名称:姓名$/); - }); - - it('CONTROL: the same loan `nameField` without `generated` draws 「名称:借阅标题」', () => { - const plan = planEnvelope('zh', { generatedTitle: true }); - const objects = plan.planCard.objects.map((o) => { - if (!('nameField' in o) || !o.nameField || !('generated' in o.nameField)) return o; - const { generated: _g, ...nameField } = o.nameField; - return { ...o, nameField }; - }); - renderPlan({ ...plan, planCard: { ...plan.planCard, objects } }); - expect(nameLineOf('loan')).toHaveTextContent(/^名称:借阅标题$/); - expect(nameLineOf('loan')).not.toHaveAttribute('data-generated'); - }); -}); diff --git a/ui/packages/plugin-chatbot/src/__tests__/ChatbotEnhanced.planCardLifecycle-12994.test.tsx b/ui/packages/plugin-chatbot/src/__tests__/ChatbotEnhanced.planCardLifecycle-12994.test.tsx deleted file mode 100644 index cc261587396..00000000000 --- a/ui/packages/plugin-chatbot/src/__tests__/ChatbotEnhanced.planCardLifecycle-12994.test.tsx +++ /dev/null @@ -1,77 +0,0 @@ -/** - * ObjectUI - * Copyright (c) 2024-present ObjectStack Inc. - * - * objectui#12994 — the plan card draws a stage field's lifecycle on its chip - * (the AiBuild artboard's 「借出 · 已还 ✓完成 · 逾期 ⚠」), from the - * `planCard.objects[].fields[].lifecycle` key objectstack-ai/cloud declares - * (`build-cards.schema.json`, vendored as `fixtures/build-cards.schema.ts`). - * A chip without the key draws as before. - * - * Each message goes through the real mapper (`uiMessageToChatMessage`) from a - * raw tool part, so the lift is under test, not a hand-built invocation. - */ -import '@testing-library/jest-dom/vitest'; -import { describe, expect, it, vi } from 'vitest'; -import { render, screen, within } from '@testing-library/react'; -import { I18nProvider } from '@object-ui/i18n'; -import { ChatbotEnhanced } from '../ChatbotEnhanced'; -import { uiMessageToChatMessage } from '../mapMessages'; -import { planEnvelope } from './fixtures/buildCards.fixtures'; - -const turn = (output: unknown) => - uiMessageToChatMessage({ - id: 'plan', - role: 'assistant', - parts: [{ type: 'tool-propose_blueprint', toolCallId: 'plan-0', state: 'output-available', input: {}, output }], - }); - -const renderPlan = (envelope: unknown, lang: 'zh' | 'en' = 'zh') => - render( - - - , - ); - -const chipsOf = (objectName: string) => - within(screen.getByTestId(`proposed-plan-object-${objectName}`)).getAllByTestId('proposed-plan-field'); - -describe('objectui#12994 — the plan card draws a stage field`s lifecycle', () => { - it('zh: the stage field`s chip draws its lifecycle beside its label', () => { - renderPlan(planEnvelope('zh')); - const status = chipsOf('loan')[5]; - expect(status).toHaveAttribute('title', 'status'); - expect(within(status).getByTestId('proposed-plan-field-lifecycle')).toHaveTextContent(/^借出 · 已还 ✓完成 · 逾期 ⚠$/); - expect(status.textContent).toBe('状态借出 · 已还 ✓完成 · 逾期 ⚠'); - expect(screen.getAllByTestId('proposed-plan-field-lifecycle')).toHaveLength(1); - }); - - it('en: the same line in English', () => { - renderPlan(planEnvelope('en'), 'en'); - expect(within(chipsOf('loan')[5]).getByTestId('proposed-plan-field-lifecycle')).toHaveTextContent( - /^Borrowed · Returned ✓done · Overdue ⚠$/, - ); - }); - - it('CONTROL: a chip without the key draws as before', () => { - renderPlan(planEnvelope('zh')); - expect(chipsOf('loan').slice(0, 5).map((c) => c.textContent)).toEqual(['图书', '读者', '借出日期', '应还日期', '归还日期']); - for (const chip of chipsOf('book')) { - expect(within(chip).queryByTestId('proposed-plan-field-lifecycle')).not.toBeInTheDocument(); - } - }); - - it('CONTROL: the same stage field without `lifecycle` draws its plain label', () => { - const plan = planEnvelope('zh'); - const loan = plan.planCard.objects[2]; - const fields = loan.fields.map((f) => { - if (!('lifecycle' in f)) return f; - const { lifecycle: _l, ...rest } = f; - return rest; - }); - const objects = [...plan.planCard.objects.slice(0, 2), { ...loan, fields }]; - renderPlan({ ...plan, planCard: { ...plan.planCard, objects } }); - expect(chipsOf('loan')[5].textContent).toBe('状态'); - expect(screen.queryByTestId('proposed-plan-field-lifecycle')).not.toBeInTheDocument(); - }); -}); diff --git a/ui/packages/plugin-chatbot/src/__tests__/ChatbotEnhanced.planCardPosture-12724.test.tsx b/ui/packages/plugin-chatbot/src/__tests__/ChatbotEnhanced.planCardPosture-12724.test.tsx deleted file mode 100644 index 22e11ba981c..00000000000 --- a/ui/packages/plugin-chatbot/src/__tests__/ChatbotEnhanced.planCardPosture-12724.test.tsx +++ /dev/null @@ -1,83 +0,0 @@ -/** - * ObjectUI - * Copyright (c) 2024-present ObjectStack Inc. - * - * objectui#12724 — the plan card says how the build will land (the AiBuild - * artboard's last 假设 item, 「首次搭建直接上线;之后的修改先存草稿,由你发布」) from - * the `planCard.posture` key objectstack-ai/cloud declares (cloud#2924 ruling A; - * `build-cards.schema.json`, vendored as `fixtures/build-cards.schema.ts`). A plan - * card without the key says nothing about it. - * - * Each message goes through the real mapper (`uiMessageToChatMessage`) from a - * raw tool part, so the lift is under test, not a hand-built invocation. - */ -import '@testing-library/jest-dom/vitest'; -import { describe, expect, it, vi } from 'vitest'; -import { render, screen, within } from '@testing-library/react'; -import { I18nProvider } from '@object-ui/i18n'; -import { ChatbotEnhanced } from '../ChatbotEnhanced'; -import { uiMessageToChatMessage } from '../mapMessages'; -import { planEnvelope } from './fixtures/buildCards.fixtures'; - -const turn = (output: unknown) => - uiMessageToChatMessage({ - id: 'plan', - role: 'assistant', - parts: [{ type: 'tool-propose_blueprint', toolCallId: 'plan-0', state: 'output-available', input: {}, output }], - }); - -const renderPlan = (envelope: unknown, lang: 'zh' | 'en' = 'zh') => - render( - - - , - ); - -const assumptionItems = () => - within(screen.getByTestId('proposed-plan-assumptions')) - .getAllByRole('listitem') - .map((li) => li.textContent); - -describe('objectui#12724 — the plan card draws `planCard.posture.line`', () => { - it('zh: a first build`s line is the last assumption item', () => { - renderPlan(planEnvelope('zh', { posture: 'firstBuild' })); - expect(assumptionItems()).toEqual([ - '只建这三部分,不建仪表盘、预约、罚款;补充的字段(分类)可以去掉。', - '归还后状态置为已还;逾期由应还日期已过且未归还判定。', - '首次搭建直接上线;之后的修改先存草稿,由你发布', - ]); - expect(screen.getByTestId('proposed-plan-posture')).toHaveAttribute('data-posture', 'publish'); - }); - - it('en: the same line in English', () => { - renderPlan(planEnvelope('en', { posture: 'firstBuild' }), 'en'); - expect(screen.getByTestId('proposed-plan-posture')).toHaveTextContent( - /^This first build goes live at once; later changes are saved as drafts for you to publish$/, - ); - }); - - it('a build into a live app draws the producer`s draft line, records included', () => { - renderPlan(planEnvelope('zh', { posture: 'draft' })); - const line = screen.getByTestId('proposed-plan-posture'); - expect(line).toHaveTextContent(/^这个应用已上线,有 36 条记录在用;这次的改动先存为草稿,由你在「变更」里核对后发布$/); - expect(line).toHaveAttribute('data-posture', 'draft'); - }); - - it('a plan card with no assumptions still draws the section for the posture line alone', () => { - const plan = planEnvelope('zh', { posture: 'firstBuild' }); - renderPlan({ ...plan, planCard: { ...plan.planCard, assumptions: [] } }); - expect(assumptionItems()).toEqual(['首次搭建直接上线;之后的修改先存草稿,由你发布']); - }); - - it('CONTROL: a plan card without `posture` draws only the assumptions', () => { - renderPlan(planEnvelope('zh')); - expect(screen.queryByTestId('proposed-plan-posture')).not.toBeInTheDocument(); - expect(assumptionItems()).toHaveLength(2); - }); - - it('CONTROL: a posture whose mode the schema does not declare is not drawn', () => { - const plan = planEnvelope('zh', { posture: 'firstBuild' }); - renderPlan({ ...plan, planCard: { ...plan.planCard, posture: { ...plan.planCard.posture, mode: 'live' } } }); - expect(screen.queryByTestId('proposed-plan-posture')).not.toBeInTheDocument(); - }); -}); diff --git a/ui/packages/plugin-chatbot/src/__tests__/ChatbotEnhanced.planCardSuggestedLegend-33419.test.tsx b/ui/packages/plugin-chatbot/src/__tests__/ChatbotEnhanced.planCardSuggestedLegend-33419.test.tsx deleted file mode 100644 index 8e7415a9de4..00000000000 --- a/ui/packages/plugin-chatbot/src/__tests__/ChatbotEnhanced.planCardSuggestedLegend-33419.test.tsx +++ /dev/null @@ -1,112 +0,0 @@ -/** - * ObjectUI - * Copyright (c) 2024-present ObjectStack Inc. - * - * #33419 — the plan card says what its dashed 「· 补充」 (`· suggested`) mark - * means. A field the user's words did not name arrives with `suggested: true` - * on `planCard.objects[].fields[]` and is drawn as a dashed chip ending in the - * mark. When at least one field on the card is suggested, one legend line under - * the field rows explains it: the AI added the field, the user did not ask for - * it. The chip's tooltip keeps the field's machine name. - * - * Each message goes through the real mapper (`uiMessageToChatMessage`) from a - * raw tool part, so the lift is under test, not a hand-built invocation. - */ -import '@testing-library/jest-dom/vitest'; -import { describe, expect, it, vi } from 'vitest'; -import { render, screen, within } from '@testing-library/react'; -import { I18nProvider } from '@object-ui/i18n'; -import { ChatbotEnhanced } from '../ChatbotEnhanced'; -import { uiMessageToChatMessage } from '../mapMessages'; -import { planEnvelope } from './fixtures/buildCards.fixtures'; - -const turn = (output: unknown) => - uiMessageToChatMessage({ - id: 'plan', - role: 'assistant', - parts: [{ type: 'tool-propose_blueprint', toolCallId: 'plan-0', state: 'output-available', input: {}, output }], - }); - -const renderPlan = (envelope: unknown, lang: 'zh' | 'en' = 'zh') => - render( - - - , - ); - -type Plan = ReturnType; - -/** The plan with its card's objects replaced (the envelope is raw tool output, typed `unknown` by the mapper). */ -const withObjects = (plan: Plan, objects: readonly unknown[]) => ({ ...plan, planCard: { ...plan.planCard, objects } }); - -/** One object, one field the user named and one the AI suggested. */ -const oneNamedOneSuggested = (lang: 'zh' | 'en') => { - const plan = planEnvelope(lang); - const book = plan.planCard.objects[0]; - const title = book.fields.find((f) => f.name === 'title')!; - const category = book.fields.find((f) => f.name === 'category')!; - expect('suggested' in title).toBe(false); - expect(category).toMatchObject({ suggested: true }); - return withObjects(plan, [{ ...book, fields: [title, category] }]); -}; - -/** Every field on the card with `suggested` taken off. */ -const noneSuggested = (lang: 'zh' | 'en') => { - const plan = planEnvelope(lang); - return withObjects( - plan, - plan.planCard.objects.map((o) => ({ - ...o, - fields: o.fields.map((f) => { - if (!('suggested' in f)) return f; - const { suggested: _s, ...rest } = f; - return rest; - }), - })), - ); -}; - -const legends = () => screen.queryAllByTestId('proposed-plan-suggested-legend'); - -describe('#33419 — the plan card explains its suggested-field mark', () => { - it('zh: one named and one suggested field: one legend line under the field rows, the chip keeps its machine name', () => { - renderPlan(oneNamedOneSuggested('zh')); - expect(legends()).toHaveLength(1); - expect(legends()[0]).toHaveTextContent(/^标「补充」的字段是 AI 自行补充的,你没有要求。$/); - // Under the field rows: inside the objects block, after its last object row. - const objects = screen.getByTestId('proposed-plan-objects'); - expect(objects).toContainElement(legends()[0]); - expect(objects.lastElementChild).toBe(legends()[0]); - const chips = within(screen.getByTestId('proposed-plan-object-book')).getAllByTestId('proposed-plan-field'); - expect(chips.map((c) => c.getAttribute('title'))).toEqual(['title', 'category']); - expect(chips[1]).toHaveAttribute('data-suggested', 'true'); - expect(chips[1]).toHaveTextContent(/· 补充$/); - expect(chips[0]).not.toHaveAttribute('data-suggested'); - }); - - it('en: the same legend in English', () => { - renderPlan(oneNamedOneSuggested('en'), 'en'); - expect(legends()).toHaveLength(1); - expect(legends()[0]).toHaveTextContent(/^Fields marked “suggested” were added by the AI; you didn’t ask for them\.$/); - }); - - it('two suggested fields on two objects still draw one legend line', () => { - const plan = planEnvelope('zh'); - const objects = plan.planCard.objects.map((o) => - o.name === 'reader' - ? { ...o, fields: o.fields.map((f) => (f.name === 'phone' ? { ...f, suggested: true } : f)) } - : o, - ); - renderPlan(withObjects(plan, objects)); - expect(document.querySelectorAll('[data-suggested="true"]')).toHaveLength(2); - expect(legends()).toHaveLength(1); - }); - - it('CONTROL: no suggested field on the card draws no legend', () => { - renderPlan(noneSuggested('zh')); - expect(screen.getByTestId('proposed-plan-objects')).toBeInTheDocument(); - expect(document.querySelector('[data-suggested]')).toBeNull(); - expect(legends()).toHaveLength(0); - expect(screen.getByTestId('proposed-plan-objects')).not.toHaveTextContent('补充'); - }); -}); diff --git a/ui/packages/plugin-chatbot/src/__tests__/ChatbotEnhanced.queuedSend-32984.test.tsx b/ui/packages/plugin-chatbot/src/__tests__/ChatbotEnhanced.queuedSend-32984.test.tsx new file mode 100644 index 00000000000..3c9e3b39882 --- /dev/null +++ b/ui/packages/plugin-chatbot/src/__tests__/ChatbotEnhanced.queuedSend-32984.test.tsx @@ -0,0 +1,71 @@ +/** + * ObjectUI + * Copyright (c) 2024-present ObjectStack Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * objectstack#32984 item 2 — a message typed while a turn runs is queued in + * sight and sent when the turn ends, never dropped. Every interaction goes + * through the rendered component (Enter in the textarea, a click on the + * button), so the input pipeline runs as it does in the console. + */ +import '@testing-library/jest-dom/vitest'; +import { describe, it, expect, vi } from 'vitest'; +import { act, fireEvent, render, screen, waitFor } from '@testing-library/react'; +import { ChatbotEnhanced } from '../ChatbotEnhanced'; + +describe('objectstack#32984 item 2 — a message typed during a turn is never dropped', () => { + it('Enter during a turn queues it in sight, and it is sent when the turn ends', async () => { + const onSendMessage = vi.fn(); + const { rerender } = render( + , + ); + const textarea = screen.getByPlaceholderText('Ask…') as HTMLTextAreaElement; + // The composer is live during the turn: the user can type. + expect(textarea).not.toBeDisabled(); + fireEvent.change(textarea, { target: { value: '在哪里打开这个应用?' } }); + fireEvent.keyDown(textarea, { key: 'Enter' }); + + const queued = await screen.findByTestId('composer-queued-item'); + expect(queued).toHaveTextContent('在哪里打开这个应用?'); + expect(queued).toHaveTextContent('Sends when the current reply finishes'); + expect(onSendMessage).not.toHaveBeenCalled(); + + // The turn ends: the queued message goes out, once, and leaves the queue. + rerender(); + await waitFor(() => expect(onSendMessage).toHaveBeenCalledTimes(1)); + expect(onSendMessage).toHaveBeenCalledWith('在哪里打开这个应用?', undefined); + expect(screen.queryByTestId('composer-queued-item')).not.toBeInTheDocument(); + }); + + it('Cancel takes it out of the queue and puts the text back in the box', async () => { + const onSendMessage = vi.fn(); + const { rerender } = render( + , + ); + const textarea = screen.getByPlaceholderText('Ask…') as HTMLTextAreaElement; + fireEvent.change(textarea, { target: { value: 'never mind' } }); + fireEvent.keyDown(textarea, { key: 'Enter' }); + fireEvent.click(await screen.findByTestId('composer-queued-cancel')); + + expect(screen.queryByTestId('composer-queued-item')).not.toBeInTheDocument(); + expect(textarea.value).toBe('never mind'); + rerender(); + await act(async () => { + await new Promise((r) => setTimeout(r, 10)); + }); + expect(onSendMessage).not.toHaveBeenCalled(); + }); + + it('control: with no turn running, Enter sends at once', async () => { + const onSendMessage = vi.fn(); + render(); + const textarea = screen.getByPlaceholderText('Ask…') as HTMLTextAreaElement; + fireEvent.change(textarea, { target: { value: 'hello' } }); + fireEvent.keyDown(textarea, { key: 'Enter' }); + await waitFor(() => expect(onSendMessage).toHaveBeenCalledTimes(1)); + expect(onSendMessage.mock.calls[0][0]).toBe('hello'); + expect(screen.queryByTestId('composer-queued-item')).not.toBeInTheDocument(); + }); +}); diff --git a/ui/packages/plugin-chatbot/src/__tests__/ChatbotEnhanced.quotaBlockedConfirm.test.tsx b/ui/packages/plugin-chatbot/src/__tests__/ChatbotEnhanced.quotaBlockedConfirm.test.tsx deleted file mode 100644 index 03abb377a85..00000000000 --- a/ui/packages/plugin-chatbot/src/__tests__/ChatbotEnhanced.quotaBlockedConfirm.test.tsx +++ /dev/null @@ -1,295 +0,0 @@ -/** - * ObjectUI - * Copyright (c) 2024-present ObjectStack Inc. - * - * objectui#7253 — the paywall moment on the 确认修改 (confirm-changes) card. - * - * Measured on the local rig: a free user's SECOND build iteration clicked - * "Confirm changes" and the cloud token guardrail refused it with a 429 - * (`AI_DESIGN_QUOTA_EXHAUSTED`). Two things then went wrong on top of the - * refusal itself: - * - * 1. the card rolled straight back to "Confirm / Adjust" — indistinguishable - * from a card still waiting for the user, so nothing on it said the click - * had failed, and clicking again just bought the same 429; - * 2. the composer was refilled with the user's PREVIOUS message — one that had - * already been delivered and answered — because the card's canned approval - * text left the "restore my typing" slot pointing at stale input. - * - * The rollback itself is correct for a TRANSIENT failure (offline, per-minute - * rate limit), so it stays; the split is on the quota refusal only, and both - * halves are pinned here. - */ -import '@testing-library/jest-dom/vitest'; -import { describe, it, expect, vi } from 'vitest'; -import { render, screen, fireEvent, waitFor } from '@testing-library/react'; -import { ChatbotEnhanced, type ChatbotEnhancedMessage } from '../ChatbotEnhanced'; - -const QUOTA_ZH = '今天的 AI 设计额度已用完,明天会重置;升级后可继续设计。'; -const QUOTA_EN = "You've used today's free AI design quota. It resets tomorrow — upgrade to keep designing."; - -/** - * The wire shape the cloud guardrail actually sends (ADR-0112 declared envelope - * carrying the closed ledger code), tagged the way `sendAwareFetch` tags a POST - * that was refused BEFORE any tokens streamed. - */ -function quotaRefusal(): Error { - const e = new Error( - JSON.stringify({ - success: false, - error: { - code: 'AI_DESIGN_QUOTA_EXHAUSTED', - message: QUOTA_ZH, - category: 'rate_limit', - details: { messageEn: QUOTA_EN, upgrade: true, resetsTonight: true }, - }, - }), - ) as Error & { notSent?: boolean; status?: number }; - e.notSent = true; - e.status = 429; - return e; -} - -/** A transient not-sent failure — same `notSent` tag, no quota code. */ -function offlineFailure(): Error { - const e = new Error('Failed to fetch') as Error & { notSent?: boolean }; - e.notSent = true; - return e; -} - -function changesMessage(): ChatbotEnhancedMessage[] { - return [ - { - id: 'a1', - role: 'assistant', - content: '', - toolInvocations: [ - { - toolCallId: 't1', - toolName: 'update_metadata', - state: 'output-available', - proposedChanges: { - summary: 'Two edits to the task object', - changes: [{ verb: 'add_field', object: 'task', field: 'priority', type: 'select' }], - }, - }, - ], - } as unknown as ChatbotEnhancedMessage, - ]; -} - -/** Type + submit a message, the way the user's earlier turn reached the agent. */ -async function typeAndSend(text: string, onSendMessage: ReturnType) { - const textarea = screen.getByPlaceholderText('Ask…') as HTMLTextAreaElement; - fireEvent.change(textarea, { target: { value: text } }); - fireEvent.submit(textarea.closest('form')!); - await waitFor(() => expect(onSendMessage).toHaveBeenCalled()); - return textarea; -} - -describe('confirm card — AI quota refusal (objectui#7253)', () => { - it('parks the card in an explicit blocked state with the next step, instead of re-offering Confirm', async () => { - const onSendMessage = vi.fn(); - const onUpgrade = vi.fn(); - const { rerender } = render( - , - ); - - fireEvent.click(screen.getByTestId('proposed-changes-confirm')); - expect(screen.getByTestId('proposed-changes-applying')).toBeInTheDocument(); - - rerender( - , - ); - - // ① The card says the click failed… - await waitFor(() => - expect(screen.getByTestId('proposed-changes-quota-blocked')).toBeInTheDocument(), - ); - // ② …and does NOT hand back the button that just bought a 429, nor keep - // claiming the change is being applied. - expect(screen.queryByTestId('proposed-changes-confirm')).not.toBeInTheDocument(); - expect(screen.queryByTestId('proposed-changes-applying')).not.toBeInTheDocument(); - // ③ The next step is on the card: the server's own sentence (which names - // both exits — tomorrow's reset and the upgrade) plus the action. - expect(screen.getByTestId('proposed-changes-quota-reason')).toHaveTextContent( - new RegExp(`${QUOTA_ZH}|resets tomorrow`), - ); - fireEvent.click(screen.getByTestId('proposed-changes-quota-upgrade')); - expect(onUpgrade).toHaveBeenCalledTimes(1); - }); - - it('does not refill the composer with the message the user already sent', async () => { - const onSendMessage = vi.fn(); - const { rerender } = render( - , - ); - - // The user's real turn — delivered, answered, and the reason a proposal - // card exists at all. - const textarea = await typeAndSend('also track the due date', onSendMessage); - expect(textarea.value).toBe(''); - - // Now the card click, refused by the paywall. - fireEvent.click(screen.getByTestId('proposed-changes-confirm')); - rerender( - , - ); - - await waitFor(() => - expect(screen.getByTestId('proposed-changes-quota-blocked')).toBeInTheDocument(), - ); - // The bug: 'also track the due date' reappeared here, reading as "resend - // this" for a message that was never lost. - expect(textarea.value).toBe(''); - }); - - it('renders the blocked badge without a next step when the host wired no upgrade action', async () => { - const onSendMessage = vi.fn(); - const { rerender } = render( - , - ); - fireEvent.click(screen.getByTestId('proposed-changes-confirm')); - rerender( - , - ); - - await waitFor(() => - expect(screen.getByTestId('proposed-changes-quota-blocked')).toBeInTheDocument(), - ); - // A runtime with no upstream cloud passes no `onUpgrade` — the reason still - // shows; the button that would go nowhere does not. - expect(screen.getByTestId('proposed-changes-quota-reason')).toBeInTheDocument(); - expect(screen.queryByTestId('proposed-changes-quota-upgrade')).not.toBeInTheDocument(); - }); -}); - -describe('confirm card — transient not-sent failure keeps the retry path', () => { - it('rolls back to Confirm / Adjust, blocks nothing, and refills nothing', async () => { - const onSendMessage = vi.fn(); - const { rerender } = render( - , - ); - - const textarea = await typeAndSend('add a status field', onSendMessage); - fireEvent.click(screen.getByTestId('proposed-changes-confirm')); - rerender( - , - ); - - // Retrying IS the right next step for a dropped connection, so the buttons - // come back and nothing is blocked… - await waitFor(() => expect(screen.getByTestId('proposed-changes-confirm')).toBeInTheDocument()); - expect(screen.queryByTestId('proposed-changes-quota-blocked')).not.toBeInTheDocument(); - // …but the composer still isn't refilled: what failed was the card's canned - // approval, not the earlier message, which the agent already answered. - expect(textarea.value).toBe(''); - }); - - it('still restores text the user typed when THAT send is the one refused', async () => { - const onSendMessage = vi.fn(); - const { rerender } = render( - , - ); - const textarea = await typeAndSend('add a status field', onSendMessage); - - rerender( - , - ); - - // The unchanged half of the send-failure UX: this text never reached the - // model and the composer is the only place it exists. - await waitFor(() => expect(textarea.value).toBe('add a status field')); - }); -}); - -describe('confirm card — a refusal that names no upgrade offers none (cloud#4853)', () => { - /** The cloud guardrail's paid-plan five-hour 429: upgrade:false, topUp:false. */ - function paidFiveHourRefusal(): Error { - const e = new Error( - JSON.stringify({ - success: false, - error: { - code: 'AI_ALLOWANCE_EXHAUSTED', - message: '近五小时的 AI 用量已达上限,五小时内恢复后即可继续。', - category: 'rate_limit', - details: { - messageEn: "You've hit the five-hour AI usage limit. It resets within five hours — then you're good to go.", - upgrade: false, - topUp: false, - }, - }, - }), - ) as Error & { notSent?: boolean; status?: number }; - e.notSent = true; - e.status = 429; - return e; - } - - it('paid plan, resetKind fiveHour: the reason shows, the upgrade action does not', async () => { - const onSendMessage = vi.fn(); - const onUpgrade = vi.fn(); - const { rerender } = render( - , - ); - fireEvent.click(screen.getByTestId('proposed-changes-confirm')); - rerender( - , - ); - - await waitFor(() => - expect(screen.getByTestId('proposed-changes-quota-blocked')).toBeInTheDocument(), - ); - expect(screen.getByTestId('proposed-changes-quota-reason')).toHaveTextContent(/five-hour AI usage limit/); - expect(screen.queryByTestId('proposed-changes-quota-upgrade')).not.toBeInTheDocument(); - expect(screen.queryByRole('button', { name: 'Upgrade plan' })).toBeNull(); - }); -}); diff --git a/ui/packages/plugin-chatbot/src/__tests__/ChatbotEnhanced.replayOutcome.test.tsx b/ui/packages/plugin-chatbot/src/__tests__/ChatbotEnhanced.replayOutcome.test.tsx deleted file mode 100644 index 2a174c41cdb..00000000000 --- a/ui/packages/plugin-chatbot/src/__tests__/ChatbotEnhanced.replayOutcome.test.tsx +++ /dev/null @@ -1,234 +0,0 @@ -/** - * ObjectUI - * Copyright (c) 2024-present ObjectStack Inc. - * - * objectui#5695 — the 确认修改 card's terminal states after approval. - * - * Clicking 确认修改 makes the runtime re-dispatch the proposal under a - * `replay_` tool call. Before this card knew about replays, everything - * after the click was a black box: the card looked untouched, a REFUSED - * publish (`publishFailed:true, publishOutcome:'rolled_back'`) existed only in - * a tool-result JSON the user never sees, and the agent could narrate success - * over it (the 2026-08-22 staging E2E on cloud#1584). These pins drive each - * replay envelope shape through the real message stream and assert the card - * renders the verdict — the failure state above all, because a UI-rendered - * refusal is the layer a model cannot talk over. - */ -import '@testing-library/jest-dom/vitest'; -import { describe, it, expect, vi } from 'vitest'; -import { render, screen, fireEvent } from '@testing-library/react'; -import { ChatbotEnhanced, type ChatbotEnhancedMessage } from '../ChatbotEnhanced'; - -function proposalMessage(): ChatbotEnhancedMessage { - return { - id: 'a1', - role: 'assistant', - content: '', - toolInvocations: [ - { - toolCallId: 't1', - toolName: 'update_metadata', - state: 'output-available', - proposedChanges: { - changes: [{ verb: 'add_field', object: 'task', field: 'priority' }], - }, - }, - ], - }; -} - -function replayMessage( - outcome: NonNullable< - NonNullable[number]['replayOutcome'] - > | undefined, - extra: Partial[number]> = {}, -): ChatbotEnhancedMessage { - return { - id: 'a2', - role: 'assistant', - content: '', - toolInvocations: [ - { - toolCallId: 'replay_turn_0', - toolName: 'update_metadata', - state: 'output-available', - result: '{}', - ...(outcome ? { replayOutcome: outcome } : {}), - ...extra, - }, - ], - }; -} - -describe('ChatbotEnhanced — confirm card replay terminal states (objectui#5695)', () => { - it('published replay → the card shows the Applied badge, no live buttons', () => { - render( - , - ); - expect(screen.getByTestId('proposed-changes-applied')).toHaveTextContent('Applied'); - expect(screen.queryByTestId('proposed-changes-confirm')).not.toBeInTheDocument(); - expect(screen.queryByTestId('proposed-changes-confirmed')).not.toBeInTheDocument(); - }); - - it('drafted replay → Saved-as-draft badge, with an inline publish affordance when the host can publish', () => { - const onPublishDrafts = vi.fn(async () => true); - render( - , - ); - expect(screen.getByTestId('proposed-changes-drafted')).toHaveTextContent('Saved as draft'); - fireEvent.click(screen.getByTestId('proposed-changes-publish')); - expect(onPublishDrafts).toHaveBeenCalledWith('app.k9qk'); - }); - - it('drafted replay without a publish host (read-only share page) → badge only, no button', () => { - render( - , - ); - expect(screen.getByTestId('proposed-changes-drafted')).toBeInTheDocument(); - expect(screen.queryByTestId('proposed-changes-publish')).not.toBeInTheDocument(); - }); - - it('failed replay → Not-applied badge carrying the publishError headline; the point of the card', () => { - render( - , - ); - expect(screen.getByTestId('proposed-changes-failed')).toHaveTextContent('Not applied'); - expect(screen.getByTestId('proposed-changes-failed-reason')).toHaveTextContent( - 'dangling view reference', - ); - // The legacy positional 已确认 badge must NOT win over the failure verdict — - // that would be the old "narrated success" bug in UI form. - expect(screen.queryByTestId('proposed-changes-confirmed')).not.toBeInTheDocument(); - }); - - it('replay still in flight (no result yet) → Applying… spinner state', () => { - render( - , - ); - expect(screen.getByTestId('proposed-changes-applying')).toHaveTextContent('Applying…'); - }); - - it('clicking 确认修改 flips the card to Applying… optimistically', () => { - render(); - fireEvent.click(screen.getByTestId('proposed-changes-confirm')); - expect(screen.getByTestId('proposed-changes-applying')).toBeInTheDocument(); - expect(screen.queryByTestId('proposed-changes-confirm')).not.toBeInTheDocument(); - }); - - it('a second proposal after a replayed one keeps its own live buttons (positional, per-card)', () => { - const second: ChatbotEnhancedMessage = { - id: 'a3', - role: 'assistant', - content: '', - toolInvocations: [ - { - toolCallId: 't2', - toolName: 'update_metadata', - state: 'output-available', - proposedChanges: { changes: [{ verb: 'delete_field', object: 'task', field: 'old' }] }, - }, - ], - }; - render( - , - ); - expect(screen.getByTestId('proposed-changes-applied')).toBeInTheDocument(); - expect(screen.getByTestId('proposed-changes-confirm')).toBeInTheDocument(); - }); -}); - -describe('self-repair supersede (objectui#5695 follow-up)', () => { - const dispatchFailedReplay = (): ChatbotEnhancedMessage => - replayMessage({ - kind: 'failed', - dispatchError: true, - error: 'apply_edit op #1 (add_field): object "task" not found.', - }); - - it('a dispatch-errored replay with NO later verdict renders the failure state', () => { - render( - , - ); - expect(screen.getByTestId('proposed-changes-failed')).toBeInTheDocument(); - expect(screen.getByTestId('proposed-changes-failed-reason')).toHaveTextContent('not found'); - }); - - it("the model's later successful authoring result supersedes the dispatch error — never 未生效 over a landed change", () => { - const selfRepair: ChatbotEnhancedMessage = { - id: 'a3', - role: 'assistant', - content: '', - toolInvocations: [ - { - toolCallId: 'toolu_selfrepair', - toolName: 'add_field', - state: 'output-available', - result: JSON.stringify({ status: 'published' }), - }, - ], - }; - render( - , - ); - expect(screen.getByTestId('proposed-changes-applied')).toBeInTheDocument(); - expect(screen.queryByTestId('proposed-changes-failed')).not.toBeInTheDocument(); - }); - - it('a REAL publish failure (publishFailed envelope) is NOT superseded by later results', () => { - const later: ChatbotEnhancedMessage = { - id: 'a3', - role: 'assistant', - content: '', - toolInvocations: [ - { - toolCallId: 'toolu_other', - toolName: 'list_objects', - state: 'output-available', - result: JSON.stringify({ status: 'published' }), - }, - ], - }; - render( - , - ); - expect(screen.getByTestId('proposed-changes-failed')).toBeInTheDocument(); - }); -}); diff --git a/ui/packages/plugin-chatbot/src/__tests__/ChatbotEnhanced.replayedBuild-25887.test.tsx b/ui/packages/plugin-chatbot/src/__tests__/ChatbotEnhanced.replayedBuild-25887.test.tsx deleted file mode 100644 index 7edfd65532f..00000000000 --- a/ui/packages/plugin-chatbot/src/__tests__/ChatbotEnhanced.replayedBuild-25887.test.tsx +++ /dev/null @@ -1,118 +0,0 @@ -/** - * ObjectUI - * Copyright (c) 2024-present ObjectStack Inc. - * - * objectstack#25887 — a whole-app build that ran as a confirm-replay draws the - * same result card as a model-driven one. - * - * Approving the proposed plan sends the approval sentence, and the runtime - * replays the approved `apply_blueprint` under a synthetic `replay_` tool-call - * id. A replay streams no `data-build-progress` frames, and the mapper used to - * suppress the draft review of every `replay_` result (objectui#5695, there to - * keep a live Publish off a rolled-back confirm card). So the build's own - * envelope, `drafted[]`, `packageId`, `checklist` and `nextSteps` included, - * reached `tool.result` and was drawn nowhere: no result card, no 打开应用, no - * checklist, no next steps, live or after a reload. - * - * Each message goes through the real mapper from a raw tool part, in the - * shapes the result arrives in: the live stream's object, and the stored - * tool row's `{type:'json'}` and `{type:'text'}` wrappers. The envelope is the - * vendored `build-cards` fixture; the producer lives outside this repository. - */ -import '@testing-library/jest-dom/vitest'; -import { describe, expect, it, vi } from 'vitest'; -import { fireEvent, render, screen } from '@testing-library/react'; -import { I18nProvider } from '@object-ui/i18n'; -import { ChatbotEnhanced } from '../ChatbotEnhanced'; -import { uiMessageToChatMessage } from '../mapMessages'; -import { applyEnvelope } from './fixtures/buildCards.fixtures'; - -const NEXT = '接下来可以说:「给借阅记录加续借次数」 「做一个本月借出统计的仪表盘」 「只允许管理员删除图书」'; - -/** The assistant turn the replay appends: one `apply_blueprint` under a `replay_` id. */ -const replayTurn = (output: unknown) => - uiMessageToChatMessage({ - id: 'replayed', - role: 'assistant', - parts: [ - { - type: 'tool-apply_blueprint', - toolCallId: 'replay_BFpdNra4mJHv5BMH_0', - state: 'output-available', - input: {}, - output, - }, - ], - }); - -const renderZh = (output: unknown, props: { onOpenBuiltApp?: (app: string) => void } = {}) => - render( - - - , - ); - -describe('a replayed whole-app apply_blueprint draws the result card (objectstack#25887)', () => { - it.each([ - ['live: the streamed envelope object', applyEnvelope('zh')], - ['reload: the stored json wrapper', { type: 'json', value: applyEnvelope('zh') }], - ['reload: the stored text wrapper', { type: 'text', value: JSON.stringify(applyEnvelope('zh')) }], - ])('%s — the card, its checklist, its next steps and 打开应用', (_shape, output) => { - const onOpenBuiltApp = vi.fn(); - renderZh(output, { onOpenBuiltApp }); - expect(screen.getByTestId('build-progress-title')).toHaveTextContent('图书借阅管理'); - expect(screen.getByTestId('build-checklist-chip')).toHaveTextContent(/^核对通过 7\/7$/); - expect(screen.getByTestId('build-result-next-steps')).toHaveTextContent(NEXT); - fireEvent.click(screen.getByTestId('build-progress-open-app')); - expect(onOpenBuiltApp).toHaveBeenCalledWith('library_app'); - }); - - it('the auto-publish posture: a published replay envelope draws the card and its next steps', () => { - renderZh({ ...applyEnvelope('zh'), status: 'published' }); - expect(screen.getByTestId('build-progress-title')).toHaveTextContent('图书借阅管理'); - expect(screen.getByTestId('build-checklist-chip')).toHaveTextContent(/^核对通过 7\/7$/); - expect(screen.getByTestId('build-result-next-steps')).toHaveTextContent(NEXT); - }); - - it('a replay whose in-turn publish rolled back still draws no result card', () => { - renderZh({ ...applyEnvelope('zh'), publishFailed: true, publishOutcome: 'rolled_back', publishError: 'boom' }); - expect(screen.queryByTestId('build-progress-title')).not.toBeInTheDocument(); - expect(screen.queryByTestId('build-result-next-steps')).not.toBeInTheDocument(); - }); - - it('a replayed incremental edit (kind edit) is still not a build', () => { - renderZh({ ...applyEnvelope('zh'), kind: 'edit' }); - expect(screen.queryByTestId('build-progress-title')).not.toBeInTheDocument(); - }); -}); - -describe('the mapper keeps the replay verdict and lifts the build (objectstack#25887)', () => { - it('a drafted whole-app replay carries both its replayOutcome and its draftReview', () => { - const msg = replayTurn(applyEnvelope('zh')); - const tool = msg.toolInvocations?.[0]; - expect(tool?.replayOutcome).toMatchObject({ kind: 'drafted', packageId: 'app.hcpl' }); - expect(tool?.draftReview).toMatchObject({ packageId: 'app.hcpl', autoPublishable: true }); - expect(tool?.draftReview?.nextSteps).toEqual(applyEnvelope('zh').nextSteps); - expect(msg.buildProgress).toMatchObject({ phase: 'done' }); - }); - - it('a published whole-app replay lifts no draftReview (nothing left to publish) but a done tree', () => { - const msg = replayTurn({ ...applyEnvelope('zh'), status: 'published' }); - expect(msg.toolInvocations?.[0]?.replayOutcome).toMatchObject({ kind: 'published' }); - expect(msg.toolInvocations?.[0]?.draftReview).toBeUndefined(); - expect(msg.buildProgress).toMatchObject({ phase: 'done' }); - }); - - it('a failed replay keeps the objectui#5695 suppression: no draftReview, no tree', () => { - const msg = replayTurn({ ...applyEnvelope('zh'), publishFailed: true }); - expect(msg.toolInvocations?.[0]?.replayOutcome).toMatchObject({ kind: 'failed' }); - expect(msg.toolInvocations?.[0]?.draftReview).toBeUndefined(); - expect(msg.buildProgress).toBeUndefined(); - }); - - it('a replayed non-build draft (no app in drafted[]) keeps the suppression', () => { - const msg = replayTurn({ status: 'drafted', packageId: 'app.k9', drafted: [{ type: 'view', name: 'v' }] }); - expect(msg.toolInvocations?.[0]?.replayOutcome).toMatchObject({ kind: 'drafted' }); - expect(msg.toolInvocations?.[0]?.draftReview).toBeUndefined(); - }); -}); diff --git a/ui/packages/plugin-chatbot/src/__tests__/ChatbotEnhanced.sendError.test.tsx b/ui/packages/plugin-chatbot/src/__tests__/ChatbotEnhanced.sendError.test.tsx index cb410ab8849..8ff6a27010b 100644 --- a/ui/packages/plugin-chatbot/src/__tests__/ChatbotEnhanced.sendError.test.tsx +++ b/ui/packages/plugin-chatbot/src/__tests__/ChatbotEnhanced.sendError.test.tsx @@ -23,7 +23,6 @@ import { render, screen, fireEvent, waitFor } from '@testing-library/react'; import { I18nProvider } from '@object-ui/i18n'; import { en, zh } from '@object-ui/i18n/locales'; import { ChatbotEnhanced } from '../ChatbotEnhanced'; -import type { ChatbotEnhancedMessage } from '../ChatbotEnhanced'; const LABELS = { sendFailedRateLimited: 'RATE_LIMIT_MSG', @@ -185,141 +184,6 @@ describe('ChatbotEnhanced send-failure UX', () => { }); }); -/** - * objectui#2627 — the ROLLBACK half of the plan card's optimistic approve. - * Clicking "Build it" flips the card to a "Confirmed" badge (objectstack#32984; - * it read "Building…" before) before the server - * has said anything (#2632, pinned in ChatbotEnhanced.test.tsx). When that - * approval never left the client — a 429 or an offline send, tagged `notSent` — - * the optimistic badge is a lie AND a dead end: the badge replaces the buttons, - * so with no rollback the user cannot re-approve at all and the build silently - * never starts. The happy flip was pinned on its own; this is the other side. - */ -const planMessage: ChatbotEnhancedMessage[] = [ - { - id: 'a1', - role: 'assistant', - content: '', - toolInvocations: [ - { - toolCallId: 't1', - toolName: 'propose_blueprint', - state: 'output-available', - proposedPlan: { - summary: 'A tiny CRM', - objects: [{ name: 'contact', label: 'Contact', fieldCount: 4 }], - counts: { objects: 1, views: 1, dashboards: 0, seedData: 0 }, - questions: [], - assumptions: [], - }, - }, - ], - } as unknown as ChatbotEnhancedMessage, -]; - -describe('ChatbotEnhanced plan approval — optimistic flip rollback (#2627)', () => { - it('rolls the "Confirmed" badge back to the buttons when the approval never left the client', async () => { - const onSendMessage = vi.fn(); - const { rerender } = render( - , - ); - - fireEvent.click(screen.getByTestId('proposed-plan-approve')); - expect(screen.getByTestId('proposed-plan-confirmed')).toBeInTheDocument(); - expect(screen.queryByTestId('proposed-plan-approve')).not.toBeInTheDocument(); - - // The approval was rejected before reaching the model (rate limit). - rerender( - , - ); - - // The card must be actionable again — nothing is building. - await waitFor(() => - expect(screen.getByTestId('proposed-plan-approve')).toBeInTheDocument(), - ); - expect(screen.queryByTestId('proposed-plan-confirmed')).not.toBeInTheDocument(); - // …and the failure is surfaced, not swallowed. - expect(screen.getByTestId('chat-send-error')).toHaveTextContent('RATE_LIMIT_MSG'); - }); - - it('a STREAMED-response error leaves the badge alone — that approval did reach the server', async () => { - const onSendMessage = vi.fn(); - const { rerender } = render( - , - ); - fireEvent.click(screen.getByTestId('proposed-plan-approve')); - - // Not `notSent`: the turn started and the stream dropped. Re-offering - // "Build it" here invites a SECOND build of the same plan. - rerender( - , - ); - - expect(screen.getByTestId('proposed-plan-confirmed')).toBeInTheDocument(); - expect(screen.queryByTestId('proposed-plan-approve')).not.toBeInTheDocument(); - }); - - it('a LATER send supersedes the approve — its failure must not re-open the built card', async () => { - const onSendMessage = vi.fn(); - const { rerender } = render( - , - ); - fireEvent.click(screen.getByTestId('proposed-plan-approve')); - // The approval went through; the user then types something that does not. - await submit('also add invoices', onSendMessage); - - rerender( - , - ); - - // The composer text is restored, but the plan card stays "Confirmed" — - // rolling it back would offer a second build of a plan already building. - await waitFor(() => expect(screen.getByTestId('chat-send-error')).toBeInTheDocument()); - expect(screen.getByTestId('proposed-plan-confirmed')).toBeInTheDocument(); - expect(screen.queryByTestId('proposed-plan-approve')).not.toBeInTheDocument(); - }); -}); - describe('ChatbotEnhanced composer — a file over maxFileSize is named to the user (objectstack#34463)', () => { const LIMIT = 1024; const limitText = new Intl.NumberFormat('en', { style: 'unit', unit: 'kilobyte', maximumFractionDigits: 1 }).format(1); diff --git a/ui/packages/plugin-chatbot/src/__tests__/ChatbotEnhanced.test.tsx b/ui/packages/plugin-chatbot/src/__tests__/ChatbotEnhanced.test.tsx index 51df4a7783e..6bec9b53b78 100644 --- a/ui/packages/plugin-chatbot/src/__tests__/ChatbotEnhanced.test.tsx +++ b/ui/packages/plugin-chatbot/src/__tests__/ChatbotEnhanced.test.tsx @@ -8,14 +8,8 @@ */ import '@testing-library/jest-dom/vitest'; import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'; -import { render, screen, fireEvent, waitFor, act } from '@testing-library/react'; -import { - ChatbotEnhanced, - classifyAssumptions, - selectDesignHintIndex, - type ChatbotEnhancedMessage, -} from '../ChatbotEnhanced'; -import { uiMessagesToChatMessages } from '../mapMessages'; +import { render, screen, fireEvent, act } from '@testing-library/react'; +import { ChatbotEnhanced, type ChatbotEnhancedMessage } from '../ChatbotEnhanced'; describe('ChatbotEnhanced (AI Elements composition)', () => { beforeEach(() => { @@ -49,145 +43,6 @@ describe('ChatbotEnhanced (AI Elements composition)', () => { expect(screen.getByText(/How can I help/i)).toBeInTheDocument(); }); - it('renders the pre-build "Proposed plan" card instead of collapsing the propose tool into a chip', () => { - // Regression: a propose_blueprint tool carries `proposedPlan` but no - // draftReview — it must route to the DETAILED tool body (where the card - // lives), not the summary chip strip, or the confirm-gate card never shows. - const messages: ChatbotEnhancedMessage[] = [ - { - id: 'a1', - role: 'assistant', - content: '', - toolInvocations: [ - { - toolCallId: 't1', - toolName: 'propose_blueprint', - state: 'output-available', - proposedPlan: { - summary: 'A reading list', - objects: [{ name: 'book', label: 'Book', fieldCount: 2 }], - counts: { objects: 1, views: 0, dashboards: 0, seedData: 0 }, - questions: ['Track loans separately?'], - assumptions: ['One shelf for now'], - }, - }, - ], - }, - ]; - render(); - expect(screen.getByTestId('proposed-plan')).toBeInTheDocument(); - expect(screen.getByText('Proposed plan')).toBeInTheDocument(); - expect(screen.getByText(/A reading list/)).toBeInTheDocument(); - expect(screen.getByTestId('proposed-plan-questions')).toBeInTheDocument(); - expect(screen.getByText(/Track loans separately/)).toBeInTheDocument(); - }); - - it('renders the "Open in Builder →" handoff card and fires onOpenBuilder (ADR-0057 P4)', () => { - const onOpenBuilder = vi.fn(); - const messages: ChatbotEnhancedMessage[] = [ - { - id: 'a1', - role: 'assistant', - content: '', - toolInvocations: [ - { - toolCallId: 't1', - toolName: 'suggest_builder', - state: 'output-available', - builderHandoff: { prompt: 'Add a priority field to tasks', packageId: 'com.acme.crm' }, - }, - ], - }, - ]; - render(); - expect(screen.getByTestId('builder-handoff')).toBeInTheDocument(); - expect(screen.getByText(/Add a priority field to tasks/)).toBeInTheDocument(); - fireEvent.click(screen.getByTestId('builder-handoff-open')); - expect(onOpenBuilder).toHaveBeenCalledWith({ - prompt: 'Add a priority field to tasks', - packageId: 'com.acme.crm', - }); - }); - - it('keeps only the LATEST handoff card actionable; older ones are superseded/inert (#2458 UX#5)', () => { - const onOpenBuilder = vi.fn(); - const messages: ChatbotEnhancedMessage[] = [ - { - id: 'a1', - role: 'assistant', - content: '', - toolInvocations: [ - { toolCallId: 't1', toolName: 'suggest_builder', state: 'output-available', builderHandoff: { prompt: 'first request' } }, - ], - }, - { - id: 'a2', - role: 'assistant', - content: '', - toolInvocations: [ - { toolCallId: 't2', toolName: 'suggest_builder', state: 'output-available', builderHandoff: { prompt: 'second request' } }, - ], - }, - ]; - render(); - // The older card (t1) is inert; the latest (t2) is actionable. - const superseded = screen.getByTestId('builder-handoff-superseded'); - expect(superseded).toBeDisabled(); - const actionable = screen.getByTestId('builder-handoff-open'); - fireEvent.click(actionable); - expect(onOpenBuilder).toHaveBeenCalledWith({ prompt: 'second request' }); - // Clicking the superseded one does nothing (disabled). - fireEvent.click(superseded); - expect(onOpenBuilder).toHaveBeenCalledTimes(1); - }); - - it('disables "Open in Builder" when no host wired onOpenBuilder', () => { - const messages: ChatbotEnhancedMessage[] = [ - { - id: 'a1', - role: 'assistant', - content: '', - toolInvocations: [ - { toolCallId: 't1', toolName: 'suggest_builder', state: 'output-available', builderHandoff: { prompt: 'x' } }, - ], - }, - ]; - render(); - expect(screen.getByTestId('builder-handoff-open')).toBeDisabled(); - }); - - // #2458 item 3 — the ask-decline handoff card is the actionable payload; it - // must surface the moment `suggest_builder` reaches `output-available`, while - // the turn is STILL streaming and the trailing one-line prose hasn't arrived - // (content still empty). We must not withhold it until the text part finishes. - it('renders the handoff card at output-available while still streaming, before prose arrives (#2458)', () => { - const onOpenBuilder = vi.fn(); - const messages: ChatbotEnhancedMessage[] = [ - { id: 'u1', role: 'user', content: '帮我搭一个客户管理应用' }, - { - id: 'a1', - role: 'assistant', - content: '', // no prose yet — the sentence streams in AFTER the card - streaming: true, - toolInvocations: [ - { - toolCallId: 't1', - toolName: 'suggest_builder', - state: 'output-available', - builderHandoff: { prompt: '客户管理应用', packageId: 'com.acme.crm' }, - }, - ], - }, - ]; - render(); - // The actionable card is present and live despite the unfinished stream. - expect(screen.getByTestId('builder-handoff')).toBeInTheDocument(); - fireEvent.click(screen.getByTestId('builder-handoff-open')); - expect(onOpenBuilder).toHaveBeenCalledWith({ - prompt: '客户管理应用', - packageId: 'com.acme.crm', - }); - }); // #2458 item 3 — while the ask agent is still deciding (no prose, no rendered // tool row yet), a mid-stream turn whose only text is the persisted @@ -233,164 +88,6 @@ describe('ChatbotEnhanced (AI Elements composition)', () => { expect(screen.queryByText('(called suggest_builder)')).not.toBeInTheDocument(); }); - const planMessage = (questions: string[]): ChatbotEnhancedMessage[] => [ - { - id: 'a1', - role: 'assistant', - content: '', - toolInvocations: [ - { - toolCallId: 't1', - toolName: 'propose_blueprint', - state: 'output-available', - proposedPlan: { - summary: 'A reading list', - objects: [{ name: 'book', label: 'Book', fieldCount: 2 }], - counts: { objects: 1, views: 0, dashboards: 0, seedData: 0 }, - questions, - assumptions: ['One shelf for now'], - }, - }, - ], - }, - ]; - - it('"Build it" on a plan with open questions approves with the accept-defaults message', () => { - const onSendMessage = vi.fn(); - render( - , - ); - fireEvent.click(screen.getByTestId('proposed-plan-approve')); - // Open questions → the click must authorize defaults, not silently drop them. - expect(onSendMessage).toHaveBeenCalledWith('APPROVE_DEFAULTS'); - }); - - it('"Build it" on a plan with no open questions approves with the plain message', () => { - const onSendMessage = vi.fn(); - render( - , - ); - expect(screen.queryByTestId('proposed-plan-questions')).not.toBeInTheDocument(); - fireEvent.click(screen.getByTestId('proposed-plan-approve')); - expect(onSendMessage).toHaveBeenCalledWith('APPROVE_PLAIN'); - }); - - // objectstack#32984 — the click confirms; it does not build. The card reads - // 已确认 until an apply_blueprint actually starts. - it('flips the clicked card to a "Confirmed" badge immediately (#2627)', () => { - const onSendMessage = vi.fn(); - render( - , - ); - fireEvent.click(screen.getByTestId('proposed-plan-approve')); - // The approval's chat-level effects land at the bottom of the thread — - // the card ITSELF must show the state change or the click reads as lost. - expect(screen.queryByTestId('proposed-plan-approve')).not.toBeInTheDocument(); - expect(screen.getByTestId('proposed-plan-confirmed')).toHaveTextContent('Confirmed'); - expect(screen.queryByTestId('proposed-plan-building')).not.toBeInTheDocument(); - expect(onSendMessage).toHaveBeenCalledTimes(1); - }); - - it('falls back to the static hint (no action buttons) when message sending is not wired', () => { - render(); - expect(screen.queryByTestId('proposed-plan-actions')).not.toBeInTheDocument(); - expect(screen.getByText('HINT_TEXT')).toBeInTheDocument(); - }); - - // issue #432: once the plan's build has run, re-clicking "Build it" rebuilt - // the whole app. The card must collapse to an inert "Built" badge. - const planThenBuild: ChatbotEnhancedMessage[] = [ - ...planMessage([]), - { - id: 'a2', - role: 'assistant', - content: '', - toolInvocations: [ - { - toolCallId: 't2', - toolName: 'apply_blueprint', - state: 'output-available', - // objectstack#32984 — a build is what the envelope says it is. - result: { status: 'drafted', drafted: [{ type: 'app', name: 'crm' }] }, - }, - ], - }, - ]; - - it('collapses the plan actions to an inert "Built" badge once apply_blueprint has run', () => { - const onSendMessage = vi.fn(); - render( - , - ); - // No live "Build it" button to re-trigger the build. - expect(screen.queryByTestId('proposed-plan-approve')).not.toBeInTheDocument(); - expect(screen.getByTestId('proposed-plan-built')).toBeInTheDocument(); - expect(screen.getByText('BUILT_BADGE')).toBeInTheDocument(); - }); - - it('keeps the "Build it" button active for a plan that has NOT been built yet', () => { - render(); - expect(screen.getByTestId('proposed-plan-approve')).toBeInTheDocument(); - expect(screen.queryByTestId('proposed-plan-built')).not.toBeInTheDocument(); - }); - - const Q_INTERVIEW = 'Track interviews as a separate object or a stage field?'; - const planWithChoices: ChatbotEnhancedMessage[] = [ - { - id: 'a1', - role: 'assistant', - content: '', - toolInvocations: [ - { - toolCallId: 't1', - toolName: 'propose_blueprint', - state: 'output-available', - proposedPlan: { - summary: 'A recruiting app', - objects: [{ name: 'candidate', label: 'Candidate', fieldCount: 3 }], - counts: { objects: 1, views: 0, dashboards: 0, seedData: 0 }, - questions: [Q_INTERVIEW], - questionChoices: [{ text: Q_INTERVIEW, options: ['Separate object', 'Stage field'] }], - assumptions: [], - }, - }, - ], - }, - ]; - - it('renders one-click answer chips for a question that has choices, and sends the answer on click', () => { - const onSendMessage = vi.fn(); - render( - `ANSWER:${q}=${o}`} - />, - ); - expect(screen.getByTestId('proposed-plan-choice')).toBeInTheDocument(); - fireEvent.click(screen.getByText('Stage field')); - expect(onSendMessage).toHaveBeenCalledWith(`ANSWER:${Q_INTERVIEW}=Stage field`); - }); - - it('renders plain questions with NO chips when there are no matching choices', () => { - render(); - expect(screen.getByText(/Some open-ended question/)).toBeInTheDocument(); - expect(screen.queryByTestId('proposed-plan-choice')).not.toBeInTheDocument(); - }); it('shows an error banner with a retry affordance', () => { const onReload = vi.fn(); @@ -586,111 +283,6 @@ describe('ChatbotEnhanced (AI Elements composition)', () => { expect(screen.getByText(/Picked the query_data tool/i)).toBeInTheDocument(); }); - it('hides raw tool JSON for drafting tools in summary mode but keeps the Review affordance', () => { - const draftTool: ChatbotEnhancedMessage = { - id: 'a1', - role: 'assistant', - content: 'Built your sales CRM.', - toolInvocations: [ - { - toolCallId: 'tc1', - toolName: 'apply_blueprint', - state: 'output-available', - args: { blueprint: { summary: 'sales', objects: [{ name: 'opportunity_secret_field' }] } }, - result: { status: 'drafted', drafted: [{ type: 'object', name: 'opportunity' }] }, - draftReview: { items: [{ type: 'object', name: 'opportunity' }], summary: 'drafted 1 artifact(s)' }, - }, - ], - }; - const onReviewDraft = vi.fn(); - const { rerender } = render( - , - ); - // Consumer surface (summary): the friendly card + Review affordance render, - // but the raw blueprint PARAMETERS / drafted RESULT JSON stay hidden. - expect(screen.getByText(/Apply blueprint/i)).toBeInTheDocument(); - expect(screen.queryByText('Parameters')).not.toBeInTheDocument(); - expect(screen.queryByText('Result')).not.toBeInTheDocument(); - expect(screen.queryByText(/opportunity_secret_field/)).not.toBeInTheDocument(); - expect(screen.getByText(/Review/i)).toBeInTheDocument(); - - // Developer surface (debug): the raw PARAMETERS JSON is revealed. - rerender(); - expect(screen.getByText('Parameters')).toBeInTheDocument(); - }); - - it('#2493 — the draft-review summary can truncate (min-w-0) and its action row wraps, so it does not overflow on mobile', () => { - const longSummary = - 'built 5 artifact(s) — live in your new app, grouped under app.pi8e — objects, views and a task board, all wired and ready to publish'; - const draftTool: ChatbotEnhancedMessage = { - id: 'ov1', - role: 'assistant', - content: 'Built your app.', - toolInvocations: [ - { - toolCallId: 'tc-ov', - toolName: 'apply_blueprint', - state: 'output-available', - result: { status: 'drafted', drafted: [{ type: 'app', name: 'todo_app' }] }, - draftReview: { - items: [{ type: 'app', name: 'todo_app' }], - packageId: 'app.pi8e', - summary: longSummary, - }, - }, - ], - }; - render(); - const summary = screen.getByText(longSummary); - // The summary is a flex child that must be shrinkable + clipped, or its - // nowrap text expands the chat column past a phone viewport (the bug). - expect(summary).toHaveClass('truncate'); - expect(summary).toHaveClass('min-w-0'); - // And the action row wraps so its buttons never force horizontal scroll. - const row = summary.closest('div'); - expect(row?.className).toContain('flex-wrap'); - }); - - it('expands the verification chip into the actual lint findings (ADR-0038 L1)', () => { - const issueTool: ChatbotEnhancedMessage = { - id: 'a2', - role: 'assistant', - content: 'Drafted your app.', - toolInvocations: [ - { - toolCallId: 'tc2', - toolName: 'create_metadata', - state: 'output-available', - args: {}, - result: { status: 'drafted', type: 'object', name: 'book' }, - draftReview: { - items: [{ type: 'object', name: 'book' }], - summary: 'Drafted new object "book"', - verification: { errors: 1, warnings: 0 }, - issues: [ - { - severity: 'error', - code: 'select_without_options', - message: 'genre is a required select with no options', - fix: 'Add an options array.', - }, - ], - }, - }, - ], - }; - render(); - // The chip still shows the COUNT, and the new detail block expands it into - // the actual finding + fix hint \u2014 no more dead-end "1 issue" badge. - // objectstack#32984 — the count through the pack ("1 to fix"), and the - // findings (written for the agent) kept behind the Technical details - // disclosure under a customer sentence. - expect(screen.getByTestId('draft-verification-chip')).toHaveTextContent('1 to fix'); - const detail = screen.getByTestId('draft-issues-details'); - expect(detail).toHaveTextContent('genre is a required select with no options'); - expect(detail).toHaveTextContent('Add an options array.'); - }); - it('renders a model picker and forwards changes', async () => { const onModelChange = vi.fn(); render( @@ -723,638 +315,6 @@ describe('ChatbotEnhanced (AI Elements composition)', () => { ); expect(screen.queryByLabelText(/Model/i)).toBeNull(); }); - - // Improvement 1: a propose_blueprint can FINISH without its result parsing - // into a structured `proposedPlan` (a thin/odd envelope, or a prose proposal). - // Before, that collapsed into a "Completed" chip and the user was left with - // prose and no button — guess-the-"确认". Now a fallback confirm card with an - // explicit "Build it" / "Adjust" always renders. - describe('fallback confirm gate for an unstructured propose_blueprint', () => { - // A completed propose_blueprint with NO proposedPlan (detector returned - // undefined) — the regression case. - const unstructured: ChatbotEnhancedMessage[] = [ - { - id: 'a1', - role: 'assistant', - content: "Here's a plan for a reading list. Reply to confirm and I'll build it.", - toolInvocations: [ - { toolCallId: 't1', toolName: 'propose_blueprint', state: 'output-available' }, - ], - }, - ]; - - it('renders the fallback "Build it" card (not just prose) when the plan did not parse', () => { - render( - , - ); - expect(screen.getByTestId('proposed-plan-fallback')).toBeInTheDocument(); - // An explicit, one-click confirm gate — no guessing the "确认" phrase. - expect(screen.getByTestId('proposed-plan-approve')).toBeInTheDocument(); - expect(screen.getByTestId('proposed-plan-adjust')).toBeInTheDocument(); - expect(screen.getByText('READY_TEXT')).toBeInTheDocument(); - }); - - it('"Build it" on the fallback card sends the plain approve message (no open questions to default)', () => { - const onSendMessage = vi.fn(); - render( - , - ); - fireEvent.click(screen.getByTestId('proposed-plan-approve')); - expect(onSendMessage).toHaveBeenCalledWith('APPROVE_PLAIN'); - }); - - it('falls back to the static hint (no buttons) when message sending is not wired', () => { - render(); - expect(screen.getByTestId('proposed-plan-fallback')).toBeInTheDocument(); - expect(screen.queryByTestId('proposed-plan-actions')).not.toBeInTheDocument(); - expect(screen.getByText('HINT_TEXT')).toBeInTheDocument(); - }); - - it('collapses the fallback card to an inert "Built" badge once apply_blueprint has run', () => { - const built: ChatbotEnhancedMessage[] = [ - ...unstructured, - { - id: 'a2', - role: 'assistant', - content: '', - toolInvocations: [ - { - toolCallId: 't2', - toolName: 'apply_blueprint', - state: 'output-available', - // objectstack#32984 — a build is what the envelope says it is. - result: { status: 'drafted', drafted: [{ type: 'app', name: 'crm' }] }, - }, - ], - }, - ]; - render(); - expect(screen.queryByTestId('proposed-plan-approve')).not.toBeInTheDocument(); - expect(screen.getByTestId('proposed-plan-built')).toBeInTheDocument(); - expect(screen.getByText('BUILT_BADGE')).toBeInTheDocument(); - }); - - it('does NOT render the fallback card while the propose_blueprint is still running', () => { - // A running proposal keeps its live timer in the summary strip; the - // fallback confirm gate is only for the FINISHED-but-unstructured case. - render( - , - ); - expect(screen.queryByTestId('proposed-plan-fallback')).not.toBeInTheDocument(); - expect(screen.queryByTestId('proposed-plan-approve')).not.toBeInTheDocument(); - }); - - it('prefers the RICH plan card over the fallback when the plan DID parse', () => { - const structured: ChatbotEnhancedMessage[] = [ - { - id: 'a1', - role: 'assistant', - content: '', - toolInvocations: [ - { - toolCallId: 't1', - toolName: 'propose_blueprint', - state: 'output-available', - proposedPlan: { - summary: 'A reading list', - objects: [{ name: 'book', label: 'Book', fieldCount: 2 }], - counts: { objects: 1, views: 0, dashboards: 0, seedData: 0 }, - questions: [], - assumptions: [], - }, - }, - ], - }, - ]; - render(); - // Rich card present, fallback absent — no double card. - expect(screen.getByTestId('proposed-plan')).toBeInTheDocument(); - expect(screen.queryByTestId('proposed-plan-fallback')).not.toBeInTheDocument(); - }); - }); -}); - -describe('ChatbotEnhanced — auto-publish drafts (self-use magic moment)', () => { - const userMsg: ChatbotEnhancedMessage = { id: 'u1', role: 'user', content: 'build a todo app' }; - // A whole-app build: the backend marks it `autoPublishable` (apply_blueprint). - const draftMsg = (packageId: string): ChatbotEnhancedMessage => ({ - id: 'a1', - role: 'assistant', - content: 'Built your app.', - toolInvocations: [ - { - toolCallId: 'tc1', - toolName: 'apply_blueprint', - state: 'output-available', - draftReview: { items: [{ type: 'object', name: 'task' }], packageId, autoPublishable: true }, - }, - ], - }); - // An incremental edit: NOT auto-publishable — stays a draft for review. - const editMsg = (packageId: string): ChatbotEnhancedMessage => ({ - id: 'e1', - role: 'assistant', - content: 'Drafted a field.', - toolInvocations: [ - { - toolCallId: 'tc-edit', - toolName: 'add_field', - state: 'output-available', - draftReview: { items: [{ type: 'object', name: 'task' }], packageId }, - }, - ], - }); - - it('auto-fires onPublishDrafts for a NEW draft once the turn finishes', () => { - const onPublishDrafts = vi.fn(); - const { rerender } = render( - , - ); - // Draft streams in but the turn is still running → hold off. - rerender( - , - ); - expect(onPublishDrafts).not.toHaveBeenCalled(); - // Turn finished → publish exactly once, with the drafted package id. - rerender( - , - ); - expect(onPublishDrafts).toHaveBeenCalledTimes(1); - expect(onPublishDrafts).toHaveBeenCalledWith('app.todo'); - }); - - it('does NOT auto-publish drafts already present when the chat mounts', () => { - const onPublishDrafts = vi.fn(); - const { rerender } = render( - , - ); - rerender( - , - ); - expect(onPublishDrafts).not.toHaveBeenCalled(); - }); - - it('does NOT auto-publish an incremental edit (not autoPublishable) — it stays a draft', () => { - const onPublishDrafts = vi.fn(); - const { rerender } = render( - , - ); - // Even with auto-publish ON and the turn finished, an edit must not fire — - // destructive/incremental changes go live only on explicit review. - rerender( - , - ); - expect(onPublishDrafts).not.toHaveBeenCalled(); - }); - - it('does not auto-publish when autoPublishDrafts is off', () => { - const onPublishDrafts = vi.fn(); - const { rerender } = render( - , - ); - rerender( - , - ); - expect(onPublishDrafts).not.toHaveBeenCalled(); - }); - - it('publishes the same draft tool call at most once across re-renders', () => { - const onPublishDrafts = vi.fn(); - const withDraft = [userMsg, draftMsg('app.todo')]; - const { rerender } = render( - , - ); - rerender(); - rerender(); - expect(onPublishDrafts).toHaveBeenCalledTimes(1); - }); - - it('shows "Published" only on the published draft, not later edits into the same package', async () => { - // Regression: the published badge is keyed per draft (toolCallId), not per - // package. After a build auto-publishes com.workspace, a later edit into the - // same package is a fresh pending draft and must still offer "Publish". - const onPublishDrafts = vi.fn().mockResolvedValue(true); - const { rerender } = render( - , - ); - rerender( - , - ); - await waitFor(() => expect(onPublishDrafts).toHaveBeenCalledTimes(1)); - await screen.findByText('Published'); // the build card flips to published - // A later incremental edit into the SAME package — still pending. - rerender( - , - ); - expect(screen.getAllByText('Published')).toHaveLength(1); // only the build card - expect(screen.getByText('Publish')).toBeInTheDocument(); // the edit card still needs publishing - }); - - it('auto-publishes a SECOND build into the SAME package (distinct tool call)', () => { - // Regression: dedup must be per draft tool call, not per packageId — both - // builds target com.workspace; keying by packageId would skip the second. - const onPublishDrafts = vi.fn(); - const build = (callId: string, name: string): ChatbotEnhancedMessage => ({ - id: 'a-' + callId, - role: 'assistant', - content: 'built', - toolInvocations: [ - { - toolCallId: callId, - toolName: 'apply_blueprint', - state: 'output-available', - draftReview: { items: [{ type: 'object', name }], packageId: 'com.workspace', autoPublishable: true }, - }, - ], - }); - const { rerender } = render( - , - ); - rerender( - , - ); - expect(onPublishDrafts).toHaveBeenCalledTimes(1); - // Second build into the same workspace package, new tool call → fires again. - rerender( - , - ); - expect(onPublishDrafts).toHaveBeenCalledTimes(2); - expect(onPublishDrafts).toHaveBeenLastCalledWith('com.workspace'); - }); -}); - -describe('ChatbotEnhanced — streaming build preview (live build tree)', () => { - const buildMsg = (phase: 'structure' | 'data' | 'done'): ChatbotEnhancedMessage => ({ - id: 'a1', - role: 'assistant', - content: '', - streaming: phase !== 'done', - buildProgress: { - phase, - appLabel: 'CRM', - items: [ - { type: 'object', name: 'customer' }, - { type: 'view', name: 'customer.list' }, - { type: 'seed', name: 'customer_sample' }, - ], - done: 3, - total: 6, - }, - }); - - it('renders a live build tree (not thinking dots) while a build streams', () => { - render(); - expect(screen.getByTestId('build-progress')).toBeInTheDocument(); - expect(screen.getByText(/Building CRM/i)).toBeInTheDocument(); - // Artifacts are grouped by type with friendly labels. - expect(screen.getByText('Objects')).toBeInTheDocument(); - expect(screen.getByText('Views')).toBeInTheDocument(); - expect(screen.getByText('Sample data')).toBeInTheDocument(); - // The artifact names render (seeds without the _sample suffix). - expect(screen.getAllByText(/customer/).length).toBeGreaterThan(0); - }); - - it('collapses to a "Built" summary when the build is done', () => { - render(); - expect(screen.getByText(/Built CRM/i)).toBeInTheDocument(); - }); - - it('offers "Open app" on a finished build that created an app, wired to onOpenBuiltApp', () => { - const onOpenBuiltApp = vi.fn(); - const doneWithApp: ChatbotEnhancedMessage = { - ...buildMsg('done'), - buildProgress: { - ...buildMsg('done').buildProgress!, - items: [...buildMsg('done').buildProgress!.items, { type: 'app', name: 'crm' }], - }, - }; - render(); - const btn = screen.getByTestId('build-progress-open-app'); - fireEvent.click(btn); - expect(onOpenBuiltApp).toHaveBeenCalledWith('crm'); - }); - - // objectui#12724 (the AiBuild artboard) — the finished card's PRIMARY action - // opens the built app; Studio is the secondary door. Replaces the earlier - // pin (objectui#2623) that put Studio in the primary slot. - it('renders "Open app" as the PRIMARY action and Studio as the secondary door (objectui#12724)', () => { - const onDesignBuiltApp = vi.fn(); - const onOpenBuiltApp = vi.fn(); - const doneWithApp: ChatbotEnhancedMessage = { - ...buildMsg('done'), - buildProgress: { - ...buildMsg('done').buildProgress!, - items: [...buildMsg('done').buildProgress!.items, { type: 'app', name: 'crm' }], - }, - }; - render( - , - ); - const open = screen.getByTestId('build-progress-open-app'); - const design = screen.getByTestId('build-progress-design-app'); - expect(open.className).toContain('bg-primary'); - expect(design.className).toContain('border'); - expect(design.className).not.toContain('bg-primary'); - fireEvent.click(design); - expect(onDesignBuiltApp).toHaveBeenCalledWith('crm', undefined); - }); - - it("passes the build's OWN package id (from its draft envelope) to the Studio CTA — history-safe", () => { - const onDesignBuiltApp = vi.fn(); - const doneWithApp: ChatbotEnhancedMessage = { - ...buildMsg('done'), - toolInvocations: [ - { - toolCallId: 't1', - toolName: 'apply_blueprint', - draftReview: { - items: [{ type: 'app', name: 'crm' }], - packageId: 'app.crm', - }, - }, - ], - buildProgress: { - ...buildMsg('done').buildProgress!, - items: [...buildMsg('done').buildProgress!.items, { type: 'app', name: 'crm' }], - }, - }; - render(); - fireEvent.click(screen.getByTestId('build-progress-design-app')); - expect(onDesignBuiltApp).toHaveBeenCalledWith('crm', 'app.crm'); - }); - - it('deep-links done-build artifacts via getArtifactAction; null renders plain text', () => { - const open = vi.fn(); - const getArtifactAction = vi.fn( - (a: { type: string; name: string }) => (a.type === 'object' ? () => open(a) : null), - ); - render(); - const link = screen.getByTestId('build-artifact-link-object-customer'); - fireEvent.click(link); - expect(open).toHaveBeenCalledWith({ type: 'object', name: 'customer' }); - // Seeds have no direct-edit home (host returned null) → plain text, no link. - expect(screen.queryByTestId('build-artifact-link-seed-customer_sample')).not.toBeInTheDocument(); - }); - - it('keeps artifact rows plain while the build is still streaming', () => { - const getArtifactAction = vi.fn(() => () => {}); - render( - , - ); - expect(screen.queryByTestId('build-artifact-link-object-customer')).not.toBeInTheDocument(); - }); - - it('shows no Open-app action while streaming or without an app artifact', () => { - const onOpenBuiltApp = vi.fn(); - const { rerender } = render( - , - ); - expect(screen.queryByTestId('build-progress-open-app')).not.toBeInTheDocument(); - // Done but no `app` item → still no button (nothing to open). - rerender(); - expect(screen.queryByTestId('build-progress-open-app')).not.toBeInTheDocument(); - }); - - // ADR-0048: AI-built apps route on their PACKAGE id (globally unique), not the - // LLM's display name (`library`, which can collide across apps). - it('the draft Preview button passes the app package id as the route segment', () => { - const onPreviewDraftApp = vi.fn(); - const msg: ChatbotEnhancedMessage = { - id: 'a1', - role: 'assistant', - content: '', - toolInvocations: [ - { - toolCallId: 't1', - toolName: 'apply_blueprint', - state: 'output-available', - draftReview: { items: [{ type: 'app', name: 'library' }], packageId: 'app.fh79', materialized: true }, - }, - ], - }; - render(); - fireEvent.click(screen.getByTestId('draft-preview-app')); - expect(onPreviewDraftApp).toHaveBeenCalledWith('library', expect.objectContaining({ appSegment: 'app.fh79' })); - }); - - it('onDraftArtifacts carries the app package id for the auto-opened preview pane', () => { - const onDraftArtifacts = vi.fn(); - const msg: ChatbotEnhancedMessage = { - id: 'a1', - role: 'assistant', - content: '', - toolInvocations: [ - { - toolCallId: 't1', - toolName: 'apply_blueprint', - state: 'output-available', - draftReview: { - items: [{ type: 'app', name: 'library' }, { type: 'object', name: 'fh79_book' }], - packageId: 'app.fh79', - }, - }, - ], - }; - render(); - expect(onDraftArtifacts).toHaveBeenCalledWith(expect.any(Array), 'app.fh79'); - }); -}); - -/** - * ADR-0038 L3 — the build-health line under a Published card: the host's - * onPublishDrafts may return `{ ok, health }` (seedApplied + runtime probes) - * and the chat must show what the publish ACTUALLY did, not just "Published". - */ -describe('ChatbotEnhanced — publish build-health line (ADR-0038)', () => { - const userMsg: ChatbotEnhancedMessage = { id: 'u1', role: 'user', content: 'build it' }; - const draftMsg = (packageId: string): ChatbotEnhancedMessage => ({ - id: 'a1', - role: 'assistant', - content: 'Built your app.', - toolInvocations: [ - { - toolCallId: 'tc-health', - toolName: 'apply_blueprint', - state: 'output-available', - draftReview: { items: [{ type: 'object', name: 'task' }], packageId, autoPublishable: true }, - }, - ], - }); - - it('renders rows-seeded + verified counts and runtime issues from a structured outcome', async () => { - const onPublishDrafts = vi.fn().mockResolvedValue({ - ok: true, - health: { - seededRows: 12, - checked: { seeds: 2, views: 3, widgets: 4 }, - issues: [ - { severity: 'error', code: 'empty_query', message: 'widget "w1" returns NO data' }, - { severity: 'warning', code: 'probes_unavailable', message: '1 widget not probed' }, - ], - }, - }); - const { rerender } = render( - , - ); - rerender( - , - ); - await waitFor(() => expect(screen.getByTestId('publish-health')).toBeInTheDocument()); - expect(screen.getByText(/12 sample rows live/i)).toBeInTheDocument(); - // Errors present → the "verified" claim is withheld; the findings show instead, - // as the generic sentence on the line with their agent text under the details - // (objectstack#32984: neither finding carries a userMessage). - expect(screen.queryByText(/verified/i)).not.toBeInTheDocument(); - expect(screen.getByTestId('publish-health-summary')).toHaveTextContent(/need fixing/i); - expect(screen.getByText(/returns NO data/i).closest('details')).not.toBeNull(); - expect(screen.getByText(/not probed/i).closest('details')).not.toBeNull(); - }); - - it('claims "verified" only when the probes ran clean', async () => { - const onPublishDrafts = vi.fn().mockResolvedValue({ - ok: true, - health: { seededRows: 6, checked: { seeds: 1, views: 2, widgets: 3 }, issues: [] }, - }); - const { rerender } = render( - , - ); - rerender( - , - ); - await waitFor(() => expect(screen.getByTestId('publish-health')).toBeInTheDocument()); - expect(screen.getByText(/6 sample rows live · 2 views · 3 widgets · 1 sample data set verified/i)).toBeInTheDocument(); - }); - - it('renders the seed-load failure loudly', async () => { - const onPublishDrafts = vi.fn().mockResolvedValue({ - ok: true, - health: { seedError: 'no readable seed bodies' }, - }); - const { rerender } = render( - , - ); - rerender( - , - ); - await waitFor(() => expect(screen.getByTestId('publish-health')).toBeInTheDocument()); - // objectstack#32984 — the line says it; the loader's engine text is the detail. - expect(screen.getByTestId('publish-health-seed')).toHaveTextContent('Sample data failed to load.'); - expect(screen.getByText(/no readable seed bodies/i).closest('details')).not.toBeNull(); - }); - - it('stays silent (no health element) for legacy boolean outcomes', async () => { - const onPublishDrafts = vi.fn().mockResolvedValue(true); - const { rerender } = render( - , - ); - rerender( - , - ); - // Publish resolves → Published badge, but no health line. - await waitFor(() => expect(screen.getByText('Published')).toBeInTheDocument()); - expect(screen.queryByTestId('publish-health')).not.toBeInTheDocument(); - }); - - it('treats {ok:false} as failure — no Published badge', async () => { - const onPublishDrafts = vi.fn().mockResolvedValue({ ok: false }); - const { rerender } = render( - , - ); - rerender( - , - ); - await waitFor(() => expect(onPublishDrafts).toHaveBeenCalled()); - expect(screen.queryByText('Published')).not.toBeInTheDocument(); - }); -}); - -describe('publishHealthFromResponse', () => { - it('maps seedApplied + probes through the {success,data} envelope', async () => { - const { publishHealthFromResponse } = await import('../ChatbotEnhanced'); - const health = publishHealthFromResponse({ - success: true, - data: { - seedApplied: { success: true, inserted: 10, updated: 2 }, - probes: { - checked: { seeds: 2, views: 1, widgets: 3 }, - issues: [{ severity: 'error', code: 'empty_query', message: 'm' }], - }, - }, - }); - expect(health).toEqual({ - seededRows: 12, - checked: { seeds: 2, views: 1, widgets: 3 }, - issues: [{ severity: 'error', code: 'empty_query', message: 'm' }], - }); - }); - - it('maps a failed seedApplied to seedError and tolerates a flat body', async () => { - const { publishHealthFromResponse } = await import('../ChatbotEnhanced'); - const health = publishHealthFromResponse({ - seedApplied: { success: false, errors: ['row 3 rejected'] }, - }); - expect(health).toEqual({ seedFailed: true, seedError: 'row 3 rejected' }); - }); - - it('objectstack#32984 — reads userMessage and fix only when they are non-empty strings', async () => { - const { publishHealthFromResponse } = await import('../ChatbotEnhanced'); - const health = publishHealthFromResponse({ - probes: { - issues: [ - { severity: 'error', code: 'seed_no_rows', message: 'agent text', fix: 'agent fix', userMessage: 'customer sentence' }, - { severity: 'warning', code: 'w', message: 'm2', fix: '', userMessage: ' ' }, - { severity: 'warning', code: 'w', message: 'm3', fix: 42, userMessage: { text: 'x' } }, - ], - }, - }); - expect(health?.issues).toEqual([ - { severity: 'error', code: 'seed_no_rows', message: 'agent text', fix: 'agent fix', userMessage: 'customer sentence' }, - { severity: 'warning', code: 'w', message: 'm2' }, - { severity: 'warning', code: 'w', message: 'm3' }, - ]); - }); - - it('objectstack#32984 — a loader finding object gives its message, and no producer text invents none', async () => { - const { publishHealthFromResponse } = await import('../ChatbotEnhanced'); - expect( - publishHealthFromResponse({ - seedApplied: { - success: false, - errors: [{ sourceObject: 'task', field: 'owner', message: 'Reference not found: owner = "ann"' }], - }, - }), - ).toEqual({ seedFailed: true, seedError: 'Reference not found: owner = "ann"' }); - expect(publishHealthFromResponse({ seedApplied: { success: false } })).toEqual({ seedFailed: true }); - }); - - it('returns undefined when the server reported neither (older runtimes)', async () => { - const { publishHealthFromResponse } = await import('../ChatbotEnhanced'); - expect(publishHealthFromResponse({ success: true, data: { publishedCount: 3 } })).toBeUndefined(); - }); }); describe('ChatbotEnhanced — activity-driven liveness (not a fake clock)', () => { @@ -1366,15 +326,6 @@ describe('ChatbotEnhanced — activity-driven liveness (not a fake clock)', () = vi.useRealTimers(); }); - const buildMsg = (done: number, items: Array<{ type: string; name: string }>, phase = 'structure'): ChatbotEnhancedMessage[] => [ - { - id: 'b1', - role: 'assistant', - content: '', - buildProgress: { phase: phase as 'structure' | 'data' | 'done', appLabel: '进销存', items, done, total: 4 }, - }, - ]; - it('pre-first-token turn shows a neutral "waiting" WITH a live timer, not a fake "receiving"', () => { const { container } = render(); // Honest: the tier is the muted "waiting", never the emerald "receiving" @@ -1400,721 +351,4 @@ describe('ChatbotEnhanced — activity-driven liveness (not a fake clock)', () = // The seconds-since-last-byte stay available on the hover title. expect(liveness?.getAttribute('title')).toMatch(/7s with no response/); }); - - it('build panel reads as "receiving" (m:ss) while progress bytes keep arriving', () => { - const { rerender } = render(); - act(() => { - vi.advanceTimersByTime(2000); - }); - expect(screen.getByText('0:02')).toBeInTheDocument(); - - // A new build-progress part arrives (done 1→2) → activity re-stamped, - // stays "receiving"; it is real stream activity, not a free clock. - rerender( - , - ); - act(() => { - vi.advanceTimersByTime(2000); - }); - expect(screen.getByText('0:04')).toBeInTheDocument(); - expect(screen.queryByText(/Waiting for server/i)).not.toBeInTheDocument(); - }); - - it('build panel flips to amber "still working" when progress genuinely stalls, then recovers on the next byte', () => { - const { container, rerender } = render(); - // No new progress for >6s → honest stall, not a reassuring tick. - act(() => { - vi.advanceTimersByTime(7000); - }); - expect(container.querySelector('[data-liveness-tier]')).toHaveAttribute('data-liveness-tier', 'stalled'); - expect(screen.getByText(/Still working/i)).toBeInTheDocument(); - - // The server sends the next artifact → back to "receiving". - rerender( - , - ); - act(() => { - vi.advanceTimersByTime(1000); - }); - expect(screen.queryByText(/Still working/i)).not.toBeInTheDocument(); - expect(container.querySelector('[data-liveness-tier]')).toHaveAttribute('data-liveness-tier', 'receiving'); - // Back to "receiving" — the m:ss is the whole-turn duration (7s stall + 1s). - expect(screen.getByText('0:08')).toBeInTheDocument(); - }); - - it('server keep-alive heartbeats (bumped seq, identical content) keep the build panel "receiving" through a quiet stretch', () => { - // A seeding level can run >6s with no new artifact — content stays identical. - // The server re-emits a heartbeat that only advances `seq`; that must keep - // the panel green (receiving), proving liveness rides REAL server bytes and - // not a free clock (without the heartbeat, this same gap goes amber — see the - // test above). - const seedingMsg = (seq: number): ChatbotEnhancedMessage[] => [ - { - id: 'b1', - role: 'assistant', - content: '', - buildProgress: { - phase: 'data', - appLabel: '进销存', - items: [{ type: 'object', name: 'product' }], - done: 1, - total: 4, - seq, - }, - }, - ]; - const { rerender } = render(); - // Heartbeats arrive every ~3s; advance 9s but re-stamp via seq at 3s and 6s. - act(() => { - vi.advanceTimersByTime(3000); - }); - rerender(); - act(() => { - vi.advanceTimersByTime(3000); - }); - rerender(); - act(() => { - vi.advanceTimersByTime(2000); - }); - // Never went amber — the heartbeats kept it honestly "receiving". - expect(screen.queryByText(/Waiting for server/i)).not.toBeInTheDocument(); - expect(screen.getByText('0:08')).toBeInTheDocument(); - }); -}); - -// Improvement 2: the propose_blueprint call is a single long, atomic LLM request -// (no token stream), so a bare timer felt stuck. While it runs, the summary strip -// shows a friendly "Designing your app…" lead-in plus a hint that rotates every -// few seconds — presentational reassurance that the wait is moving. -describe('ChatbotEnhanced — propose_blueprint in-progress design hints', () => { - beforeEach(() => { - vi.useFakeTimers(); - Object.defineProperty(navigator, 'clipboard', { - configurable: true, - value: { writeText: vi.fn().mockResolvedValue(undefined) }, - }); - }); - afterEach(() => { - vi.runOnlyPendingTimers(); - vi.useRealTimers(); - }); - - const runningProposal: ChatbotEnhancedMessage[] = [ - { id: 'u1', role: 'user', content: 'build me a CRM' }, - { - id: 'a1', - role: 'assistant', - content: '', - streaming: true, - toolInvocations: [ - { toolCallId: 't1', toolName: 'propose_blueprint', state: 'input-available' }, - ], - }, - ]; - - it('shows the friendly designing indicator (lead-in + rotating hint + timer) for a running proposal', () => { - const { container } = render( - , - ); - const hint = container.querySelector('[data-testid="build-proposal-progress"]'); - expect(hint).not.toBeNull(); - expect(hint?.textContent).toContain('DESIGNING'); - // First hint up immediately, plus the live elapsed timer beside it. - expect(hint?.textContent).toContain('HINT_A'); - expect(hint?.querySelector('[data-tool-running-timer]')).not.toBeNull(); - }); - - it('rotates to the next hint after the interval elapses', () => { - const { container } = render( - , - ); - const hint = () => container.querySelector('[data-testid="build-proposal-progress"]'); - expect(hint()?.textContent).toContain('HINT_A'); - act(() => { - vi.advanceTimersByTime(3500); - }); - expect(hint()?.textContent).toContain('HINT_B'); - expect(hint()?.textContent).not.toContain('HINT_A'); - }); - - it('a non-proposal running tool keeps the plain timer, not the design hint', () => { - const { container } = render( - , - ); - expect(container.querySelector('[data-testid="build-proposal-progress"]')).toBeNull(); - expect(container.querySelector('[data-tool-running-timer]')).not.toBeNull(); - }); -}); - -// Improvement 2: a plan's `assumptions` mix neutral design notes with business -// rules the build is explicitly DEFERRING ("…will be added later / 需要后续单独补"). -// `classifyAssumptions` splits them so the card can surface the deferred set -// apart, and the user can't mistake a still-to-come rule for delivered behaviour. -describe('classifyAssumptions (deferred vs. design-note split)', () => { - it('routes explicit "deferred" markers (zh + en) to `deferred`, keeps the rest as design notes', () => { - const { designNotes, deferred } = classifyAssumptions([ - '设备通过所属客户建立归属关系', // neutral design note - '技师只能看到分配给自己的工单,将在后续 Flow / 权限配置中实现', // deferred (将在 / 后续) - 'Each device belongs to one customer', // neutral design note - 'Role-based access for technicians will be added later', // deferred (will be added / later) - '审批流确认后一起补', // deferred (一起补) - '需要后续单独补权限/流程配置', // deferred (需要后续) - ]); - expect(designNotes).toEqual([ - '设备通过所属客户建立归属关系', - 'Each device belongs to one customer', - ]); - expect(deferred).toEqual([ - '技师只能看到分配给自己的工单,将在后续 Flow / 权限配置中实现', - 'Role-based access for technicians will be added later', - '审批流确认后一起补', - '需要后续单独补权限/流程配置', - ]); - }); - - it('matches deferral markers case-insensitively and is not fooled by a bare "flow"/"permission" mention', () => { - const { designNotes, deferred } = classifyAssumptions([ - 'Approvals are NOT YET wired up', // deferred — uppercase marker - 'A flow runs on every new work order', // built rule that merely mentions "flow" → design note - 'Permissions follow the org role', // built rule that mentions permission → design note - ]); - expect(deferred).toEqual(['Approvals are NOT YET wired up']); - expect(designNotes).toEqual([ - 'A flow runs on every new work order', - 'Permissions follow the org role', - ]); - }); - - it('trims and drops blank/whitespace assumptions and tolerates non-strings', () => { - const { designNotes, deferred } = classifyAssumptions([ - ' One shelf for now ', - '', - ' ', - // @ts-expect-error — guard against malformed backend data - null, - '暂不实现导出', // deferred (暂不) - ]); - expect(designNotes).toEqual(['One shelf for now']); - expect(deferred).toEqual(['暂不实现导出']); - }); - - it('handles the all-design-notes and all-deferred extremes', () => { - expect(classifyAssumptions(['plain a', 'plain b'])).toEqual({ - designNotes: ['plain a', 'plain b'], - deferred: [], - }); - expect(classifyAssumptions(['deferred later', '稍后补充'])).toEqual({ - designNotes: [], - deferred: ['deferred later', '稍后补充'], - }); - }); -}); - -// Improvement 2 (render): the plan card surfaces the deferred assumptions in a -// distinct "Not yet built" section, separate from the ordinary assumptions list. -describe('ChatbotEnhanced — proposed plan deferred-assumptions section', () => { - beforeEach(() => { - Object.defineProperty(navigator, 'clipboard', { - configurable: true, - value: { writeText: vi.fn().mockResolvedValue(undefined) }, - }); - }); - - const planWithAssumptions = (assumptions: string[]): ChatbotEnhancedMessage[] => [ - { - id: 'a1', - role: 'assistant', - content: '', - toolInvocations: [ - { - toolCallId: 't1', - toolName: 'propose_blueprint', - state: 'output-available', - proposedPlan: { - summary: 'A field-service app', - objects: [{ name: 'work_order', label: 'Work Order', fieldCount: 4 }], - counts: { objects: 1, views: 0, dashboards: 0, seedData: 0 }, - questions: [], - assumptions, - }, - }, - ], - }, - ]; - - it('renders deferred assumptions in their own "Not yet built" section, design notes in the normal list', () => { - render( - , - ); - const deferred = screen.getByTestId('proposed-plan-deferred'); - expect(deferred).toHaveTextContent('NOT_YET_BUILT'); - expect(deferred).toHaveTextContent('将在后续权限配置中实现'); - // The neutral note stays in the ordinary assumptions group, NOT the deferred box. - const notes = screen.getByTestId('proposed-plan-assumptions'); - expect(notes).toHaveTextContent('Devices belong to a customer'); - expect(notes).not.toHaveTextContent('将在后续权限配置中实现'); - }); - - it('omits the deferred section entirely when no assumption is deferred', () => { - render( - , - ); - expect(screen.getByTestId('proposed-plan-assumptions')).toBeInTheDocument(); - expect(screen.queryByTestId('proposed-plan-deferred')).not.toBeInTheDocument(); - }); - - it('omits the ordinary assumptions section when every assumption is deferred', () => { - render( - , - ); - expect(screen.getByTestId('proposed-plan-deferred')).toBeInTheDocument(); - expect(screen.queryByTestId('proposed-plan-assumptions')).not.toBeInTheDocument(); - }); -}); - -// Improvement 4: the design-wait hint should read as steady forward progress on a -// long (multi-minute) propose_blueprint call. `selectDesignHintIndex` advances one -// stage per interval, then CLAMPS on the last hint instead of wrapping — so it never -// looks like it restarted, and there is no fake percentage. -describe('selectDesignHintIndex (elapsed → design stage)', () => { - const step = 3500; - it('advances one stage per interval', () => { - expect(selectDesignHintIndex(0, 5, step)).toBe(0); - expect(selectDesignHintIndex(step - 1, 5, step)).toBe(0); - expect(selectDesignHintIndex(step, 5, step)).toBe(1); - expect(selectDesignHintIndex(step * 2, 5, step)).toBe(2); - expect(selectDesignHintIndex(step * 3, 5, step)).toBe(3); - }); - - it('clamps on the final stage rather than wrapping back to the start', () => { - // Way past the last stage (a multi-minute wait) — pins the last hint, never loops. - expect(selectDesignHintIndex(step * 4, 5, step)).toBe(4); - expect(selectDesignHintIndex(step * 50, 5, step)).toBe(4); - expect(selectDesignHintIndex(step * 999, 10, step)).toBe(9); - }); - - it('returns -1 for an empty list and pins index 0 for a single hint', () => { - expect(selectDesignHintIndex(0, 0, step)).toBe(-1); - expect(selectDesignHintIndex(step * 5, 0, step)).toBe(-1); - expect(selectDesignHintIndex(0, 1, step)).toBe(0); - expect(selectDesignHintIndex(step * 5, 1, step)).toBe(0); - }); - - it('treats negative / non-finite elapsed as stage 0 (no crash)', () => { - expect(selectDesignHintIndex(-100, 5, step)).toBe(0); - expect(selectDesignHintIndex(Number.NaN, 5, step)).toBe(0); - // Infinity is not finite → guarded to stage 0 rather than NaN/overflow. - expect(selectDesignHintIndex(Number.POSITIVE_INFINITY, 5, step)).toBe(0); - }); -}); - -// Improvement 4 (render): the running-proposal indicator shows step dots that fill -// up to the current stage and advances forward through a longer hint pool. -describe('ChatbotEnhanced — design-wait staging (dots + forward progress)', () => { - beforeEach(() => { - vi.useFakeTimers(); - Object.defineProperty(navigator, 'clipboard', { - configurable: true, - value: { writeText: vi.fn().mockResolvedValue(undefined) }, - }); - }); - afterEach(() => { - vi.runOnlyPendingTimers(); - vi.useRealTimers(); - }); - - const runningProposal: ChatbotEnhancedMessage[] = [ - { id: 'u1', role: 'user', content: 'build me a CRM' }, - { - id: 'a1', - role: 'assistant', - content: '', - streaming: true, - toolInvocations: [ - { toolCallId: 't1', toolName: 'propose_blueprint', state: 'input-available' }, - ], - }, - ]; - - it('renders one step dot per hint and advances the hint forward as the wait grows', () => { - const { container } = render( - , - ); - const dots = () => container.querySelector('[data-testid="build-proposal-progress-dots"]'); - const hint = () => container.querySelector('[data-testid="build-proposal-progress"]'); - expect(dots()?.children.length).toBe(3); - expect(hint()?.textContent).toContain('HINT_A'); - act(() => { - vi.advanceTimersByTime(3500); - }); - expect(hint()?.textContent).toContain('HINT_B'); - act(() => { - vi.advanceTimersByTime(3500); - }); - expect(hint()?.textContent).toContain('HINT_C'); - }); - - it('clamps on the last hint on a long wait instead of looping back', () => { - const { container } = render( - , - ); - const hint = () => container.querySelector('[data-testid="build-proposal-progress"]'); - act(() => { - vi.advanceTimersByTime(3500 * 8); // well past the last stage - }); - expect(hint()?.textContent).toContain('HINT_B'); - expect(hint()?.textContent).not.toContain('HINT_A'); - }); - - it('shows no step dots when rotation is disabled (single hint)', () => { - const { container } = render( - , - ); - expect(container.querySelector('[data-testid="build-proposal-progress"]')).not.toBeNull(); - expect(container.querySelector('[data-testid="build-proposal-progress-dots"]')).toBeNull(); - }); -}); - -describe('ChatbotEnhanced — propose_blueprint live design progress (data-blueprint-progress)', () => { - beforeEach(() => { - vi.useFakeTimers(); - Object.defineProperty(navigator, 'clipboard', { - configurable: true, - value: { writeText: vi.fn().mockResolvedValue(undefined) }, - }); - }); - afterEach(() => { - vi.runOnlyPendingTimers(); - vi.useRealTimers(); - }); - - // A running propose_blueprint whose stream has begun emitting the reconciled - // `data-blueprint-progress` part — lifted onto the message as blueprintProgress - // by uiMessageToChatMessage (see mapMessages.test.ts for the event→data half). - const designing = ( - blueprintProgress: NonNullable, - ): ChatbotEnhancedMessage[] => [ - { id: 'u1', role: 'user', content: 'build me a recruiting app' }, - { - id: 'a1', - role: 'assistant', - content: '', - streaming: true, - toolInvocations: [ - { toolCallId: 't1', toolName: 'propose_blueprint', state: 'input-available' }, - ], - blueprintProgress, - }, - ]; - - it('renders the live design panel with object chips (label + field count) and the summary', () => { - const { container } = render( - , - ); - const panel = container.querySelector('[data-testid="blueprint-progress"]'); - expect(panel).not.toBeNull(); - expect(panel?.textContent).toContain('Designing your app…'); - // Summary one-liner revealed progressively. - expect(panel?.textContent).toContain('招聘管理系统'); - const chips = container.querySelector('[data-testid="blueprint-progress-objects"]'); - expect(chips).not.toBeNull(); - expect(chips?.textContent).toContain('候选人'); - expect(chips?.textContent).toContain('职位'); - // Field-count suffix on the chips. - expect(chips?.textContent).toContain('5'); - expect(chips?.textContent).toContain('4'); - // Compact counts line. - expect(panel?.textContent).toContain('2 objects'); - }); - - it('object chips reflect the latest streamed frame as objects accrue one by one', () => { - const { container, rerender } = render( - , - ); - let chips = container.querySelector('[data-testid="blueprint-progress-objects"]'); - expect(chips?.querySelectorAll('span[title]').length).toBe(1); - // The next reconciled frame reveals a second object — in place. - rerender( - , - ); - chips = container.querySelector('[data-testid="blueprint-progress-objects"]'); - expect(chips?.querySelectorAll('span[title]').length).toBe(2); - expect(chips?.textContent).toContain('职位'); - }); - - it('supersedes the rotating-hint placeholder once real progress events arrive', () => { - const { container } = render( - , - ); - // The event-driven panel is up… - expect(container.querySelector('[data-testid="blueprint-progress"]')).not.toBeNull(); - // …and the purely-presentational rotating hint is NOT also shown in the - // activity strip (no duplicate "designing" affordance). - expect(container.querySelector('[data-testid="build-proposal-progress"]')).toBeNull(); - }); - - it('falls back to the rotating-hint placeholder when NO progress events arrive (older runtimes)', () => { - const { container } = render( - , - ); - // No blueprintProgress → no panel, and the placeholder behaves exactly as before. - expect(container.querySelector('[data-testid="blueprint-progress"]')).toBeNull(); - expect(container.querySelector('[data-testid="build-proposal-progress"]')).not.toBeNull(); - }); - - it('hands off to the authoritative "Proposed plan" card once the result lands (panel goes away)', () => { - render( - , - ); - expect(document.querySelector('[data-testid="blueprint-progress"]')).toBeNull(); - expect(screen.getByTestId('proposed-plan')).toBeInTheDocument(); - }); - - it('shows the extend-mode badge with the target app when extending', () => { - const { container } = render( - , - ); - const badge = container.querySelector('[data-testid="blueprint-progress-extend"]'); - expect(badge).not.toBeNull(); - expect(badge?.textContent).toContain('Extending'); - expect(badge?.textContent).toContain('recruiting'); - }); -}); - -/** - * One build turn renders ONE plan card: the newest `propose_blueprint` result, - * the plan the runtime builds. Each message goes through the real live mapper - * (`uiMessagesToChatMessages`) from raw tool parts. - */ -describe('one plan card per build turn — the newest propose_blueprint result', () => { - const plan = (n: number) => ({ - status: 'blueprint_proposed', - summary: `Plan ${n}`, - blueprint: { - app: { label: `App ${n}` }, - objects: [{ name: 'book', label: 'Book', fields: [{ name: 'title' }] }], - }, - counts: { objects: 1, views: 0, dashboards: 0, seedData: 0 }, - questions: [], - }); - const proposePart = (n: number, state: 'output-available' | 'input-available' = 'output-available') => ({ - type: 'tool-propose_blueprint', - toolCallId: `plan-${n}`, - state, - input: {}, - ...(state === 'output-available' ? { output: plan(n) } : {}), - }); - const user = (id: string) => ({ id, role: 'user' as const, parts: [{ type: 'text', text: 'build me a library app' }] }); - const titles = () => screen.getAllByTestId('proposed-plan-title').map((el) => el.textContent); - - it('a turn with four propose_blueprint results draws one card, the newest', () => { - render( - proposePart(n)) }, - ])} - />, - ); - expect(screen.getAllByTestId('proposed-plan')).toHaveLength(1); - expect(titles()).toEqual(['Proposed plan · App 4']); - // The earlier results draw as a completed step: no unstructured confirm - // card, nothing awaiting the user, one "Build it". - expect(screen.queryByTestId('proposed-plan-fallback')).toBeNull(); - expect(screen.getByTestId('tool-phase-line')).toHaveTextContent(/^Completed/); - expect(screen.getAllByTestId('proposed-plan-approve')).toHaveLength(1); - }); - - it('while the turn streams, the newest landed result is the card', () => { - render( - , - ); - expect(titles()).toEqual(['Proposed plan · App 2']); - }); - - it('PRESERVATION: a plan from a previous turn keeps its card', () => { - render( - proposePart(n)) }, - ])} - />, - ); - expect(titles()).toEqual(['Proposed plan · App 0', 'Proposed plan · App 4']); - }); }); diff --git a/ui/packages/plugin-chatbot/src/__tests__/buildCards.contract-12724.test.ts b/ui/packages/plugin-chatbot/src/__tests__/buildCards.contract-12724.test.ts deleted file mode 100644 index ab99d529af4..00000000000 --- a/ui/packages/plugin-chatbot/src/__tests__/buildCards.contract-12724.test.ts +++ /dev/null @@ -1,142 +0,0 @@ -/** - * ObjectUI - * Copyright (c) 2024-present ObjectStack Inc. - * - * objectui#12724 — the build cards render only what the producer declared, so - * the payloads their tests feed must be payloads the producer can send. - * - * The producer's contract is objectstack-ai/cloud's `build-cards.schema.json`, - * vendored as `fixtures/build-cards.schema.ts`. No JSON Schema validator is a - * dependency of this package, so the check below walks the subset of JSON - * Schema that file uses — `type`, `properties`, `required`, - * `additionalProperties`, `items`, `oneOf`, `const`, `enum`, `minLength`, - * `minItems`, `maxItems`, `minimum` — and refuses any other keyword it meets, - * so a newer schema that leans on one fails here instead of passing unread. - */ -import { describe, expect, it } from 'vitest'; -import { BUILD_CARDS_SCHEMA } from './fixtures/build-cards.schema'; -import { applyEnvelope, planEnvelope, verifyEnvelope } from './fixtures/buildCards.fixtures'; - -type Schema = Record; - -const KNOWN = new Set([ - '$schema', - '$comment', - 'title', - 'type', - 'properties', - 'required', - 'additionalProperties', - 'propertyNames', - 'items', - 'oneOf', - 'const', - 'enum', - 'minLength', - 'minItems', - 'maxItems', - 'minimum', - 'maximum', -]); - -/** Every violation of `schema` by `value`, as `path: reason`. */ -function violations(schema: Schema, value: unknown, path = '$'): string[] { - const unknownKeyword = Object.keys(schema).find((k) => !KNOWN.has(k)); - if (unknownKeyword) return [`${path}: schema keyword ${unknownKeyword} is not checked here`]; - const out: string[] = []; - if ('const' in schema && value !== schema.const) out.push(`${path}: expected const ${String(schema.const)}`); - if (Array.isArray(schema.enum) && !schema.enum.includes(value)) out.push(`${path}: not in enum`); - if (Array.isArray(schema.oneOf)) { - const passing = (schema.oneOf as Schema[]).filter((s) => violations(s, value, path).length === 0); - if (passing.length !== 1) out.push(`${path}: matches ${passing.length} oneOf branches`); - return out; - } - switch (schema.type) { - case 'string': - if (typeof value !== 'string') return [`${path}: not a string`]; - if (typeof schema.minLength === 'number' && value.length < schema.minLength) out.push(`${path}: too short`); - break; - case 'integer': - if (!Number.isInteger(value)) return [`${path}: not an integer`]; - if (typeof schema.minimum === 'number' && (value as number) < schema.minimum) out.push(`${path}: below minimum`); - break; - case 'boolean': - if (typeof value !== 'boolean') return [`${path}: not a boolean`]; - break; - case 'array': { - if (!Array.isArray(value)) return [`${path}: not an array`]; - if (typeof schema.minItems === 'number' && value.length < schema.minItems) out.push(`${path}: too few items`); - if (typeof schema.maxItems === 'number' && value.length > schema.maxItems) out.push(`${path}: too many items`); - const items = schema.items as Schema | undefined; - if (items) value.forEach((v, i) => out.push(...violations(items, v, `${path}[${i}]`))); - break; - } - case 'object': { - if (!value || typeof value !== 'object' || Array.isArray(value)) return [`${path}: not an object`]; - const obj = value as Record; - const props = (schema.properties ?? {}) as Record; - for (const key of (schema.required ?? []) as string[]) { - if (!(key in obj)) out.push(`${path}.${key}: required`); - } - for (const [key, v] of Object.entries(obj)) { - if (props[key]) out.push(...violations(props[key], v, `${path}.${key}`)); - else if (schema.additionalProperties === false) out.push(`${path}.${key}: not declared`); - else if (schema.additionalProperties && typeof schema.additionalProperties === 'object') { - out.push(...violations(schema.additionalProperties as Schema, v, `${path}.${key}`)); - } - } - break; - } - case undefined: - break; - default: - out.push(`${path}: schema type ${String(schema.type)} is not checked here`); - } - return out; -} - -const defs = BUILD_CARDS_SCHEMA.$defs as Record; -const PLAN = defs.ProposeBlueprintCardPayload; -const RESULT = defs.BuildResultCardPayload; - -describe('the build-card fixtures are payloads the producer declares (objectui#12724)', () => { - it('reads both definitions off the vendored schema', () => { - expect(PLAN?.type).toBe('object'); - expect(RESULT?.type).toBe('object'); - expect(PLAN.required).toEqual(['status', 'blueprint', 'planCard']); - expect(RESULT.required).toEqual(['checklist', 'nextSteps']); - }); - - it.each(['zh', 'en'] as const)('%s: the propose_blueprint envelope satisfies ProposeBlueprintCardPayload', (lang) => { - expect(violations(PLAN, planEnvelope(lang))).toEqual([]); - }); - - it.each(['zh', 'en'] as const)('%s: the envelope with a generated loan title satisfies ProposeBlueprintCardPayload (objectui#13004)', (lang) => { - expect(violations(PLAN, planEnvelope(lang, { generatedTitle: true }))).toEqual([]); - }); - - it.each(['zh', 'en'] as const)('%s: the envelopes with a publish posture satisfy ProposeBlueprintCardPayload (cloud#2924)', (lang) => { - expect(violations(PLAN, planEnvelope(lang, { posture: 'firstBuild' }))).toEqual([]); - expect(violations(PLAN, planEnvelope(lang, { posture: 'draft' }))).toEqual([]); - }); - - it.each(['zh', 'en'] as const)('%s: the apply_blueprint envelopes satisfy BuildResultCardPayload', (lang) => { - expect(violations(RESULT, applyEnvelope(lang))).toEqual([]); - expect(violations(RESULT, applyEnvelope(lang, { materialized: true }))).toEqual([]); - }); - - it.each(['zh', 'en'] as const)('%s: the verify_build envelopes satisfy BuildResultCardPayload', (lang) => { - expect(violations(RESULT, verifyEnvelope(lang))).toEqual([]); - expect(violations(RESULT, verifyEnvelope(lang, { failedView: true }))).toEqual([]); - }); - - it('CONTROL — the walk refuses a key the card schema does not declare, and a missing required key', () => { - const plan = planEnvelope('zh'); - const extraKey = { ...plan, planCard: { ...plan.planCard, nameTemplate: '{图书} · {读者}' } }; - expect(violations(PLAN, extraKey)).toEqual(['$.planCard.nameTemplate: not declared']); - const { checklist: _dropped, ...noChecklist } = applyEnvelope('zh'); - expect(violations(RESULT, noChecklist)).toEqual(['$.checklist: required']); - const twoSteps = { ...applyEnvelope('zh'), nextSteps: ['a', 'b'] }; - expect(violations(RESULT, twoSteps)).toEqual(['$.nextSteps: too few items']); - }); -}); diff --git a/ui/packages/plugin-chatbot/src/__tests__/buildGroupLabel-27419.test.tsx b/ui/packages/plugin-chatbot/src/__tests__/buildGroupLabel-27419.test.tsx deleted file mode 100644 index 31383c91fdc..00000000000 --- a/ui/packages/plugin-chatbot/src/__tests__/buildGroupLabel-27419.test.tsx +++ /dev/null @@ -1,56 +0,0 @@ -/** - * ObjectUI - * Copyright (c) 2024-present ObjectStack Inc. - * - * objectstack#27419 — no build-panel group heading is a raw artifact type. The - * staged set is no union here (`ChatBuildProgress.items` types `type` as a free - * string; cloud's `apply_blueprint` produces it), so `STAGED_TYPES` is what a - * real build staged; a type added later lands on "Other", the second case. - */ -import '@testing-library/jest-dom/vitest'; -import { describe, it, expect, vi, afterEach } from 'vitest'; -import { render, screen, cleanup } from '@testing-library/react'; -import { I18nProvider } from '@object-ui/i18n'; -import { ChatbotEnhanced } from '../ChatbotEnhanced'; - -const STAGED_TYPES = ['object', 'view', 'dashboard', 'app', 'seed', 'dataset', 'permission'] as const; -type Heading = (typeof STAGED_TYPES)[number] | 'other'; -const HEADINGS: Record<'zh' | 'en', Record> = { - zh: { object: '对象', view: '视图', dashboard: '仪表盘', app: '应用', seed: '示例数据', dataset: '数据集', permission: '权限', other: '其他' }, - en: { object: 'Objects', view: 'Views', dashboard: 'Dashboards', app: 'App', seed: 'Sample data', dataset: 'Datasets', permission: 'Permissions', other: 'Other' }, -}; - -// Labels differ from every type id and heading, so a text match finds headings. -const ITEMS = [...STAGED_TYPES, 'flow'].map((type) => ({ type, name: `${type}_item`, label: `item ${type}` })); - -function renderIn(language: 'zh' | 'en') { - const buildProgress = { phase: 'structure' as const, appLabel: 'CRM', items: ITEMS, done: 3, total: 8 }; - return render( - - - , - ); -} - -afterEach(cleanup); - -describe.each(['zh', 'en'] as const)('build panel group headings (%s)', (language) => { - it('names every staged type, and none renders as its raw type', () => { - renderIn(language); - for (const type of STAGED_TYPES) { - expect(screen.getByText(HEADINGS[language][type])).toBeInTheDocument(); - expect(screen.queryByText(type)).not.toBeInTheDocument(); - } - }); - - it('an unnamed type falls to the neutral Other heading, never its raw type', () => { - renderIn(language); - expect(screen.getByText(HEADINGS[language].other)).toBeInTheDocument(); - expect(screen.queryByText('flow')).not.toBeInTheDocument(); - expect(screen.queryByText(/chatbot\.build/)).not.toBeInTheDocument(); - }); -}); diff --git a/ui/packages/plugin-chatbot/src/__tests__/buildPanelI18n-7388.test.tsx b/ui/packages/plugin-chatbot/src/__tests__/buildPanelI18n-7388.test.tsx deleted file mode 100644 index 725658a4608..00000000000 --- a/ui/packages/plugin-chatbot/src/__tests__/buildPanelI18n-7388.test.tsx +++ /dev/null @@ -1,191 +0,0 @@ -/** - * ObjectUI - * Copyright (c) 2024-present ObjectStack Inc. - * - * objectui#7388 — the apply_blueprint BUILD PANEL, in the user's language. - * - * Everything the panel is HANDED is localized: the host passes - * `openBuiltAppLabel` / `designBuiltAppLabel` / `previewDraftLabel` and the - * three connection cues through its own `t()`. Everything the panel OWNED was - * an English literal in the component — the two header frames, the - * sample-data suffix, the five per-type row headings, and the overflow - * counter. So a fully Chinese conversation watched a build under an English - * header, over five English row headings, one per row, on every build. - * - * The predicate this file pins is the CLASS, not a key count: no English - * literal on the panel bypasses the pack. Each subject case therefore also - * asserts the English it replaced is absent, which is what a missing key would - * bring back (the fallback renders the English default, never a raw key). - * - * ## The control, and why it is a real one - * - * `renderEn` runs the SAME three known phases (`structure` / `data` / `done`) - * through an `en` provider and pins them to the exact strings the component - * used to hard-code. It moves independently of the subject: it stays green if - * the `zh` values are wrong or missing, and it reddens only if the ENGLISH - * rendering changed — which is the regression this refactor could actually - * cause. The provider-less English world is pinned separately and was already - * there: `ChatbotEnhanced.test.tsx`'s "renders a live build tree" / - * "collapses to a Built summary". - */ -import '@testing-library/jest-dom/vitest'; -import { describe, it, expect, vi, afterEach } from 'vitest'; -import { render, screen, cleanup } from '@testing-library/react'; -import { I18nProvider } from '@object-ui/i18n'; -import { ChatbotEnhanced, type ChatbotEnhancedMessage } from '../ChatbotEnhanced'; - -function renderIn(language: string, ui: React.ReactElement) { - return render( - - {ui} - , - ); -} - -const ITEMS = [ - { type: 'object', name: 'customer' }, - { type: 'view', name: 'customer.list' }, - { type: 'dashboard', name: 'sales' }, - { type: 'seed', name: 'customer_sample' }, -]; - -function buildMsg( - phase: 'structure' | 'data' | 'done', - over: Partial> = {}, -): ChatbotEnhancedMessage { - return { - id: 'a1', - role: 'assistant', - content: '', - streaming: phase !== 'done', - buildProgress: { phase, appLabel: 'CRM', items: ITEMS, done: 4, total: 6, ...over }, - }; -} - -function panel(phase: 'structure' | 'data' | 'done', over = {}) { - return ; -} - -afterEach(cleanup); - -// --------------------------------------------------------------------------- -// CONTROL — the English rendering of the three KNOWN phases, unchanged. -// --------------------------------------------------------------------------- -describe('control: a known phase renders exactly as it did before (en)', () => { - it('structure — header, row headings, no sample-data suffix', () => { - renderIn('en', panel('structure')); - expect(screen.getByTestId('build-progress')).toBeInTheDocument(); - expect(screen.getByText('Building CRM…')).toBeInTheDocument(); - expect(screen.getByText('Objects')).toBeInTheDocument(); - expect(screen.getByText('Views')).toBeInTheDocument(); - expect(screen.getByText('Dashboards')).toBeInTheDocument(); - expect(screen.getByText('Sample data')).toBeInTheDocument(); - expect(screen.queryByText('adding sample data')).not.toBeInTheDocument(); - }); - - it('data — the sample-data suffix appears, header still "Building"', () => { - renderIn('en', panel('data')); - expect(screen.getByText('Building CRM…')).toBeInTheDocument(); - expect(screen.getByText('adding sample data')).toBeInTheDocument(); - }); - - it('done — collapses to the "Built" summary', () => { - renderIn('en', panel('done')); - expect(screen.getByText('Built CRM')).toBeInTheDocument(); - }); - - it('an unnamed build still says "your app"', () => { - renderIn('en', panel('structure', { appLabel: undefined })); - expect(screen.getByText('Building your app…')).toBeInTheDocument(); - }); -}); - -// --------------------------------------------------------------------------- -// SUBJECT — the same panel under a zh console. -// --------------------------------------------------------------------------- -describe('the build panel under a zh console (objectui#7388)', () => { - // The header composes the verb and the app name with the ` · ` separator - // `builtAndLive` already used: a name pasted straight onto the verb ran on - // into one word (「已构建Library Lending Management」). - it('localizes the in-flight header instead of hard-coding "Building X…"', () => { - renderIn('zh', panel('structure')); - expect(screen.getByText('正在构建 · CRM…')).toBeInTheDocument(); - expect(screen.queryByText(/Building/)).not.toBeInTheDocument(); - }); - - it('localizes the finished header instead of hard-coding "Built X"', () => { - renderIn('zh', panel('done')); - expect(screen.getByText('已构建 · CRM')).toBeInTheDocument(); - expect(screen.queryByText(/^Built /)).not.toBeInTheDocument(); - }); - - it('localizes the sample-data suffix', () => { - renderIn('zh', panel('data')); - expect(screen.getByText('正在添加示例数据')).toBeInTheDocument(); - expect(screen.queryByText('adding sample data')).not.toBeInTheDocument(); - }); - - it('localizes every per-type row heading — the five that render on every build', () => { - renderIn('zh', panel('structure')); - for (const zh of ['对象', '视图', '仪表盘', '示例数据']) { - expect(screen.getByText(zh)).toBeInTheDocument(); - } - for (const en of ['Objects', 'Views', 'Dashboards', 'Sample data']) { - expect(screen.queryByText(en)).not.toBeInTheDocument(); - } - }); - - it('localizes the "App" row heading too', () => { - renderIn('zh', panel('done', { items: [...ITEMS, { type: 'app', name: 'crm' }] })); - expect(screen.getByText('应用')).toBeInTheDocument(); - expect(screen.queryByText('App')).not.toBeInTheDocument(); - }); - - // The stand-in goes through the same frame, so it reads the way - // `builtAndLive` already reads for an unnamed build (「已搭建并上线 · 你的应用」). - it('localizes the unnamed-build stand-in, so the header is Chinese end to end', () => { - renderIn('zh', panel('structure', { appLabel: undefined })); - expect(screen.getByText('正在构建 · 你的应用…')).toBeInTheDocument(); - expect(screen.queryByText(/your app/)).not.toBeInTheDocument(); - }); - - it('localizes the ">6 artifacts" overflow counter', () => { - const many = Array.from({ length: 8 }, (_, i) => ({ type: 'object', name: `obj_${i}` })); - renderIn('zh', panel('structure', { items: many })); - expect(screen.getByText(/\+2 个/)).toBeInTheDocument(); - expect(screen.queryByText(/more/)).not.toBeInTheDocument(); - }); - - // The safe shape the card's boundary asks for, on the OTHER unknown-value - // fallback this panel has: a type no pack names renders the neutral "Other" - // heading (objectstack#27419), never its raw type, and never a raw i18n key. - it('an unknown artifact type renders the Other heading, not its type or a key', () => { - renderIn('zh', panel('structure', { items: [{ type: 'flow', name: 'onboarding' }] })); - expect(screen.getByText('其他')).toBeInTheDocument(); - expect(screen.queryByText('flow')).not.toBeInTheDocument(); - expect(screen.queryByText(/chatbot\.build/)).not.toBeInTheDocument(); - }); -}); - -// --------------------------------------------------------------------------- -// The other two CJK packs keep their headers as they are: neither runs the -// verb into the name. ja puts the name first and a particle after it, ko -// already leaves a space before the verb. -// --------------------------------------------------------------------------- -describe('the build panel header under ja and ko consoles', () => { - it('ja — the name leads and the particle separates it from the verb', () => { - renderIn('ja', panel('structure')); - expect(screen.getByText('CRMを構築しています…')).toBeInTheDocument(); - cleanup(); - renderIn('ja', panel('done')); - expect(screen.getByText('CRMを構築しました')).toBeInTheDocument(); - }); - - it('ko — a space already separates the name from the verb', () => { - renderIn('ko', panel('structure')); - expect(screen.getByText('CRM 빌드 중…')).toBeInTheDocument(); - cleanup(); - renderIn('ko', panel('done')); - expect(screen.getByText('CRM 빌드 완료')).toBeInTheDocument(); - }); -}); diff --git a/ui/packages/plugin-chatbot/src/__tests__/buildVerify-11988.test.tsx b/ui/packages/plugin-chatbot/src/__tests__/buildVerify-11988.test.tsx deleted file mode 100644 index 1d218772fde..00000000000 --- a/ui/packages/plugin-chatbot/src/__tests__/buildVerify-11988.test.tsx +++ /dev/null @@ -1,169 +0,0 @@ -/** - * ObjectUI - * Copyright (c) 2024-present ObjectStack Inc. - * - * objectui#11988 — the build-progress RECEIVER reads the post-apply - * verification loop (cloud#2172 ruling A, the wire shape of cloud PR #2721). - * - * The loop reports on its own `data-build-progress` part, id `build-verify`, - * beside the apply_blueprint tree: a hop is `{ phase: 'verify', hop, tool }` - * and the exit is `{ phase: 'done' }`. The receiver used to take the LAST - * `data-build-progress` part whatever its id and coerce any phase but - * `data` / `done` to `structure`, so the first hop replaced the finished tree - * with "Building your app…". - * - * Pinned here, through the real mapper and the real panel: - * - the tree and the verify part are read apart, by part id, in either order; - * - the verify line advances per hop and closes on `done`; - * - control: a message with only the tree is unchanged; - * - a phase outside the spec's vocabulary is surfaced, never "Building". - */ -import '@testing-library/jest-dom/vitest'; -import { describe, it, expect, vi, afterEach } from 'vitest'; -import { render, screen, cleanup } from '@testing-library/react'; -import { BUILD_PROGRESS_PHASES, type BuildProgressPhase } from '@objectstack/spec/ai'; -import { I18nProvider } from '@object-ui/i18n'; -import { ChatbotEnhanced, type ChatBuildProgress } from '../ChatbotEnhanced'; -import { uiMessageToChatMessage } from '../mapMessages'; - -type Assert = T; -type Equal = (() => T extends A ? 1 : 2) extends () => T extends B ? 1 : 2 - ? true - : false; - -const ITEMS = [ - { type: 'object', name: 'customer' }, - { type: 'view', name: 'customer.list' }, - { type: 'app', name: 'crm' }, -]; - -/** The apply_blueprint tree, finished — what the verify loop runs after. */ -const TREE = { - type: 'data-build-progress', - id: 'build-progress', - data: { phase: 'done', appLabel: 'CRM', items: ITEMS, done: 3, total: 3 }, -}; - -function verifyPart(data: Record) { - return { type: 'data-build-progress', id: 'build-verify', data }; -} - -function map(parts: Array>) { - return uiMessageToChatMessage({ id: 'a1', role: 'assistant', parts }); -} - -function renderIn(language: string, parts: Array>) { - return render( - - - , - ); -} - -afterEach(cleanup); - -describe('the published phase union IS the spec vocabulary plus `unknown` (objectui#11988)', () => { - it('is pinned at compile time, in both directions', () => { - // A `tsc` error, not a runtime failure: compiled by this package's - // `tsconfig.test.json`. A phase the spec adds or drops turns it red. - type _TreePhaseIsSpec = Assert, BuildProgressPhase>>; - type _VerifyPhaseIsSpec = Assert< - Equal['phase'], 'unknown'>, BuildProgressPhase> - >; - expect(true).toBe(true); - }); -}); - -describe('the receiver keeps the tree and the build-verify part apart (objectui#11988)', () => { - it('a verify hop never displaces the finished tree', () => { - const out = map([TREE, verifyPart({ phase: 'verify', hop: 1, tool: 'verify_build' })]); - expect(out.buildProgress).toEqual({ - phase: 'done', - appLabel: 'CRM', - items: ITEMS, - done: 3, - total: 3, - verify: { phase: 'verify', hop: 1, tool: 'verify_build' }, - }); - }); - - it('is keyed by part id, not by position: a verify part ahead of the tree changes nothing', () => { - const out = map([verifyPart({ phase: 'verify', hop: 1, tool: 'verify_build' }), TREE]); - expect(out.buildProgress).toMatchObject({ phase: 'done', appLabel: 'CRM', items: ITEMS }); - expect(out.buildProgress?.verify).toEqual({ phase: 'verify', hop: 1, tool: 'verify_build' }); - }); - - it('the exit frame closes the verify state', () => { - const out = map([TREE, verifyPart({ phase: 'done' })]); - expect(out.buildProgress?.verify).toEqual({ phase: 'done' }); - expect(out.buildProgress?.phase).toBe('done'); - }); - - it('control: a message with only the tree maps exactly as before, with no verify state', () => { - const out = map([TREE]); - expect(out.buildProgress).toEqual({ phase: 'done', appLabel: 'CRM', items: ITEMS, done: 3, total: 3 }); - }); - - it('a verify part with no tree beside it is not read as a build tree', () => { - const out = map([verifyPart({ phase: 'verify', hop: 2, tool: 'verify_build' })]); - expect(out.buildProgress).toBeUndefined(); - }); - - it('reads every phase of the spec vocabulary as itself, on the tree and on the verify part', () => { - for (const phase of BUILD_PROGRESS_PHASES) { - const out = map([{ ...TREE, data: { ...TREE.data, phase } }, verifyPart({ phase })]); - expect(out.buildProgress?.phase).toBe(phase); - expect(out.buildProgress?.verify?.phase).toBe(phase); - } - }); - - it('a phase outside the vocabulary is `unknown` on either part, never coerced to `structure`', () => { - const out = map([{ ...TREE, data: { ...TREE.data, phase: 'deploying' } }, verifyPart({ phase: 'rechecking' })]); - expect(out.buildProgress?.phase).toBe('unknown'); - expect(out.buildProgress?.verify?.phase).toBe('unknown'); - }); -}); - -describe('the build panel renders the verify line (objectui#11988)', () => { - it('shows the finished tree AND a verify line that advances per hop', () => { - renderIn('en', [TREE, verifyPart({ phase: 'verify', hop: 1, tool: 'verify_build' })]); - expect(screen.getByText('Built CRM')).toBeInTheDocument(); - expect(screen.getByTestId('build-verify')).toHaveTextContent('Checking the change… step 1'); - expect(screen.getByTestId('build-verify')).toHaveAttribute('title', 'verify_build'); - expect(screen.queryByText(/Building/)).not.toBeInTheDocument(); - cleanup(); - - renderIn('en', [TREE, verifyPart({ phase: 'verify', hop: 2, tool: 'verify_build' })]); - expect(screen.getByTestId('build-verify')).toHaveTextContent('Checking the change… step 2'); - }); - - it('closes the verify line on `done`', () => { - renderIn('en', [TREE, verifyPart({ phase: 'done' })]); - expect(screen.getByText('Built CRM')).toBeInTheDocument(); - expect(screen.getByTestId('build-verify')).toHaveTextContent('Checked the change'); - expect(screen.getByTestId('build-verify')).not.toHaveTextContent(/Checking/); - }); - - it('control: a tree-only message renders the panel unchanged, with no verify line', () => { - renderIn('en', [TREE]); - expect(screen.getByText('Built CRM')).toBeInTheDocument(); - expect(screen.queryByTestId('build-verify')).not.toBeInTheDocument(); - }); - - it('an unknown tree phase is surfaced as a warning, not rendered as "Building"', () => { - renderIn('en', [{ ...TREE, data: { ...TREE.data, phase: 'deploying' } }]); - expect(screen.getByText('Unknown build phase')).toBeInTheDocument(); - expect(screen.queryByText(/Building/)).not.toBeInTheDocument(); - }); - - it('an unknown verify phase is surfaced as a warning on the verify line', () => { - renderIn('en', [TREE, verifyPart({ phase: 'rechecking' })]); - expect(screen.getByTestId('build-verify')).toHaveTextContent('Unknown build phase'); - }); - - it('the verify line is localized through the pack', () => { - renderIn('zh', [TREE, verifyPart({ phase: 'verify', hop: 3, tool: 'verify_build' })]); - expect(screen.getByTestId('build-verify')).toHaveTextContent('正在检查改动… 第 3 步'); - expect(screen.queryByText(/Checking the change/)).not.toBeInTheDocument(); - }); -}); diff --git a/ui/packages/plugin-chatbot/src/__tests__/chat-message-contract.test.ts b/ui/packages/plugin-chatbot/src/__tests__/chat-message-contract.test.ts index 921d9505a39..dd3c93920a6 100644 --- a/ui/packages/plugin-chatbot/src/__tests__/chat-message-contract.test.ts +++ b/ui/packages/plugin-chatbot/src/__tests__/chat-message-contract.test.ts @@ -157,8 +157,6 @@ describe("the barrel's ChatbotEnhancedMessage IS the enhanced shape", () => { type _HasReasoning = Assert>; type _HasSources = Assert>; type _HasTraceId = Assert>; - type _HasBuildProgress = Assert>; - type _HasBlueprintProgress = Assert>; type _HasCharts = Assert>; // The retirement is a WIDENING, which is what makes it safe for existing @@ -259,8 +257,8 @@ describe("useObjectChat's declared message type is honest about both modes", () // objectui#4424. The hook declared `messages: OuiChatMessage[]` (the // AUTHORING contract) and produced it honestly in local mode only — API // mode built RUNTIME messages and cast them with `as OuiChatMessage[]`, - // erasing `buildProgress`, `blueprintProgress`, `charts` and every HITL / - // draft-review extension on the tool invocations. The values survived + // erasing `charts`, `recordCitations` and the HITL approval id on the + // tool invocations. The values survived // because nothing on the path rebuilt a message; the declaration was the // trap, and these pins are what keeps it closed. @@ -312,18 +310,11 @@ describe("useObjectChat's declared message type is honest about both modes", () // 4. …plus the render-only keys API mode really carries. Named one by one // so a future narrowing says WHICH capability it dropped — each of these - // is a rendered affordance: the build panel, the design panel, inline - // charts, the approval card, the "Review N changes" entry point, the - // proposed-plan card, the confirm-changes card, "Open in Builder". - type _HasBuildProgress = Assert>; - type _HasBlueprintProgress = Assert>; + // is a rendered affordance: inline charts, record citations, the + // approval card. type _HasCharts = Assert>; type HookToolInvocation = NonNullable[number]; type _HasPendingActionId = Assert>; - type _HasDraftReview = Assert>; - type _HasProposedPlan = Assert>; - type _HasProposedChanges = Assert>; - type _HasBuilderHandoff = Assert>; // 5. The compatibility statement, re-derived (objectui#10018). The honest // type WAS a subtype of the authoring one until the authoring `state` @@ -416,12 +407,9 @@ describe("the seam's input contract names the keys it passes through", () => { // preserved by faith: `tsc` could not see one of them, and the pass-through // test had to cast its fixture into place. `SeamChatMessage` names them. type _SeamNotAny = Assert, false>>; - type _SeamHasBuildProgress = Assert>; - type _SeamHasBlueprintProgress = Assert>; type _SeamHasCharts = Assert>; type SeamTool = NonNullable[number]; type _SeamToolHasPendingActionId = Assert>; - type _SeamToolHasDraftReview = Assert>; // It is the seam's INPUT, so it stays wide enough for both callers: a host // holding plain authored messages (the reason the adapter is exported from @@ -528,8 +516,8 @@ describe('the Date → ISO absorption is expressed once', () => { expect( /as\s+OuiChatMessage\[\]/.test(codeOnly), 'useObjectChat.ts casts its API-mode messages into the @object-ui/types ' + - 'authoring contract again. That cast erases `buildProgress`, ' + - '`blueprintProgress`, `charts` and the HITL / draft-review extensions on ' + + 'authoring contract again. That cast erases `charts`, ' + + '`recordCitations` and the HITL approval id on ' + 'every tool invocation (objectui#4424). The hook declares ' + '`ObjectChatMessage`, which those values satisfy — assign, do not assert.', ).toBe(false); diff --git a/ui/packages/plugin-chatbot/src/__tests__/chatMessageAdapter.test.ts b/ui/packages/plugin-chatbot/src/__tests__/chatMessageAdapter.test.ts index cc9e3c6a246..4e959fc0330 100644 --- a/ui/packages/plugin-chatbot/src/__tests__/chatMessageAdapter.test.ts +++ b/ui/packages/plugin-chatbot/src/__tests__/chatMessageAdapter.test.ts @@ -110,45 +110,40 @@ describe('pass-through: the API-mode payload survives the seam', () => { // In API mode `useObjectChat` hands the renderer messages carrying keys the // authoring contract does not declare. The `as any` casts preserved them by // accident; the adapter must preserve them on purpose, or the HITL approval - // card, the "Review N changes" affordance and the build panel all vanish from - // the SDUI renderers. + // card and the inline charts vanish from the SDUI renderers. // // objectui#4424 — read the ANNOTATION, it is half the test. This fixture used // to need `as unknown as AuthoredChatMessage`: the authoring type declares // none of these keys, so the only way to hand them to the adapter was to // assert past the compiler, which is the same blindness the hook's own // `as OuiChatMessage[]` had. `SeamChatMessage` names them, so the fixture is - // now type-checked: misspell `buildProgress`, or give `draftReview` the wrong + // now type-checked: misspell `charts`, or give `pendingActionId` the wrong // shape, and this file goes red at compile time instead of quietly testing a // payload the seam was never going to see. const apiModeMessage: SeamChatMessage = { id: 'm2', role: 'assistant', - content: 'built it', + content: 'here it is', metadata: { conversationId: 'c1' }, - buildProgress: { phase: 'done', items: [], done: 3, total: 3 }, charts: [{ chartType: 'bar', data: [], series: [] }], toolInvocations: [ { toolCallId: 'call_2', - toolName: 'apply_blueprint', + toolName: 'run_action', state: 'output-available', pendingActionId: 'pa_1', - draftReview: { items: [{ type: 'object', name: 'Loan' }] }, }, ], }; it('keeps the runtime-only message keys', () => { const runtime = authoredToRuntimeMessage(apiModeMessage); - expect(runtime.buildProgress).toEqual({ phase: 'done', items: [], done: 3, total: 3 }); expect(runtime.charts).toHaveLength(1); }); it('keeps the runtime-only tool-invocation extensions', () => { const [tool] = authoredToRuntimeMessage(apiModeMessage).toolInvocations ?? []; expect(tool?.pendingActionId).toBe('pa_1'); - expect(tool?.draftReview?.items).toEqual([{ type: 'object', name: 'Loan' }]); }); it('keeps `metadata`, which the runtime contract does not declare', () => { diff --git a/ui/packages/plugin-chatbot/src/__tests__/fixtures/build-cards.schema.ts b/ui/packages/plugin-chatbot/src/__tests__/fixtures/build-cards.schema.ts deleted file mode 100644 index 3724fa0e30c..00000000000 --- a/ui/packages/plugin-chatbot/src/__tests__/fixtures/build-cards.schema.ts +++ /dev/null @@ -1,799 +0,0 @@ -// Vendored from objectstack-ai/cloud packages/service-ai-studio/schema/build-cards.schema.json at f0ecef3a (cloud PR #3111); the object below is that file verbatim. -// -// objectui#12724 — the producer's contract for the two build cards the chat draws: -// `ProposeBlueprintCardPayload` (`propose_blueprint`'s `planCard`, beside the -// blueprint) and `BuildResultCardPayload` (`apply_blueprint` / `verify_build`'s -// `checklist` and `nextSteps`). The cloud repository is private, so the copy -// lives here, as a test fixture: `buildCards.contract-12724.test.ts` checks every -// fixture payload this package's card tests use against it. Refresh it by -// copying that file again at a newer sha and renaming the sha above; never edit -// the object by hand. -export const BUILD_CARDS_SCHEMA: Record = -{ - "$schema": "https://json-schema.org/draft/2020-12/schema", - "$comment": "GENERATED from packages/service-ai-studio/src/build-cards.ts (buildCardJsonSchema) by src/__tests__/build-cards.contract.test.ts — rewrite it with `vitest -u`, never by hand.", - "title": "AI build cards: the propose_blueprint plan card and the apply_blueprint / verify_build result card", - "$defs": { - "ProposeBlueprintCardPayload": { - "type": "object", - "properties": { - "status": { - "type": "string", - "const": "blueprint_proposed" - }, - "blueprint": { - "type": "object", - "propertyNames": { - "type": "string" - }, - "additionalProperties": {} - }, - "viewIntents": { - "type": "array", - "items": { - "type": "object", - "properties": { - "view": { - "type": "string", - "minLength": 1 - }, - "object": { - "type": "string", - "minLength": 1 - }, - "label": { - "type": "string", - "minLength": 1 - }, - "line": { - "type": "string", - "minLength": 1 - } - }, - "required": [ - "view", - "object", - "line" - ], - "additionalProperties": false - } - }, - "planCard": { - "type": "object", - "properties": { - "objects": { - "type": "array", - "items": { - "type": "object", - "properties": { - "name": { - "type": "string", - "minLength": 1 - }, - "label": { - "type": "string", - "minLength": 1 - }, - "fields": { - "type": "array", - "items": { - "type": "object", - "properties": { - "name": { - "type": "string", - "minLength": 1 - }, - "label": { - "type": "string", - "minLength": 1 - }, - "type": { - "type": "string", - "minLength": 1 - }, - "format": { - "type": "object", - "properties": { - "kind": { - "type": "string", - "enum": [ - "isbn13", - "email", - "phone", - "url" - ] - }, - "label": { - "type": "string", - "minLength": 1 - } - }, - "required": [ - "kind", - "label" - ], - "additionalProperties": false - }, - "lifecycle": { - "type": "object", - "properties": { - "options": { - "type": "array", - "items": { - "type": "object", - "properties": { - "value": { - "type": "string", - "minLength": 1 - }, - "label": { - "type": "string", - "minLength": 1 - }, - "kind": { - "type": "string", - "enum": [ - "open", - "won", - "lost" - ] - } - }, - "required": [ - "value", - "label", - "kind" - ], - "additionalProperties": false - } - }, - "label": { - "type": "string", - "minLength": 1 - } - }, - "required": [ - "options", - "label" - ], - "additionalProperties": false - }, - "suggested": { - "type": "boolean", - "const": true - } - }, - "required": [ - "name", - "label", - "type" - ], - "additionalProperties": false - } - }, - "nameField": { - "type": "object", - "properties": { - "name": { - "type": "string", - "minLength": 1 - }, - "label": { - "type": "string", - "minLength": 1 - }, - "generated": { - "type": "object", - "properties": { - "template": { - "type": "string", - "minLength": 1 - }, - "line": { - "type": "string", - "minLength": 1 - } - }, - "required": [ - "template", - "line" - ], - "additionalProperties": false - } - }, - "required": [ - "name", - "label" - ], - "additionalProperties": false - } - }, - "required": [ - "name", - "label", - "fields" - ], - "additionalProperties": false - } - }, - "views": { - "type": "array", - "items": { - "type": "object", - "properties": { - "view": { - "type": "string", - "minLength": 1 - }, - "object": { - "type": "string", - "minLength": 1 - }, - "label": { - "type": "string", - "minLength": 1 - }, - "layout": { - "type": "string", - "enum": [ - "list", - "form", - "kanban", - "calendar", - "gallery", - "gantt" - ] - }, - "groupBy": { - "type": "object", - "properties": { - "name": { - "type": "string", - "minLength": 1 - }, - "label": { - "type": "string", - "minLength": 1 - } - }, - "required": [ - "name", - "label" - ], - "additionalProperties": false - }, - "filters": { - "type": "array", - "items": { - "type": "object", - "properties": { - "field": { - "type": "string", - "minLength": 1 - }, - "operator": { - "type": "string", - "minLength": 1 - }, - "value": {} - }, - "required": [ - "field", - "operator" - ], - "additionalProperties": false - } - }, - "sort": { - "type": "array", - "items": { - "type": "object", - "properties": { - "field": { - "type": "string", - "minLength": 1 - }, - "order": { - "type": "string", - "enum": [ - "asc", - "desc" - ] - } - }, - "required": [ - "field", - "order" - ], - "additionalProperties": false - } - }, - "fields": { - "type": "array", - "items": { - "type": "object", - "properties": { - "name": { - "type": "string", - "minLength": 1 - }, - "label": { - "type": "string", - "minLength": 1 - } - }, - "required": [ - "name", - "label" - ], - "additionalProperties": false - } - }, - "line": { - "type": "string", - "minLength": 1 - } - }, - "required": [ - "view", - "object", - "layout", - "filters", - "sort", - "fields", - "line" - ], - "additionalProperties": false - } - }, - "assumptions": { - "type": "array", - "items": { - "type": "string" - } - }, - "sampleData": { - "type": "object", - "properties": { - "objects": { - "type": "array", - "items": { - "type": "object", - "properties": { - "object": { - "type": "string", - "minLength": 1 - }, - "label": { - "type": "string", - "minLength": 1 - }, - "rows": { - "type": "integer", - "minimum": 0, - "maximum": 9007199254740991 - } - }, - "required": [ - "object", - "label", - "rows" - ], - "additionalProperties": false - } - }, - "unique": { - "type": "array", - "items": { - "type": "object", - "properties": { - "object": { - "type": "string", - "minLength": 1 - }, - "fields": { - "type": "array", - "items": { - "type": "object", - "properties": { - "name": { - "type": "string", - "minLength": 1 - }, - "label": { - "type": "string", - "minLength": 1 - } - }, - "required": [ - "name", - "label" - ], - "additionalProperties": false - } - } - }, - "required": [ - "object", - "fields" - ], - "additionalProperties": false - } - }, - "formats": { - "type": "array", - "items": { - "type": "object", - "properties": { - "object": { - "type": "string", - "minLength": 1 - }, - "field": { - "type": "string", - "minLength": 1 - }, - "label": { - "type": "string", - "minLength": 1 - }, - "format": { - "type": "object", - "properties": { - "kind": { - "type": "string", - "enum": [ - "isbn13", - "email", - "phone", - "url" - ] - }, - "label": { - "type": "string", - "minLength": 1 - } - }, - "required": [ - "kind", - "label" - ], - "additionalProperties": false - } - }, - "required": [ - "object", - "field", - "label", - "format" - ], - "additionalProperties": false - } - }, - "line": { - "type": "string", - "minLength": 1 - } - }, - "required": [ - "objects", - "unique", - "formats", - "line" - ], - "additionalProperties": false - }, - "posture": { - "type": "object", - "properties": { - "mode": { - "type": "string", - "enum": [ - "publish", - "draft" - ] - }, - "liveRecords": { - "type": "integer", - "minimum": 0, - "maximum": 9007199254740991 - }, - "line": { - "type": "string", - "minLength": 1 - } - }, - "required": [ - "mode", - "liveRecords", - "line" - ], - "additionalProperties": false - } - }, - "required": [ - "objects", - "views", - "assumptions" - ], - "additionalProperties": false - } - }, - "required": [ - "status", - "blueprint", - "planCard" - ], - "additionalProperties": {} - }, - "BuildResultCardPayload": { - "type": "object", - "properties": { - "checklist": { - "type": "object", - "properties": { - "status": { - "type": "string", - "enum": [ - "passed", - "failed" - ] - }, - "passed": { - "type": "integer", - "minimum": 0, - "maximum": 9007199254740991 - }, - "total": { - "type": "integer", - "minimum": 0, - "maximum": 9007199254740991 - }, - "lines": { - "type": "array", - "items": { - "oneOf": [ - { - "type": "object", - "properties": { - "kind": { - "type": "string", - "const": "object" - }, - "object": { - "type": "string", - "minLength": 1 - }, - "label": { - "type": "string", - "minLength": 1 - }, - "status": { - "type": "string", - "enum": [ - "passed", - "failed" - ] - }, - "fields": { - "type": "integer", - "minimum": 0, - "maximum": 9007199254740991 - }, - "sampleRows": { - "type": "integer", - "minimum": 0, - "maximum": 9007199254740991 - }, - "line": { - "type": "string", - "minLength": 1 - } - }, - "required": [ - "kind", - "object", - "label", - "status", - "line" - ], - "additionalProperties": false - }, - { - "type": "object", - "properties": { - "kind": { - "type": "string", - "const": "view" - }, - "view": { - "type": "string", - "minLength": 1 - }, - "object": { - "type": "string", - "minLength": 1 - }, - "label": { - "type": "string", - "minLength": 1 - }, - "status": { - "type": "string", - "enum": [ - "passed", - "failed" - ] - }, - "matched": { - "type": "integer", - "minimum": 0, - "maximum": 9007199254740991 - }, - "total": { - "type": "integer", - "minimum": 0, - "maximum": 9007199254740991 - }, - "groups": { - "type": "array", - "items": { - "type": "object", - "properties": { - "value": { - "type": "string", - "minLength": 1 - }, - "label": { - "type": "string", - "minLength": 1 - }, - "count": { - "type": "integer", - "minimum": 0, - "maximum": 9007199254740991 - } - }, - "required": [ - "value", - "label", - "count" - ], - "additionalProperties": false - } - }, - "line": { - "type": "string", - "minLength": 1 - } - }, - "required": [ - "kind", - "view", - "object", - "label", - "status", - "line" - ], - "additionalProperties": false - }, - { - "type": "object", - "properties": { - "kind": { - "type": "string", - "const": "sampleData" - }, - "status": { - "type": "string", - "const": "passed" - }, - "unique": { - "type": "object", - "propertyNames": { - "type": "string" - }, - "additionalProperties": { - "type": "array", - "items": { - "type": "string" - } - } - }, - "formats": { - "type": "array", - "items": { - "type": "object", - "properties": { - "object": { - "type": "string", - "minLength": 1 - }, - "field": { - "type": "string", - "minLength": 1 - }, - "format": { - "type": "string", - "enum": [ - "isbn13", - "email", - "phone", - "url" - ] - } - }, - "required": [ - "object", - "field", - "format" - ], - "additionalProperties": false - } - }, - "line": { - "type": "string", - "minLength": 1 - } - }, - "required": [ - "kind", - "status", - "unique", - "formats", - "line" - ], - "additionalProperties": false - } - ] - } - }, - "app": { - "type": "object", - "properties": { - "name": { - "type": "string", - "minLength": 1 - }, - "label": { - "type": "string", - "minLength": 1 - } - }, - "required": [ - "name" - ], - "additionalProperties": false - }, - "packageId": { - "type": "string", - "minLength": 1 - } - }, - "required": [ - "status", - "passed", - "total", - "lines" - ], - "additionalProperties": false - }, - "nextSteps": { - "minItems": 3, - "maxItems": 3, - "type": "array", - "items": { - "type": "string", - "minLength": 1 - } - } - }, - "required": [ - "checklist", - "nextSteps" - ], - "additionalProperties": {} - } - } -} -; diff --git a/ui/packages/plugin-chatbot/src/__tests__/fixtures/buildCards.fixtures.ts b/ui/packages/plugin-chatbot/src/__tests__/fixtures/buildCards.fixtures.ts deleted file mode 100644 index 790e29dc780..00000000000 --- a/ui/packages/plugin-chatbot/src/__tests__/fixtures/buildCards.fixtures.ts +++ /dev/null @@ -1,401 +0,0 @@ -/** - * ObjectUI - * Copyright (c) 2024-present ObjectStack Inc. - * - * objectui#12724 — tool envelopes carrying the two build cards' payloads, in the - * shape objectstack-ai/cloud's `build-cards.schema.json` declares (vendored - * beside this file as `build-cards.schema.ts`). The library-lending build the - * AiBuild artboard draws, once in each language the screenshots use. - * - * Every payload exported here is checked against the vendored schema by - * `buildCards.contract-12724.test.ts`, so a card test cannot pass on a key the - * producer never declared. - */ - -type Lang = 'zh' | 'en'; - -const W = { - zh: { - app: '图书借阅管理', - book: '图书', - reader: '读者', - loan: '借阅记录', - title: '书名', - author: '作者', - copies: '馆藏数量', - category: '分类', - fullName: '姓名', - email: '邮箱', - phone: '电话', - loanDate: '借出日期', - dueDate: '应还日期', - returnDate: '归还日期', - status: '状态', - isbnFormat: '13 位数字', - emailFormat: '邮箱格式', - phoneFormat: '电话格式', - board: '借阅看板', - overdue: '逾期未还记录', - boardLine: '看板 · 按 状态 分组 · 卡片:图书、读者、应还日期', - overdueLine: '列表 · 筛选 状态 = 逾期 且 归还日期 为空 · 按应还日期升序', - allBooksLine: '列表 · 显示全部记录', - assumptions: [ - '只建这三部分,不建仪表盘、预约、罚款;补充的字段(分类)可以去掉。', - '归还后状态置为已还;逾期由应还日期已过且未归还判定。', - ], - sampleLine: '示例数据 12 条/对象', - bookLine: '图书 · 5 个字段 · 12 条示例', - readerLine: '读者 · 3 个字段 · 12 条示例', - loanLine: '借阅记录 · 6 个字段 · 12 条示例', - boardCheck: '借阅看板 · 按状态分组 · 5 / 4 / 3', - overdueCheck: '逾期未还记录 · 筛选生效 · 命中 3 条', - allBooksCheck: '图书 · 显示全部记录 · 12 条', - sampleCheck: '示例数据 · 无重复 · ISBN / 邮箱格式通过', - borrowed: '借出', - returned: '已还', - overdueOption: '逾期', - statusLifecycle: '借出 · 已还 ✓完成 · 逾期 ⚠', - loanTitle: '借阅标题', - loanTitleTemplate: '{图书} · {读者} · {借出日期}', - loanTitleLine: '名称:自动生成「{图书} · {读者} · {借出日期}」,表单里不出现', - nextSteps: ['给借阅记录加续借次数', '做一个本月借出统计的仪表盘', '只允许管理员删除图书'], - postureFirstBuild: '首次搭建直接上线;之后的修改先存草稿,由你发布', - postureIntoLiveApp: '这个应用已上线,有 36 条记录在用;这次的改动先存为草稿,由你在「变更」里核对后发布', - }, - en: { - app: 'Library Lending', - book: 'Book', - reader: 'Reader', - loan: 'Loan', - title: 'Title', - author: 'Author', - copies: 'Copies', - category: 'Category', - fullName: 'Full name', - email: 'Email', - phone: 'Phone', - loanDate: 'Loan date', - dueDate: 'Due date', - returnDate: 'Return date', - status: 'Status', - isbnFormat: '13 digits', - emailFormat: 'email format', - phoneFormat: 'phone format', - board: 'Loan board', - overdue: 'Overdue loans', - boardLine: 'Board · grouped by Status · cards: Book, Reader, Due date', - overdueLine: 'List · filter Status = Overdue and Return date is empty · by Due date ascending', - allBooksLine: 'List · shows every record', - assumptions: [ - 'Only these three parts: no dashboard, reservations or fines; the suggested field (Category) can go.', - 'Returning a book sets its status to Returned; a loan is overdue once its due date passes unreturned.', - ], - sampleLine: 'Sample data: 12 rows per object', - bookLine: 'Book · 5 fields · 12 sample rows', - readerLine: 'Reader · 3 fields · 12 sample rows', - loanLine: 'Loan · 6 fields · 12 sample rows', - boardCheck: 'Loan board · grouped by Status · 5 / 4 / 3', - overdueCheck: 'Overdue loans · filter applied · 3 rows match', - allBooksCheck: 'Book · shows every record · 12 rows', - sampleCheck: 'Sample data · no duplicates · ISBN and email formats pass', - borrowed: 'Borrowed', - returned: 'Returned', - overdueOption: 'Overdue', - statusLifecycle: 'Borrowed · Returned ✓done · Overdue ⚠', - loanTitle: 'Loan title', - loanTitleTemplate: '{Book} · {Reader} · {Loan date}', - loanTitleLine: 'Name: generated as “{Book} · {Reader} · {Loan date}”, not on the form', - nextSteps: ['Add a renewal count to loans', 'Make a dashboard of this month’s loans', 'Only admins may delete books'], - postureFirstBuild: 'This first build goes live at once; later changes are saved as drafts for you to publish', - postureIntoLiveApp: - 'This app is live with 36 records in use; this change is saved as a draft for you to review in Changes and publish', - }, -} as const; - -/** - * `propose_blueprint`'s `blueprint_proposed` envelope with `planCard` and `viewIntents`. - * `generatedTitle: true` (objectui#13004) gives the loan a record title composed - * from its two lookups and its date, as cloud#2925's builder writes it: a formula - * `nameField` on the blueprint, and on the plan card `nameField.generated` with - * the title field left out of the loan's chips (its line stands for it). - * `posture` (cloud#2924 ruling A) adds `planCard.posture` as `planCardOf` - * writes it: `'firstBuild'` for a new app's first build, `'draft'` for a build - * into an app live with 36 records. - */ -export function planEnvelope( - lang: Lang, - opts: { generatedTitle?: boolean; posture?: 'firstBuild' | 'draft' } = {}, -) { - const w = W[lang]; - const posture = - opts.posture === 'firstBuild' - ? { mode: 'publish' as const, liveRecords: 0, line: w.postureFirstBuild } - : opts.posture === 'draft' - ? { mode: 'draft' as const, liveRecords: 36, line: w.postureIntoLiveApp } - : undefined; - const loanTitleField = { - name: 'title', - label: w.loanTitle, - type: 'formula', - expression: "joinNonEmpty([record.book.title, record.reader.full_name, record.loan_date], ' · ')", - }; - const planViews = [ - { - view: 'loan_board', - object: 'loan', - label: w.board, - layout: 'kanban', - groupBy: { name: 'status', label: w.status }, - filters: [], - sort: [], - fields: [ - { name: 'book', label: w.book }, - { name: 'reader', label: w.reader }, - { name: 'due_date', label: w.dueDate }, - ], - line: w.boardLine, - }, - { - view: 'overdue_loans', - object: 'loan', - label: w.overdue, - layout: 'list', - filters: [ - { field: 'status', operator: '=', value: 'overdue' }, - { field: 'return_date', operator: 'is_null' }, - ], - sort: [{ field: 'due_date', order: 'asc' }], - fields: [], - line: w.overdueLine, - }, - { view: 'all_books', object: 'book', label: w.book, layout: 'list', filters: [], sort: [], fields: [], line: w.allBooksLine }, - ]; - return { - status: 'blueprint_proposed', - counts: { objects: 3, views: 3, dashboards: 0, seedData: 0 }, - questions: [], - blueprint: { - app: { name: 'library_app', label: w.app }, - objects: [ - { - name: 'book', - label: w.book, - nameField: 'title', - fields: [ - { name: 'title', label: w.title, type: 'text' }, - { name: 'author', label: w.author, type: 'text' }, - { name: 'isbn', label: 'ISBN', type: 'text' }, - { name: 'copies', label: w.copies, type: 'number' }, - { name: 'category', label: w.category, type: 'text' }, - ], - }, - { - name: 'reader', - label: w.reader, - nameField: 'full_name', - fields: [ - { name: 'full_name', label: w.fullName, type: 'text' }, - { name: 'email', label: w.email, type: 'email' }, - { name: 'phone', label: w.phone, type: 'phone' }, - ], - }, - { - name: 'loan', - label: w.loan, - ...(opts.generatedTitle ? { nameField: 'title' } : {}), - fields: [ - ...(opts.generatedTitle ? [loanTitleField] : []), - { name: 'book', label: w.book, type: 'lookup', reference: 'book' }, - { name: 'reader', label: w.reader, type: 'lookup', reference: 'reader' }, - { name: 'loan_date', label: w.loanDate, type: 'date' }, - { name: 'due_date', label: w.dueDate, type: 'date' }, - { name: 'return_date', label: w.returnDate, type: 'date' }, - { name: 'status', label: w.status, type: 'select' }, - ], - }, - ], - views: [ - { object: 'loan', name: 'loan_board', label: w.board, type: 'kanban', groupBy: 'status' }, - { object: 'loan', name: 'overdue_loans', label: w.overdue, type: 'list' }, - { object: 'book', name: 'all_books', label: w.book, type: 'list' }, - ], - // Deliberately NOT the plan card's list: the card must read `planCard`. - assumptions: ['blueprint assumption the plan card does not repeat'], - }, - viewIntents: planViews.map(({ view, object, label, line }) => ({ view, object, label, line })), - planCard: { - objects: [ - { - name: 'book', - label: w.book, - fields: [ - { name: 'title', label: w.title, type: 'text' }, - { name: 'author', label: w.author, type: 'text' }, - { name: 'isbn', label: 'ISBN', type: 'text', format: { kind: 'isbn13', label: w.isbnFormat } }, - { name: 'copies', label: w.copies, type: 'number' }, - { name: 'category', label: w.category, type: 'text', suggested: true }, - ], - nameField: { name: 'title', label: w.title }, - }, - { - name: 'reader', - label: w.reader, - fields: [ - { name: 'full_name', label: w.fullName, type: 'text' }, - { name: 'email', label: w.email, type: 'email', format: { kind: 'email', label: w.emailFormat } }, - { name: 'phone', label: w.phone, type: 'phone', format: { kind: 'phone', label: w.phoneFormat } }, - ], - nameField: { name: 'full_name', label: w.fullName }, - }, - { - name: 'loan', - label: w.loan, - fields: [ - { name: 'book', label: w.book, type: 'lookup' }, - { name: 'reader', label: w.reader, type: 'lookup' }, - { name: 'loan_date', label: w.loanDate, type: 'date' }, - { name: 'due_date', label: w.dueDate, type: 'date' }, - { name: 'return_date', label: w.returnDate, type: 'date' }, - { - name: 'status', - label: w.status, - type: 'select', - // objectui#12994 — the stage field's lifecycle, as cloud's `cardFieldLifecycle` writes it. - lifecycle: { - options: [ - { value: 'borrowed', label: w.borrowed, kind: 'open' }, - { value: 'returned', label: w.returned, kind: 'won' }, - { value: 'overdue', label: w.overdueOption, kind: 'lost' }, - ], - label: w.statusLifecycle, - }, - }, - ], - ...(opts.generatedTitle - ? { - nameField: { - name: 'title', - label: w.loanTitle, - generated: { template: w.loanTitleTemplate, line: w.loanTitleLine }, - }, - } - : {}), - }, - ], - views: planViews, - assumptions: [...w.assumptions], - sampleData: { - objects: [ - { object: 'book', label: w.book, rows: 12 }, - { object: 'reader', label: w.reader, rows: 12 }, - { object: 'loan', label: w.loan, rows: 12 }, - ], - unique: [{ object: 'book', fields: [{ name: 'isbn', label: 'ISBN' }] }], - formats: [ - { object: 'book', field: 'isbn', label: 'ISBN', format: { kind: 'isbn13', label: w.isbnFormat } }, - { object: 'reader', field: 'email', label: w.email, format: { kind: 'email', label: w.emailFormat } }, - ], - line: w.sampleLine, - }, - ...(posture ? { posture } : {}), - }, - }; -} - -/** The result card's `checklist`, as `buildResultChecklist` measures it. */ -export function checklistOf(lang: Lang, opts: { failedView?: boolean } = {}) { - const w = W[lang]; - const lines = [ - { kind: 'object', object: 'book', label: w.book, status: 'passed', fields: 5, sampleRows: 12, line: w.bookLine }, - { kind: 'object', object: 'reader', label: w.reader, status: 'passed', fields: 3, sampleRows: 12, line: w.readerLine }, - { kind: 'object', object: 'loan', label: w.loan, status: 'passed', fields: 6, sampleRows: 12, line: w.loanLine }, - { - kind: 'view', - view: 'loan.loan_board', - object: 'loan', - label: w.board, - status: 'passed', - matched: 12, - total: 12, - groups: [ - { value: 'borrowed', label: w.borrowed, count: 5 }, - { value: 'returned', label: w.returned, count: 4 }, - { value: 'overdue', label: w.overdueOption, count: 3 }, - ], - line: w.boardCheck, - }, - { - kind: 'view', - view: 'loan.overdue_loans', - object: 'loan', - label: w.overdue, - status: opts.failedView ? 'failed' : 'passed', - matched: 3, - total: 12, - line: w.overdueCheck, - }, - { kind: 'view', view: 'book.all_books', object: 'book', label: w.book, status: 'passed', matched: 12, total: 12, line: w.allBooksCheck }, - { - kind: 'sampleData', - status: 'passed', - unique: { book: ['isbn'] }, - formats: [ - { object: 'book', field: 'isbn', format: 'isbn13' }, - { object: 'reader', field: 'email', format: 'email' }, - ], - line: w.sampleCheck, - }, - ]; - const passed = lines.filter((l) => l.status === 'passed').length; - return { - status: passed === lines.length ? 'passed' : 'failed', - passed, - total: lines.length, - lines, - app: { name: 'library_app', label: w.app }, - packageId: 'app.hcpl', - }; -} - -const DRAFTED = [ - { type: 'object', name: 'book' }, - { type: 'object', name: 'reader' }, - { type: 'object', name: 'loan' }, - { type: 'view', name: 'loan.loan_board' }, - { type: 'view', name: 'loan.overdue_loans' }, - { type: 'view', name: 'book.all_books' }, - { type: 'app', name: 'library_app' }, -]; - -/** - * `apply_blueprint`'s envelope. `materialized: true` is the published-in-turn - * build: no cloud producer answers `apply_blueprint` with `status: 'published'`, - * an in-turn publish stays `drafted` and says it materialized. - */ -export function applyEnvelope(lang: Lang, opts: { materialized?: boolean } = {}) { - return { - status: 'drafted', - packageId: 'app.hcpl', - drafted: DRAFTED, - failed: [], - autoPublishable: true, - ...(opts.materialized ? { materialized: true } : {}), - summary: lang === 'zh' ? '已搭建 7 项' : 'Built 7 artifacts', - checklist: checklistOf(lang), - nextSteps: [...W[lang].nextSteps], - }; -} - -/** `verify_build`'s envelope after a repair: it re-measures the checklist. */ -export function verifyEnvelope(lang: Lang, opts: { failedView?: boolean } = {}) { - return { - status: opts.failedView ? 'failed' : 'passed', - checked: 7, - errors: opts.failedView ? 1 : 0, - warnings: 0, - issues: [], - checklist: checklistOf(lang, opts), - nextSteps: [...W[lang].nextSteps], - note: 'verified', - }; -} diff --git a/ui/packages/plugin-chatbot/src/__tests__/fixtures/changePosture.fixtures.ts b/ui/packages/plugin-chatbot/src/__tests__/fixtures/changePosture.fixtures.ts deleted file mode 100644 index 25e030f1f92..00000000000 --- a/ui/packages/plugin-chatbot/src/__tests__/fixtures/changePosture.fixtures.ts +++ /dev/null @@ -1,132 +0,0 @@ -/** - * ObjectUI - * Copyright (c) 2024-present ObjectStack Inc. - * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. - * - * objectui#12894 — the two envelopes cloud#2924 sends for a copilot change to - * a live app with records, as objectstack-ai/cloud writes them in - * `packages/service-ai-studio` (read at cloud `main` `1e3e04f8`): - * - * - the `changes_proposed` card: `changesProposedEnvelope` (with - * `postureEnvelope` and `describeEditOps`'s rows), `metadata-tools.ts` and - * `confirm-gate.ts`; - * - the applied (`drafted`) envelope of the confirm replay, stamped by - * `describeLandedChange` (`draftState` from `readDraftState` in - * `change-posture.ts`, `existingRows`, `appliedCard`). - * - * The sentences are `authoring-copy.ts`'s ZH and EN tables, byte for byte - * (`confirmChangeAsDraft`, `savedAsDraft`, `existingRowsEmpty`, - * `checkedStructure`, `changeParams`). The edit is the producer's own test - * fixture (`RENEWAL_EDIT` in `copilot-change-posture.test.ts`: a number field - * with default 0 on the borrowing table), plus one view row, which is the - * StudioRailCopilot artboard's second row. - * - * No schema declares these envelopes (cloud declares `build-cards.schema.json` - * for the build cards only), so the producer's source is the declaration. - */ - -export type Lang = 'zh' | 'en'; - -export const PACKAGE_ID = 'app.hcpl'; -export const BORROWING = 'lib_borrowing_record'; - -const COPY = { - zh: { - confirmChange: '应用前请确认这次改动。', - confirmChangeAsDraft: (n: number) => - `这个应用已上线,有 ${n} 条记录在用。改动先存为草稿;画布和右侧属性里能看到效果,你在「变更」里核对后再发布。`, - fieldParams: '续借次数 · 默认 0 · 不必填', - label: '续借次数', - savedAsDraft: (n: number) => `已存为草稿 · ${n} 项未发布`, - existingRowsEmpty: (rows: number, label: string) => `已有 ${rows} 条记录的${label}为空`, - checkedStructure: '核对:结构 ✓', - }, - en: { - confirmChange: 'Confirm this change before it is applied.', - confirmChangeAsDraft: (n: number) => - `This app is live with ${n} record(s) in use. The change is saved as a draft first — you can see it on the ` + - 'canvas and in the properties panel; review it in Changes, then publish.', - fieldParams: 'Renewals · default 0 · optional', - label: 'Renewals', - savedAsDraft: (n: number) => `Saved as a draft · ${n} unpublished change(s)`, - existingRowsEmpty: (rows: number, label: string) => `${rows} existing record(s) have no ${label} yet`, - checkedStructure: 'Checked: structure ✓', - }, -} as const; - -/** `describeEditOps` rows for the renewal edit plus the board's card-field update. */ -export function changeRows(lang: Lang) { - return [ - { verb: 'add_field', object: BORROWING, field: 'renewal_count', type: 'number', details: COPY[lang].fieldParams }, - { verb: 'update_metadata', type: 'view', name: 'borrowing_board' }, - ]; -} - -/** - * The `changes_proposed` card. `posture` absent is the envelope an older cloud - * sends (and one where the environment does not publish AI changes in the turn). - */ -export function proposedEnvelope( - lang: Lang, - posture: 'draft' | 'publish' | 'absent', - liveRecords = 12, -): Record { - const copy = COPY[lang]; - const asDraft = posture === 'draft'; - return { - status: 'changes_proposed', - applied: false, - changes: changeRows(lang), - summary: asDraft ? copy.confirmChangeAsDraft(liveRecords) : copy.confirmChange, - ...(posture === 'absent' - ? {} - : { - posture: { mode: posture, liveRecords: asDraft ? liveRecords : 0 }, - primaryAction: asDraft ? 'save_draft' : 'confirm', - }), - // The model's half of the envelope: no consumer renders it. - note: 'NOTHING has changed yet (applied:false) — this is shown to the user as a confirm card.', - }; -} - -/** - * The applied envelope of the confirm replay. `others` is the pending drafts - * this change did not stage; `withCard: false` is an older cloud's drafted - * envelope (no `draftState`, `existingRows` or `appliedCard`). - */ -export function draftedEnvelope( - lang: Lang, - opts: { others?: number; withCard?: boolean; withDraftState?: boolean } = {}, -): Record { - const copy = COPY[lang]; - const others = opts.others ?? 0; - const withCard = opts.withCard ?? true; - const withDraftState = opts.withDraftState ?? true; - const ours = [{ type: 'object', name: BORROWING }]; - const theirs = Array.from({ length: others }, (_, i) => ({ type: 'view', name: `${BORROWING}.list_${i}` })); - const pending = ours.length + theirs.length; - return { - status: 'drafted', - kind: 'edit', - drafted: ours, - packageId: PACKAGE_ID, - summary: lang === 'zh' ? '已起草 2 处改动' : 'Drafted 2 edit(s)', - verification: { errors: 0, warnings: 0 }, - posture: { mode: 'draft', liveRecords: 12 }, - note: 'SAVED AS A STUDIO DRAFT — NOT LIVE.', - ...(withCard && withDraftState - ? { draftState: { pending, items: [...ours, ...theirs], others } } - : {}), - ...(withCard - ? { - existingRows: [{ object: BORROWING, field: 'renewal_count', label: copy.label, rows: 12 }], - appliedCard: { - title: copy.savedAsDraft(pending), - lines: [copy.existingRowsEmpty(12, copy.label), copy.checkedStructure], - }, - } - : {}), - }; -} diff --git a/ui/packages/plugin-chatbot/src/__tests__/mapMessages.buildCards-12724.test.ts b/ui/packages/plugin-chatbot/src/__tests__/mapMessages.buildCards-12724.test.ts deleted file mode 100644 index 4a1ccd9d9f2..00000000000 --- a/ui/packages/plugin-chatbot/src/__tests__/mapMessages.buildCards-12724.test.ts +++ /dev/null @@ -1,98 +0,0 @@ -/** - * ObjectUI - * Copyright (c) 2024-present ObjectStack Inc. - * - * objectui#12724, phase 2 — the lifts behind the build cards' v2 rows. Each - * reads one declared key of objectstack-ai/cloud's `build-cards.schema.json` - * (vendored as `fixtures/build-cards.schema.ts`) and keeps only what a card - * draws; a value that is not the declared shape lifts nothing, so the card - * keeps its earlier rows. - */ -import { describe, expect, it } from 'vitest'; -import { detectBuildChecklist, detectProposedPlan } from '../mapMessages'; -import { applyEnvelope, planEnvelope, verifyEnvelope } from './fixtures/buildCards.fixtures'; - -describe('detectProposedPlan lifts planCard and viewIntents (objectui#12724)', () => { - it('keeps the drawn keys of planCard and nothing else', () => { - const plan = detectProposedPlan(planEnvelope('zh'))!; - expect(plan.planCard!.objects[0]).toEqual({ - name: 'book', - label: '图书', - fields: [ - { name: 'title', label: '书名' }, - { name: 'author', label: '作者' }, - { name: 'isbn', label: 'ISBN', format: { label: '13 位数字' } }, - { name: 'copies', label: '馆藏数量' }, - { name: 'category', label: '分类', suggested: true }, - ], - nameField: { name: 'title', label: '书名' }, - }); - expect(plan.planCard!.objects[2].nameField).toBeUndefined(); - // A view keeps its name, object, label and line; layout, filters, sort and - // fields are the producer's, not drawn here. - expect(plan.planCard!.views[1]).toEqual({ - view: 'overdue_loans', - object: 'loan', - label: '逾期未还记录', - line: '列表 · 筛选 状态 = 逾期 且 归还日期 为空 · 按应还日期升序', - }); - expect(plan.planCard!.sampleData).toEqual({ line: '示例数据 12 条/对象' }); - }); - - it('reads the assumptions from planCard, and from the blueprint without one', () => { - expect(detectProposedPlan(planEnvelope('zh'))!.assumptions).toEqual(planEnvelope('zh').planCard.assumptions); - const { planCard: _c, ...older } = planEnvelope('zh'); - expect(detectProposedPlan(older)!.assumptions).toEqual(['blueprint assumption the plan card does not repeat']); - expect(detectProposedPlan(older)!.planCard).toBeUndefined(); - }); - - it('lifts viewIntents as sent', () => { - expect(detectProposedPlan(planEnvelope('zh'))!.viewIntents!.map((v) => v.view)).toEqual([ - 'loan_board', - 'overdue_loans', - 'all_books', - ]); - }); - - it('a planCard missing a required list is not a plan card', () => { - const plan = planEnvelope('zh'); - const { views: _v, ...noViews } = plan.planCard; - expect(detectProposedPlan({ ...plan, planCard: noViews })!.planCard).toBeUndefined(); - expect(detectProposedPlan({ ...plan, planCard: 'card' })!.planCard).toBeUndefined(); - }); -}); - -describe('detectBuildChecklist reads the result card`s checklist (objectui#12724)', () => { - it('on apply_blueprint`s drafted envelope', () => { - expect(detectBuildChecklist(applyEnvelope('zh'))).toEqual({ - status: 'passed', - passed: 7, - total: 7, - lines: [ - { kind: 'object', status: 'passed', line: '图书 · 5 个字段 · 12 条示例' }, - { kind: 'object', status: 'passed', line: '读者 · 3 个字段 · 12 条示例' }, - { kind: 'object', status: 'passed', line: '借阅记录 · 6 个字段 · 12 条示例' }, - { kind: 'view', status: 'passed', line: '借阅看板 · 按状态分组 · 5 / 4 / 3' }, - { kind: 'view', status: 'passed', line: '逾期未还记录 · 筛选生效 · 命中 3 条' }, - { kind: 'view', status: 'passed', line: '图书 · 显示全部记录 · 12 条' }, - { kind: 'sampleData', status: 'passed', line: '示例数据 · 无重复 · ISBN / 邮箱格式通过' }, - ], - app: { name: 'library_app', label: '图书借阅管理' }, - packageId: 'app.hcpl', - }); - }); - - it('on verify_build`s envelope, wrapped as the SDK delivers a text tool output', () => { - const wrapped = { type: 'text', value: JSON.stringify(verifyEnvelope('en', { failedView: true })) }; - const checklist = detectBuildChecklist(wrapped)!; - expect([checklist.status, checklist.passed, checklist.total]).toEqual(['failed', 6, 7]); - }); - - it('nothing without a checklist, or with one missing a required key', () => { - const { checklist, ...older } = applyEnvelope('zh'); - expect(detectBuildChecklist(older)).toBeUndefined(); - const { lines: _l, ...noLines } = checklist; - expect(detectBuildChecklist({ ...older, checklist: noLines })).toBeUndefined(); - expect(detectBuildChecklist({ ...older, checklist: { ...checklist, passed: -1 } })).toBeUndefined(); - }); -}); diff --git a/ui/packages/plugin-chatbot/src/__tests__/mapMessages.builtAppEditEnvelope-10109.test.ts b/ui/packages/plugin-chatbot/src/__tests__/mapMessages.builtAppEditEnvelope-10109.test.ts deleted file mode 100644 index 9270acb8533..00000000000 --- a/ui/packages/plugin-chatbot/src/__tests__/mapMessages.builtAppEditEnvelope-10109.test.ts +++ /dev/null @@ -1,142 +0,0 @@ -/** - * ObjectUI - * Copyright (c) 2024-present ObjectStack Inc. - * - * objectui#10109 — an INCREMENTAL edit is never read as a whole-app build. - * - * `apply_edit` now lists everything it staged in `drafted[]`, and an - * `add_object` op re-stages the `app` artifact (the nav merge). "Does - * `drafted[]` contain an `app` entry" was an exact whole-app test only while - * `apply_blueprint` was its sole producer. The producer declares the - * difference on the envelope — `kind: 'edit'` on `apply_edit`, no `kind` on - * `apply_blueprint` — and deliberately does NOT drop the `app` entry from - * `drafted[]`, which is the ground truth of the staged set. - * - * Two readers in this module answer "whole-app?": `detectBuiltAppPackage` - * reads the raw envelope, and `buildProgressFromDraftReview` reads the - * `DraftReview` that `detectDraftResult` lifts from it. So the draft review - * carries the producer's `kind` too, and both readers respect it. An - * envelope with no `kind` behaves exactly as before — the `apply_blueprint` - * controls below. - * - * The envelope shapes below are the producer's declaration as recorded on - * objectui#10109; the producer lives outside this repository. - */ -import { describe, it, expect } from 'vitest'; -import { - buildProgressFromDraftReview, - detectBuiltAppPackage, - detectDraftResult, - uiMessageToChatMessage, -} from '../mapMessages'; - -/** An `apply_edit` with an `add_object` op against an app that has a nav. */ -const editEnvelope = (status: 'drafted' | 'published') => ({ - status, - kind: 'edit', - packageId: 'app.k9', - drafted: [ - { type: 'object', name: 'k9_invoice' }, - { type: 'app', name: 'k9_app' }, - ], - changedArtifacts: [ - { type: 'object', name: 'k9_invoice' }, - { type: 'app', name: 'k9_app' }, - ], -}); - -/** The whole-app build: `apply_blueprint` carries no `kind`. */ -const blueprintEnvelope = (status: 'drafted' | 'published') => ({ - status, - packageId: 'app.k9', - drafted: [ - { type: 'app', name: 'k9_app' }, - { type: 'object', name: 'k9_task' }, - ], -}); - -/** The persisted form: the envelope rides a Vercel `{ type:'text', value }` wrapper. */ -const wrapped = (envelope: object) => ({ type: 'text', value: JSON.stringify(envelope) }); - -/** A reloaded assistant message whose only tool part carries `envelope` as its output. */ -const reloadedMessage = (toolName: string, envelope: object) => - uiMessageToChatMessage({ - id: 'm1', - role: 'assistant', - parts: [ - { - type: `tool-${toolName}`, - toolCallId: 't1', - state: 'output-available', - output: wrapped(envelope), - }, - ], - }); - -describe('detectBuiltAppPackage — an edit envelope is not a whole-app build (objectui#10109)', () => { - it.each(['drafted', 'published'] as const)( - 'an apply_edit that re-staged the app artifact (%s posture) is not a built app', - (status) => { - expect(detectBuiltAppPackage(editEnvelope(status))).toBeUndefined(); - expect(detectBuiltAppPackage(wrapped(editEnvelope(status)))).toBeUndefined(); - expect(detectBuiltAppPackage(JSON.stringify(editEnvelope(status)))).toBeUndefined(); - }, - ); - - it.each(['drafted', 'published'] as const)( - 'control: an apply_blueprint build (%s posture) is still a built app', - (status) => { - expect(detectBuiltAppPackage(blueprintEnvelope(status))).toBe('app.k9'); - expect(detectBuiltAppPackage(wrapped(blueprintEnvelope(status)))).toBe('app.k9'); - expect(detectBuiltAppPackage(JSON.stringify(blueprintEnvelope(status)))).toBe('app.k9'); - }, - ); -}); - -describe('detectDraftResult — the draft review carries the producer kind (objectui#10109)', () => { - it('the edit keeps its draft card, and its draft review says kind edit', () => { - expect(detectDraftResult(editEnvelope('drafted'))).toEqual({ - items: [ - { type: 'object', name: 'k9_invoice' }, - { type: 'app', name: 'k9_app' }, - ], - packageId: 'app.k9', - kind: 'edit', - }); - }); - - it('control: an apply_blueprint draft review carries no kind', () => { - expect(detectDraftResult(blueprintEnvelope('drafted'))).toEqual({ - items: [ - { type: 'app', name: 'k9_app' }, - { type: 'object', name: 'k9_task' }, - ], - packageId: 'app.k9', - }); - }); -}); - -describe('buildProgressFromDraftReview — a reloaded edit gets no build panel (objectui#10109)', () => { - it('a reloaded apply_edit that re-staged the app artifact synthesizes no done panel', () => { - expect(buildProgressFromDraftReview(detectDraftResult(editEnvelope('drafted')))).toBeUndefined(); - const reloaded = reloadedMessage('apply_edit', editEnvelope('drafted')); - // The draft card itself survives the reload; only the build panel is withheld. - expect(reloaded.toolInvocations?.[0]?.draftReview?.items).toHaveLength(2); - expect(reloaded.buildProgress).toBeUndefined(); - }); - - it('control: a reloaded apply_blueprint build still synthesizes its done panel', () => { - const expected = { - phase: 'done', - appLabel: 'K9 App', - items: [ - { type: 'app', name: 'k9_app' }, - { type: 'object', name: 'k9_task' }, - ], - done: 2, - total: 2, - }; - expect(buildProgressFromDraftReview(detectDraftResult(blueprintEnvelope('drafted')))).toEqual(expected); - expect(reloadedMessage('apply_blueprint', blueprintEnvelope('drafted')).buildProgress).toEqual(expected); - }); -}); diff --git a/ui/packages/plugin-chatbot/src/__tests__/mapMessages.changePosture-12894.test.ts b/ui/packages/plugin-chatbot/src/__tests__/mapMessages.changePosture-12894.test.ts deleted file mode 100644 index ca2f5aafdf5..00000000000 --- a/ui/packages/plugin-chatbot/src/__tests__/mapMessages.changePosture-12894.test.ts +++ /dev/null @@ -1,199 +0,0 @@ -/** - * ObjectUI - * Copyright (c) 2024-present ObjectStack Inc. - * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. - * - * objectui#12894 — the two mappers keep the keys cloud#2924 declares on the - * copilot's change envelopes, and only those: - * - * - `detectProposedChanges` keeps `posture` (`mode`, `liveRecords`, - * `platformPackage?`, `buildTurnRows?`) and `primaryAction` beside the - * `summary` and the rows (with their `details`) it kept before; - * - `detectReplayOutcome` keeps `draftState`, `existingRows` and - * `appliedCard` on a `drafted` replay. - * - * Each absent key degrades to the shape an older cloud produced, and a value - * that does not carry its declared required members is dropped whole rather - * than half-read. The envelopes are the producer's (`fixtures/changePosture.fixtures.ts`). - */ -import { describe, expect, it } from 'vitest'; -import { detectProposedChanges, detectReplayOutcome, uiMessageToChatMessage } from '../mapMessages'; -import { BORROWING, PACKAGE_ID, changeRows, draftedEnvelope, proposedEnvelope } from './fixtures/changePosture.fixtures'; - -/** The SDK's `{ type: 'text', value }` wrapper a real tool part carries. */ -const wrapped = (env: unknown) => ({ type: 'text', value: JSON.stringify(env) }); - -describe('objectui#12894 — detectProposedChanges keeps the posture and the primary action', () => { - it('a change to a live app with records: posture draft, save_draft, the ruled note, the rows with details', () => { - const out = detectProposedChanges(wrapped(proposedEnvelope('zh', 'draft'))); - expect(out).toEqual({ - summary: - '这个应用已上线,有 12 条记录在用。改动先存为草稿;画布和右侧属性里能看到效果,你在「变更」里核对后再发布。', - changes: changeRows('zh'), - posture: { mode: 'draft', liveRecords: 12 }, - primaryAction: 'save_draft', - }); - // The row's parameters ride `details` as the producer wrote them. - expect(out!.changes[0].details).toBe('续借次数 · 默认 0 · 不必填'); - }); - - it('a change that publishes: posture publish, confirm', () => { - const out = detectProposedChanges(proposedEnvelope('en', 'publish')); - expect(out?.posture).toEqual({ mode: 'publish', liveRecords: 0 }); - expect(out?.primaryAction).toBe('confirm'); - expect(out?.summary).toBe('Confirm this change before it is applied.'); - }); - - it('keeps the optional posture members the producer declares, and only when well-formed', () => { - const env = proposedEnvelope('en', 'publish'); - const withExtras = { - ...env, - posture: { mode: 'publish', liveRecords: 0, platformPackage: true, buildTurnRows: 24 }, - }; - expect(detectProposedChanges(withExtras)?.posture).toEqual({ - mode: 'publish', - liveRecords: 0, - platformPackage: true, - buildTurnRows: 24, - }); - const malformedExtras = { - ...env, - posture: { mode: 'publish', liveRecords: 0, platformPackage: 'yes', buildTurnRows: -1 }, - }; - expect(detectProposedChanges(malformedExtras)?.posture).toEqual({ mode: 'publish', liveRecords: 0 }); - }); - - it('an older cloud (no posture, no primaryAction) lifts exactly what it lifted before', () => { - const out = detectProposedChanges(proposedEnvelope('en', 'absent')); - expect(out).toEqual({ summary: 'Confirm this change before it is applied.', changes: changeRows('en') }); - expect(out).not.toHaveProperty('posture'); - expect(out).not.toHaveProperty('primaryAction'); - }); - - it('a posture without its declared required pair is not a posture; an undeclared action is not an action', () => { - const env = proposedEnvelope('zh', 'draft'); - for (const posture of [ - { mode: 'draft' }, - { liveRecords: 12 }, - { mode: 'live', liveRecords: 12 }, - { mode: 'draft', liveRecords: '12' }, - { mode: 'draft', liveRecords: 1.5 }, - 'draft', - null, - ]) { - expect(detectProposedChanges({ ...env, posture }), JSON.stringify(posture)).not.toHaveProperty('posture'); - } - for (const primaryAction of ['publish', 'SAVE_DRAFT', '', 1, true]) { - expect(detectProposedChanges({ ...env, primaryAction }), String(primaryAction)).not.toHaveProperty( - 'primaryAction', - ); - } - }); - - it('keeps no other envelope key: the model note and the applied flag stay behind', () => { - const out = detectProposedChanges(proposedEnvelope('zh', 'draft'))!; - expect(Object.keys(out).sort()).toEqual(['changes', 'posture', 'primaryAction', 'summary']); - }); -}); - -describe('objectui#12894 — detectReplayOutcome keeps the applied card of a change saved as a draft', () => { - it('a drafted replay: draftState, existingRows and appliedCard, beside the package', () => { - const out = detectReplayOutcome('replay_turn_0', wrapped(draftedEnvelope('zh', { others: 1 }))); - expect(out).toEqual({ - kind: 'drafted', - packageId: PACKAGE_ID, - // objectui#12968 — the items this replay drafted, for the card's Preview. - items: [{ type: 'object', name: BORROWING }], - draftState: { - pending: 2, - items: [ - { type: 'object', name: BORROWING }, - { type: 'view', name: `${BORROWING}.list_0` }, - ], - others: 1, - }, - existingRows: [{ object: BORROWING, field: 'renewal_count', label: '续借次数', rows: 12 }], - appliedCard: { title: '已存为草稿 · 2 项未发布', lines: ['已有 12 条记录的续借次数为空', '核对:结构 ✓'] }, - }); - }); - - it('an older cloud drafted replay lifts none of the cloud#2924 keys', () => { - const out = detectReplayOutcome('replay_turn_0', draftedEnvelope('en', { withCard: false })); - // `items` is objectui#12968's lift of `drafted[]`, which every cloud sends. - expect(out).toEqual({ kind: 'drafted', packageId: PACKAGE_ID, items: [{ type: 'object', name: BORROWING }] }); - }); - - it('each key degrades on its own: a card without a draft state keeps the card', () => { - const out = detectReplayOutcome('replay_turn_0', draftedEnvelope('en', { withDraftState: false })); - expect(out).toMatchObject({ kind: 'drafted', appliedCard: { title: 'Saved as a draft · 1 unpublished change(s)' } }); - expect(out).not.toHaveProperty('draftState'); - expect(out?.existingRows).toHaveLength(1); - }); - - it('a draft state without both counts, a card without a title, and malformed rows are dropped whole', () => { - const env = draftedEnvelope('zh', { others: 1 }); - const out = detectReplayOutcome('replay_turn_0', { - ...env, - draftState: { pending: 2, items: [] }, - appliedCard: { lines: ['已有 12 条记录的续借次数为空'] }, - existingRows: [{ object: BORROWING, field: 'renewal_count', rows: 12 }, 'x'], - }); - expect(out).toEqual({ kind: 'drafted', packageId: PACKAGE_ID, items: [{ type: 'object', name: BORROWING }] }); - }); - - it('a card keeps only its string lines; a draft state only its well-formed items', () => { - const env = draftedEnvelope('zh', { others: 0 }); - const out = detectReplayOutcome('replay_turn_0', { - ...env, - draftState: { pending: 1, items: [{ type: 'object', name: BORROWING }, { type: 'view' }, null], others: 0 }, - appliedCard: { title: '已存为草稿 · 1 项未发布', lines: ['核对:结构 ✓', '', 3, null] }, - }); - expect(out?.draftState).toEqual({ pending: 1, items: [{ type: 'object', name: BORROWING }], others: 0 }); - expect(out?.appliedCard).toEqual({ title: '已存为草稿 · 1 项未发布', lines: ['核对:结构 ✓'] }); - }); - - it('the applied card rides only a drafted outcome: a published or failed replay keeps its old shape', () => { - const env = draftedEnvelope('zh'); - expect(detectReplayOutcome('replay_turn_0', { ...env, status: 'published' })).toEqual({ kind: 'published' }); - expect( - detectReplayOutcome('replay_turn_0', { ...env, publishFailed: true, publishOutcome: 'rolled_back' }), - ).toEqual({ kind: 'failed', outcome: 'rolled_back', packageId: PACKAGE_ID }); - }); - - it('a non-replay tool call is not a replay outcome, whatever it carries', () => { - expect(detectReplayOutcome('call_1', draftedEnvelope('zh'))).toBeUndefined(); - }); -}); - -describe('objectui#12894 — the live mapper carries both lifts onto the invocation', () => { - it('a raw proposal part and its replay part map to proposedChanges and replayOutcome', () => { - const msg = uiMessageToChatMessage({ - id: 'm1', - role: 'assistant', - parts: [ - { - type: 'tool-apply_edit', - toolCallId: 'call_1', - state: 'output-available', - input: {}, - output: wrapped(proposedEnvelope('zh', 'draft')), - }, - { - type: 'tool-apply_edit', - toolCallId: 'replay_turn_0', - state: 'output-available', - input: {}, - output: wrapped(draftedEnvelope('zh')), - }, - ], - }); - const [proposal, replay] = msg.toolInvocations ?? []; - expect(proposal.proposedChanges?.primaryAction).toBe('save_draft'); - expect(proposal.proposedChanges?.posture).toEqual({ mode: 'draft', liveRecords: 12 }); - expect(replay.replayOutcome?.appliedCard?.title).toBe('已存为草稿 · 1 项未发布'); - // A matched replay never doubles as an ordinary draft card. - expect(replay.draftReview).toBeUndefined(); - }); -}); diff --git a/ui/packages/plugin-chatbot/src/__tests__/mapMessages.iterateOrNew-27480.test.ts b/ui/packages/plugin-chatbot/src/__tests__/mapMessages.iterateOrNew-27480.test.ts deleted file mode 100644 index abbcc90941e..00000000000 --- a/ui/packages/plugin-chatbot/src/__tests__/mapMessages.iterateOrNew-27480.test.ts +++ /dev/null @@ -1,98 +0,0 @@ -/** - * ObjectUI - * Copyright (c) 2024-present ObjectStack Inc. - * - * objectstack#27480 — a `propose_blueprint` result whose `decision` is - * `iterate_or_new` overlaps an app the user already has. It is lifted as a - * plan that carries the extend-or-new QUESTION (`ProposedPlan.iterateOrNew`), - * so the card can ask instead of offering "Build it". The overlapping app is - * read from `existingAppOverlap`'s own `name` / `label`. - * - * The plain proposal is the control: it lifts exactly what it did before, with - * no `iterateOrNew` key at all. - */ -import { describe, it, expect } from 'vitest'; -import { detectProposedPlan, uiMessageToChatMessage } from '../mapMessages'; - -const blueprint = { - app: { name: 'library_v2', label: '图书馆 2' }, - objects: [{ name: 'book', label: '图书', fields: [{ name: 'title' }, { name: 'isbn' }] }], -}; - -const iterateOrNew = { - status: 'blueprint_proposed', - decision: 'iterate_or_new', - existingAppOverlap: { name: 'library', label: '图书馆' }, - blueprint, - counts: { objects: 1, views: 0, dashboards: 0, seedData: 0 }, - questions: [], -}; - -const plain = { - status: 'blueprint_proposed', - blueprint, - counts: { objects: 1, views: 0, dashboards: 0, seedData: 0 }, - questions: [], -}; - -describe('detectProposedPlan — the iterate_or_new question (objectstack#27480)', () => { - it('lifts the overlapping app by name and label', () => { - const plan = detectProposedPlan(iterateOrNew); - expect(plan?.iterateOrNew).toEqual({ app: { name: 'library', label: '图书馆' } }); - // The plan's own rows still lift: the card draws them above the question. - expect(plan?.objects).toEqual([ - { name: 'book', label: '图书', fieldCount: 2, fields: [{ name: 'title' }, { name: 'isbn' }] }, - ]); - }); - - it('peels the persisted text wrapper like every other envelope', () => { - const plan = detectProposedPlan({ type: 'text', value: JSON.stringify(iterateOrNew) }); - expect(plan?.iterateOrNew).toEqual({ app: { name: 'library', label: '图书馆' } }); - }); - - it('a plain proposal is unchanged: no iterateOrNew key', () => { - const plan = detectProposedPlan(plain); - expect(plan).toBeDefined(); - expect(plan && 'iterateOrNew' in plan).toBe(false); - }); - - it('a decision other than iterate_or_new lifts nothing', () => { - const plan = detectProposedPlan({ ...plain, decision: 'new' }); - expect(plan && 'iterateOrNew' in plan).toBe(false); - }); - - it('is still a question when the envelope names no object', () => { - // Without this the detector answers undefined, and the chat draws the - // FALLBACK card for an unparsed proposal — which has a "Build it" button. - const plan = detectProposedPlan({ ...iterateOrNew, blueprint: { objects: [] } }); - expect(plan?.iterateOrNew).toEqual({ app: { name: 'library', label: '图书馆' } }); - expect(plan?.objects).toEqual([]); - }); - - it('keeps the label optional, and leaves app absent when the overlap names no app', () => { - expect( - detectProposedPlan({ ...iterateOrNew, existingAppOverlap: { name: 'library' } })?.iterateOrNew, - ).toEqual({ app: { name: 'library' } }); - expect(detectProposedPlan({ ...iterateOrNew, existingAppOverlap: { label: '图书馆' } })?.iterateOrNew).toEqual({}); - expect(detectProposedPlan({ ...iterateOrNew, existingAppOverlap: undefined })?.iterateOrNew).toEqual({}); - }); - - it('reaches the tool invocation through the live mapper', () => { - const msg = uiMessageToChatMessage({ - id: 'a1', - role: 'assistant', - parts: [ - { - type: 'tool-propose_blueprint', - toolCallId: 't1', - state: 'output-available', - input: {}, - output: iterateOrNew, - }, - ], - }); - expect(msg.toolInvocations?.[0]?.proposedPlan?.iterateOrNew).toEqual({ - app: { name: 'library', label: '图书馆' }, - }); - }); -}); diff --git a/ui/packages/plugin-chatbot/src/__tests__/mapMessages.planCardGeneratedName-13004.test.ts b/ui/packages/plugin-chatbot/src/__tests__/mapMessages.planCardGeneratedName-13004.test.ts deleted file mode 100644 index af2d439d0f7..00000000000 --- a/ui/packages/plugin-chatbot/src/__tests__/mapMessages.planCardGeneratedName-13004.test.ts +++ /dev/null @@ -1,49 +0,0 @@ -/** - * ObjectUI - * Copyright (c) 2024-present ObjectStack Inc. - * - * objectui#13004 — `liftPlanCard` lifts an object's `nameField.generated` as the - * line the card draws (`{ line }`) when it is a well-formed object with a string - * line, and drops a malformed one like any other undeclared value. - */ -import { describe, expect, it } from 'vitest'; -import { detectProposedPlan } from '../mapMessages'; -import { planEnvelope } from './fixtures/buildCards.fixtures'; - -/** The generated-title plan envelope with the loan's `nameField.generated` replaced by `value`. */ -function withGenerated(value: unknown) { - const plan = planEnvelope('zh', { generatedTitle: true }); - const objects = plan.planCard.objects.map((o) => - o.name === 'loan' ? { ...o, nameField: { name: 'title', label: '借阅标题', generated: value } } : o, - ); - return { ...plan, planCard: { ...plan.planCard, objects } }; -} - -const loanNameOf = (envelope: unknown) => detectProposedPlan(envelope)!.planCard!.objects[2].nameField; - -describe('liftPlanCard lifts a name field`s generated line (objectui#13004)', () => { - it('lifts the line the card draws, and not the producer`s template', () => { - expect(loanNameOf(planEnvelope('zh', { generatedTitle: true }))).toEqual({ - name: 'title', - label: '借阅标题', - generated: { line: '名称:自动生成「{图书} · {读者} · {借出日期}」,表单里不出现' }, - }); - }); - - it('a name field without the key lifts none', () => { - const objects = detectProposedPlan(planEnvelope('zh', { generatedTitle: true }))!.planCard!.objects; - expect(objects[0].nameField).toEqual({ name: 'title', label: '书名' }); - expect(objects[1].nameField).toEqual({ name: 'full_name', label: '姓名' }); - }); - - it.each([ - ['a string', '名称:自动生成'], - ['an array', [{ line: '名称:自动生成' }]], - ['null', null], - ['an object without a line', { template: '{图书}' }], - ['an object with an empty line', { template: '{图书}', line: '' }], - ['an object with a non-string line', { template: '{图书}', line: 3 }], - ])('drops %s without throwing', (_what, value) => { - expect(loanNameOf(withGenerated(value))).toEqual({ name: 'title', label: '借阅标题' }); - }); -}); diff --git a/ui/packages/plugin-chatbot/src/__tests__/mapMessages.planCardLifecycle-12994.test.ts b/ui/packages/plugin-chatbot/src/__tests__/mapMessages.planCardLifecycle-12994.test.ts deleted file mode 100644 index 9f412caf502..00000000000 --- a/ui/packages/plugin-chatbot/src/__tests__/mapMessages.planCardLifecycle-12994.test.ts +++ /dev/null @@ -1,47 +0,0 @@ -/** - * ObjectUI - * Copyright (c) 2024-present ObjectStack Inc. - * - * objectui#12994 — `liftPlanCard` lifts a field chip's `lifecycle` (the words - * the chip draws, `lifecycle.label`) when it is a well-formed object with a - * string label, and drops a malformed one like any other undeclared value. - */ -import { describe, expect, it } from 'vitest'; -import { detectProposedPlan } from '../mapMessages'; -import { planEnvelope } from './fixtures/buildCards.fixtures'; - -/** The plan envelope with the loan `status` field's `lifecycle` replaced by `value`. */ -function withLifecycle(value: unknown) { - const plan = planEnvelope('zh'); - const loan = plan.planCard.objects[2]; - const fields = loan.fields.map((f) => (f.name === 'status' ? { ...f, lifecycle: value } : f)); - return { ...plan, planCard: { ...plan.planCard, objects: [...plan.planCard.objects.slice(0, 2), { ...loan, fields }] } }; -} - -const statusOf = (envelope: unknown) => detectProposedPlan(envelope)!.planCard!.objects[2].fields[5]; - -describe('liftPlanCard lifts a field`s lifecycle (objectui#12994)', () => { - it('lifts the label the chip draws, and not the producer`s options', () => { - expect(statusOf(planEnvelope('zh'))).toEqual({ - name: 'status', - label: '状态', - lifecycle: { label: '借出 · 已还 ✓完成 · 逾期 ⚠' }, - }); - }); - - it('a field without the key lifts none', () => { - const fields = detectProposedPlan(planEnvelope('zh'))!.planCard!.objects[2].fields; - expect(fields.slice(0, 5).every((f) => !('lifecycle' in f))).toBe(true); - }); - - it.each([ - ['a string', '借出 · 已还'], - ['an array', [{ label: '借出' }]], - ['null', null], - ['an object without a label', { options: [] }], - ['an object with an empty label', { options: [], label: '' }], - ['an object with a non-string label', { options: [], label: 3 }], - ])('drops %s without throwing', (_what, value) => { - expect(statusOf(withLifecycle(value))).toEqual({ name: 'status', label: '状态' }); - }); -}); diff --git a/ui/packages/plugin-chatbot/src/__tests__/mapMessages.replayOutcome.test.ts b/ui/packages/plugin-chatbot/src/__tests__/mapMessages.replayOutcome.test.ts deleted file mode 100644 index 7d5784f9b18..00000000000 --- a/ui/packages/plugin-chatbot/src/__tests__/mapMessages.replayOutcome.test.ts +++ /dev/null @@ -1,161 +0,0 @@ -/** - * ObjectUI - * Copyright (c) 2024-present ObjectStack Inc. - * - * objectui#5695 — `detectReplayOutcome` and its suppression contract. - * - * The replay envelope is the ordinary authoring envelope under a synthetic - * `replay__` toolCallId (cloud `runApprovedProposalReplay`); the - * failure stamp is cloud#1467's `publishFailed:true` + `publishOutcome` + - * `publishError` over `status:'drafted'`. The dangerous shape is the failed - * one: before this detector, `detectDraftResult` matched it and the chat - * rendered a rolled-back publish as an ordinary successful draft card with a - * live Publish button. - */ -import { describe, it, expect } from 'vitest'; -import { detectReplayOutcome, detectAuthoringVerdict, uiMessagesToChatMessages } from '../mapMessages'; - -const FAILED = JSON.stringify({ - status: 'drafted', - drafted: [{ type: 'view', name: 'k9qk_task.board' }], - packageId: 'app.k9qk', - publishFailed: true, - publishOutcome: 'rolled_back', - publishError: 'publish gate: dangling view reference\nsecond line of detail', -}); - -describe('detectReplayOutcome (objectui#5695)', () => { - it('lifts a published replay', () => { - expect(detectReplayOutcome('replay_t1_0', JSON.stringify({ status: 'published' }))).toEqual({ - kind: 'published', - }); - }); - - it('lifts a drafted replay with its packageId for the inline publish affordance', () => { - expect( - detectReplayOutcome( - 'replay_t1_0', - JSON.stringify({ status: 'drafted', drafted: [{ type: 'view', name: 'v' }], packageId: 'app.k9qk' }), - ), - ).toEqual({ kind: 'drafted', packageId: 'app.k9qk', items: [{ type: 'view', name: 'v' }] }); - }); - - it('lifts a failed publish with the machine verdict and the FIRST line of publishError', () => { - expect(detectReplayOutcome('replay_t1_0', FAILED)).toEqual({ - kind: 'failed', - outcome: 'rolled_back', - error: 'publish gate: dangling view reference', - packageId: 'app.k9qk', - }); - }); - - it('ignores the same envelope under a NON-replay toolCallId — ordinary tool results keep their cards', () => { - expect(detectReplayOutcome('call_abc', FAILED)).toBeUndefined(); - expect(detectReplayOutcome(undefined, FAILED)).toBeUndefined(); - }); - - it('ignores replay results that are not authoring envelopes', () => { - expect(detectReplayOutcome('replay_t1_0', JSON.stringify({ status: 'ok' }))).toBeUndefined(); - expect(detectReplayOutcome('replay_t1_0', 'plain text')).toBeUndefined(); - }); -}); - -describe('replay suppression in the live mapper (objectui#5695)', () => { - it('a failed replay carries replayOutcome and NO draftReview — never a live Publish button over a rollback', () => { - const [msg] = uiMessagesToChatMessages([ - { - id: 'm1', - role: 'assistant', - parts: [ - { - type: 'tool-update_metadata', - toolCallId: 'replay_t1_0', - state: 'output-available', - output: FAILED, - }, - ], - }, - ] as never); - const tool = msg.toolInvocations?.[0]; - expect(tool?.replayOutcome?.kind).toBe('failed'); - expect(tool?.draftReview).toBeUndefined(); - }); - - it('the same drafted envelope under an ordinary id still produces the draft card', () => { - const [msg] = uiMessagesToChatMessages([ - { - id: 'm1', - role: 'assistant', - parts: [ - { - type: 'tool-update_metadata', - toolCallId: 'call_1', - state: 'output-available', - output: JSON.stringify({ - status: 'drafted', - drafted: [{ type: 'view', name: 'v' }], - packageId: 'app.k9qk', - }), - }, - ], - }, - ] as never); - const tool = msg.toolInvocations?.[0]; - expect(tool?.draftReview?.items).toEqual([{ type: 'view', name: 'v' }]); - expect(tool?.replayOutcome).toBeUndefined(); - }); -}); - -describe('replay dispatch errors + authoring verdicts (objectui#5695 follow-up, measured live 2026-08-24)', () => { - it('a bare {error} replay result is a provisional dispatch failure', () => { - expect( - detectReplayOutcome( - 'replay_t1_0', - JSON.stringify({ error: 'apply_edit op #1 (add_field): object "task" not found.\nmore' }), - ), - ).toEqual({ - kind: 'failed', - dispatchError: true, - error: 'apply_edit op #1 (add_field): object "task" not found.', - }); - }); - - it('an {error} beside a status keeps status semantics (not a dispatch error)', () => { - expect( - detectReplayOutcome('replay_t1_0', JSON.stringify({ status: 'published', error: 'noise' })), - ).toEqual({ kind: 'published' }); - }); - - it('detectAuthoringVerdict classifies arbitrary tool results for the self-repair supersede', () => { - expect(detectAuthoringVerdict(JSON.stringify({ status: 'published' }))).toEqual({ kind: 'published' }); - expect( - detectAuthoringVerdict(JSON.stringify({ status: 'drafted', packageId: 'app.x' })), - ).toEqual({ kind: 'drafted', packageId: 'app.x' }); - expect( - detectAuthoringVerdict(JSON.stringify({ status: 'drafted', publishFailed: true })), - ).toEqual({ kind: 'failed' }); - expect(detectAuthoringVerdict(JSON.stringify({ error: 'x' }))).toBeUndefined(); - expect(detectAuthoringVerdict('plain')).toBeUndefined(); - }); -}); - -describe('the persisted text-wrapper shape (rehydration path)', () => { - it('a dispatch error inside the Vercel {type:"text",value} wrapper is still detected', () => { - expect( - detectReplayOutcome('replay_t1_0', { - type: 'text', - value: JSON.stringify({ error: 'apply_edit op #1 (add_field): object "task" not found.' }), - }), - ).toEqual({ - kind: 'failed', - dispatchError: true, - error: 'apply_edit op #1 (add_field): object "task" not found.', - }); - }); - - it('an authoring verdict inside the wrapper is still classified', () => { - expect( - detectAuthoringVerdict({ type: 'text', value: JSON.stringify({ status: 'published' }) }), - ).toEqual({ kind: 'published' }); - }); -}); diff --git a/ui/packages/plugin-chatbot/src/__tests__/mapMessages.test.ts b/ui/packages/plugin-chatbot/src/__tests__/mapMessages.test.ts index c885322391f..c2eb7593fda 100644 --- a/ui/packages/plugin-chatbot/src/__tests__/mapMessages.test.ts +++ b/ui/packages/plugin-chatbot/src/__tests__/mapMessages.test.ts @@ -11,11 +11,6 @@ import type { UIMessage } from '@ai-sdk/react'; import { uiMessageToChatMessage, uiMessagesToChatMessages, - detectDraftResult, - detectProposedPlan, - detectBuilderHandoff, - buildProgressFromDraftReview, - supersededPlanIds, } from '../mapMessages'; describe('uiMessageToChatMessage', () => { @@ -168,163 +163,6 @@ describe('uiMessageToChatMessage', () => { expect(out.streaming).toBe(true); }); - it('lifts a reconciled data-build-progress part into buildProgress', () => { - const out = uiMessageToChatMessage({ - id: 'm6', - role: 'assistant', - parts: [ - { - type: 'data-build-progress', - id: 'build-progress', - data: { - phase: 'data', - appLabel: 'CRM', - items: [{ type: 'object', name: 'customer' }, { type: 'view', name: 'customer.list' }], - done: 2, - total: 6, - }, - }, - ], - }); - expect(out.buildProgress).toEqual({ - phase: 'data', - appLabel: 'CRM', - items: [{ type: 'object', name: 'customer' }, { type: 'view', name: 'customer.list' }], - done: 2, - total: 6, - }); - }); - - it('leaves buildProgress undefined when there is no build-progress part', () => { - const out = uiMessageToChatMessage({ id: 'm7', role: 'assistant', parts: [{ type: 'text', text: 'hi' }] }); - expect(out.buildProgress).toBeUndefined(); - }); - - it('lifts a reconciled data-blueprint-progress part into blueprintProgress', () => { - const out = uiMessageToChatMessage({ - id: 'mbp1', - role: 'assistant', - parts: [ - { - type: 'data-blueprint-progress', - id: 'blueprint-progress', - data: { - phase: 'designing', - summary: '招聘管理系统', - appLabel: '招聘管理', - objects: [ - { name: 'candidate', label: '候选人', fields: 5 }, - { name: 'job', label: '职位', fields: 4 }, - ], - counts: { objects: 2, views: 2, dashboards: 1 }, - seq: 7, - }, - }, - ], - }); - expect(out.blueprintProgress).toEqual({ - phase: 'designing', - summary: '招聘管理系统', - appLabel: '招聘管理', - objects: [ - { name: 'candidate', label: '候选人', fields: 5 }, - { name: 'job', label: '职位', fields: 4 }, - ], - counts: { objects: 2, views: 2, dashboards: 1 }, - seq: 7, - }); - }); - - it('reconciles to the latest data-blueprint-progress frame (objects appear one by one)', () => { - // The SDK keeps a single reconciled part per stable id; given two frames we - // take the most recent — the one with more objects revealed + higher seq. - const out = uiMessageToChatMessage({ - id: 'mbp2', - role: 'assistant', - parts: [ - { - type: 'data-blueprint-progress', - id: 'blueprint-progress', - data: { phase: 'designing', objects: [{ name: 'candidate' }], seq: 1 }, - }, - { - type: 'data-blueprint-progress', - id: 'blueprint-progress', - data: { - phase: 'designing', - objects: [{ name: 'candidate' }, { name: 'job' }], - seq: 2, - }, - }, - ], - }); - expect(out.blueprintProgress?.objects).toHaveLength(2); - expect(out.blueprintProgress?.seq).toBe(2); - }); - - it('maps phase:done with the extend target and drops malformed objects/fields', () => { - const out = uiMessageToChatMessage({ - id: 'mbp3', - role: 'assistant', - parts: [ - { - type: 'data-blueprint-progress', - id: 'blueprint-progress', - data: { - phase: 'done', - targetApp: 'recruiting', - objects: [ - { name: 'candidate' }, - { label: 'no name — dropped' }, - { name: 'job', fields: 'not-a-number' }, - ], - }, - }, - ], - }); - expect(out.blueprintProgress?.phase).toBe('done'); - expect(out.blueprintProgress?.targetApp).toBe('recruiting'); - // Nameless object dropped; non-numeric `fields` omitted (chip shows no "· N"). - expect(out.blueprintProgress?.objects).toEqual([{ name: 'candidate' }, { name: 'job' }]); - }); - - it('defaults an unknown/absent phase to designing and tolerates a missing objects array', () => { - const out = uiMessageToChatMessage({ - id: 'mbp4', - role: 'assistant', - parts: [ - { type: 'data-blueprint-progress', id: 'blueprint-progress', data: { summary: 'CRM' } }, - ], - }); - expect(out.blueprintProgress?.phase).toBe('designing'); - expect(out.blueprintProgress?.objects).toEqual([]); - expect(out.blueprintProgress?.summary).toBe('CRM'); - }); - - it('drops counts entirely when none of its numeric fields are present', () => { - const out = uiMessageToChatMessage({ - id: 'mbp5', - role: 'assistant', - parts: [ - { - type: 'data-blueprint-progress', - id: 'blueprint-progress', - data: { phase: 'designing', objects: [], counts: { objects: 'x' } }, - }, - ], - }); - expect(out.blueprintProgress?.counts).toBeUndefined(); - }); - - it('leaves blueprintProgress undefined when there is no blueprint-progress part', () => { - const out = uiMessageToChatMessage({ - id: 'mbp6', - role: 'assistant', - parts: [{ type: 'text', text: 'hi' }], - }); - expect(out.blueprintProgress).toBeUndefined(); - }); - it('lifts data-chart parts into charts[] (visualize_data)', () => { const out = uiMessageToChatMessage({ id: 'm8', @@ -384,326 +222,6 @@ describe('uiMessageToChatMessage', () => { }); }); -// ADR-0033 Phase B — the chat lifts draft envelopes onto the invocation so a -// "Review N change(s)" affordance can open the designer's review/diff. -describe('draftReview detection (ADR-0033)', () => { - const toolPart = (output: unknown) => ({ - type: 'tool-create_metadata', - toolCallId: 'd1', - state: 'output-available' as const, - input: {}, - output, - }); - const draftReviewOf = (output: unknown) => - uiMessageToChatMessage({ id: 'm', role: 'assistant', parts: [toolPart(output)] }) - .toolInvocations?.[0]?.draftReview; - - it('lifts a single drafted item ({status:drafted, type, name})', () => { - const dr = draftReviewOf({ status: 'drafted', type: 'object', name: 'project', summary: 'Drafted new object "project"' }); - expect(dr).toEqual({ items: [{ type: 'object', name: 'project' }], summary: 'Drafted new object "project"' }); - }); - - it('lifts a batch from apply_blueprint ({status:drafted, drafted:[…]})', () => { - const dr = draftReviewOf({ - status: 'drafted', - drafted: [ - { type: 'object', name: 'project' }, - { type: 'view', name: 'open_tasks' }, - ], - failed: [], - summary: 'drafted 2 artifact(s)', - }); - expect(dr?.items).toEqual([ - { type: 'object', name: 'project' }, - { type: 'view', name: 'open_tasks' }, - ]); - }); - - it('parses the Vercel `{ type:text, value }` wrapper (stringified JSON)', () => { - const dr = draftReviewOf({ type: 'text', value: JSON.stringify({ status: 'drafted', type: 'view', name: 'grid_v' }) }); - expect(dr?.items).toEqual([{ type: 'view', name: 'grid_v' }]); - }); - - it('lifts apply_blueprint nextSteps for the getting-started checklist (drops blanks)', () => { - const dr = draftReviewOf({ - status: 'drafted', - drafted: [{ type: 'app', name: 'recruiting' }], - summary: 'built 13 artifact(s)', - nextSteps: ['Make the data yours', '', ' ', 'Publish from the status panel'], - }); - expect(dr?.nextSteps).toEqual(['Make the data yours', 'Publish from the status panel']); - }); - - it('omits nextSteps when absent or not a string array', () => { - expect(draftReviewOf({ status: 'drafted', type: 'object', name: 'x' })?.nextSteps).toBeUndefined(); - expect(draftReviewOf({ status: 'drafted', type: 'object', name: 'x', nextSteps: 'nope' })?.nextSteps).toBeUndefined(); - }); - - it('does NOT surface blueprint_proposed (no draft yet) or plain results', () => { - expect(draftReviewOf({ status: 'blueprint_proposed', counts: { objects: 3 } })).toBeUndefined(); - expect(draftReviewOf({ users: [] })).toBeUndefined(); - expect(draftReviewOf({ status: 'drafted' })).toBeUndefined(); // no type/name → no target - }); - - it('lifts ADR-0038 lint issues (message + fix) alongside the verification counts', () => { - const dr = draftReviewOf({ - status: 'drafted', - type: 'object', - name: 'book', - summary: 'Drafted new object "book"', - verification: { errors: 1, warnings: 1 }, - issues: [ - { - layer: 'graph', - severity: 'error', - artifact: { type: 'object', name: 'book' }, - code: 'select_without_options', - message: 'genre is a required select with no options', - fix: 'Add an options array.', - }, - { severity: 'warning', code: 'unknown_column', message: 'author renders empty' }, - { code: 'no_message_dropped' }, // malformed → must be dropped - ], - }); - expect(dr?.verification).toEqual({ errors: 1, warnings: 1 }); - expect(dr?.issues).toEqual([ - { - severity: 'error', - code: 'select_without_options', - message: 'genre is a required select with no options', - fix: 'Add an options array.', - }, - { severity: 'warning', code: 'unknown_column', message: 'author renders empty' }, - ]); - }); - - it('omits the issues key entirely when there are none (no envelope churn)', () => { - const dr = draftReviewOf({ status: 'drafted', type: 'view', name: 'grid_v' }); - expect(dr).toEqual({ items: [{ type: 'view', name: 'grid_v' }] }); - }); -}); - -// propose_blueprint returns a PLAN before anything is staged. The chat surfaces -// it as a reviewable "Proposed plan" card (the confirm gate), so detection must -// lift the objects, counts, assumptions, and structure-deciding questions. -describe('proposedPlan detection (propose_blueprint)', () => { - const fullEnvelope = { - status: 'blueprint_proposed', - summary: 'A lightweight applicant tracker', - counts: { objects: 2, views: 3, dashboards: 1, seedData: 2 }, - questions: ['Track interviews as a separate object, or as a stage field?'], - blueprint: { - summary: 'A lightweight applicant tracker', - assumptions: ['One pipeline for all roles', 'No external job-board sync'], - objects: [ - { name: 'candidate', label: 'Candidate', fields: [{ name: 'full_name' }, { name: 'stage' }] }, - { name: 'job', label: 'Job', fields: [{ name: 'title' }] }, - ], - views: [{ name: 'pipeline' }, { name: 'all' }, { name: 'archived' }], - questions: ['ignored — envelope questions win'], - }, - }; - - it('lifts the plan shape (objects, counts, assumptions, questions) from the envelope', () => { - const plan = detectProposedPlan(fullEnvelope); - expect(plan).toEqual({ - summary: 'A lightweight applicant tracker', - objects: [ - { - name: 'candidate', - label: 'Candidate', - fieldCount: 2, - fields: [{ name: 'full_name' }, { name: 'stage' }], - }, - { name: 'job', label: 'Job', fieldCount: 1, fields: [{ name: 'title' }] }, - ], - views: [{ name: 'pipeline' }, { name: 'all' }, { name: 'archived' }], - counts: { objects: 2, views: 3, dashboards: 1, seedData: 2 }, - questions: ['Track interviews as a separate object, or as a stage field?'], - assumptions: ['One pipeline for all roles', 'No external job-board sync'], - }); - }); - - it('parses a JSON-string result (what the tool actually returns) and wires onto the tool invocation', () => { - const msg = uiMessageToChatMessage({ - id: 'm', - role: 'assistant', - parts: [ - { - type: 'tool-propose_blueprint', - toolCallId: 'p1', - state: 'output-available' as const, - input: {}, - output: JSON.stringify(fullEnvelope), - }, - ], - }); - expect(msg.toolInvocations?.[0]?.proposedPlan?.objects).toEqual([ - { - name: 'candidate', - label: 'Candidate', - fieldCount: 2, - fields: [{ name: 'full_name' }, { name: 'stage' }], - }, - { name: 'job', label: 'Job', fieldCount: 1, fields: [{ name: 'title' }] }, - ]); - }); - - it('derives counts from the blueprint when the envelope omits them, and drops malformed objects', () => { - const plan = detectProposedPlan({ - status: 'blueprint_proposed', - blueprint: { - objects: [ - { name: 'task', fields: [{ name: 'title' }] }, - { label: 'no name → dropped' }, - { name: 'note' }, // no fields → fieldCount 0 - ], - views: [{ name: 'board' }], - }, - }); - expect(plan?.objects).toEqual([ - { name: 'task', fieldCount: 1, fields: [{ name: 'title' }] }, - { name: 'note', fieldCount: 0 }, - ]); - expect(plan?.counts).toEqual({ objects: 2, views: 1, dashboards: 0, seedData: 0 }); - expect(plan?.questions).toEqual([]); - expect(plan?.assumptions).toEqual([]); - }); - - // objectui#12724 — the plan card v2 rows, from what the spec's - // `SolutionBlueprintSchema` declares and nothing else: each field's and - // view's `name` + `label`, and `app.label`. - it('lifts field and view names + labels and the app label (objectui#12724)', () => { - const plan = detectProposedPlan({ - status: 'blueprint_proposed', - blueprint: { - app: { name: 'library_app', label: '图书借阅管理' }, - objects: [ - { - name: 'book', - label: '图书', - fields: [ - { name: 'title', label: '书名', type: 'text' }, - { name: 'isbn', type: 'text' }, - { label: 'no name → dropped' }, - null, - ], - }, - ], - views: [{ name: 'loan_board', label: '借阅看板', type: 'kanban', groupBy: 'status' }, { type: 'list' }], - }, - }); - expect(plan?.appLabel).toBe('图书借阅管理'); - expect(plan?.objects[0]).toEqual({ - name: 'book', - label: '图书', - fieldCount: 4, - fields: [{ name: 'title', label: '书名' }, { name: 'isbn' }], - }); - expect(plan?.views).toEqual([{ name: 'loan_board', label: '借阅看板' }]); - }); - - it('a count-only fields array (the cache-fallback copy) lifts no field rows (objectui#12724)', () => { - const plan = detectProposedPlan({ - status: 'blueprint_proposed', - blueprint: { objects: [{ name: 'book', fields: [null, null, null] }] }, - }); - expect(plan?.objects).toEqual([{ name: 'book', fieldCount: 3 }]); - expect(plan?.views).toBeUndefined(); - expect(plan?.appLabel).toBeUndefined(); - }); - - it('surfaces the extend-mode targetApp', () => { - const plan = detectProposedPlan({ - status: 'blueprint_proposed', - targetApp: 'recruiting', - blueprint: { objects: [{ name: 'offer', fields: [] }] }, - }); - expect(plan?.targetApp).toBe('recruiting'); - }); - - it('returns undefined for non-proposal statuses and proposals with no nameable objects', () => { - expect(detectProposedPlan({ status: 'drafted', type: 'object', name: 'x' })).toBeUndefined(); - expect(detectProposedPlan({ status: 'blueprint_proposed', blueprint: { objects: [] } })).toBeUndefined(); - expect(detectProposedPlan({ status: 'blueprint_proposed' })).toBeUndefined(); - expect(detectProposedPlan({ foo: 1 })).toBeUndefined(); - }); - - it('lifts well-formed questionChoices and drops malformed / <2-option ones', () => { - const plan = detectProposedPlan({ - status: 'blueprint_proposed', - blueprint: { objects: [{ name: 'book', fields: [] }] }, - questions: ['Track loans separately?', 'Star ratings or 1-10?'], - questionChoices: [ - { text: 'Track loans separately?', options: ['Separate object', 'Status field'] }, - { text: 'Star ratings or 1-10?', options: ['only one'] }, // <2 → dropped - { text: '', options: ['a', 'b'] }, // no text → dropped - { options: ['a', 'b'] }, // no text → dropped - ], - }); - expect(plan?.questionChoices).toEqual([ - { text: 'Track loans separately?', options: ['Separate object', 'Status field'] }, - ]); - }); - - it('omits questionChoices entirely when absent or not an array', () => { - const plan = detectProposedPlan({ - status: 'blueprint_proposed', - blueprint: { objects: [{ name: 'book', fields: [] }] }, - questions: ['Q?'], - }); - expect(plan?.questionChoices).toBeUndefined(); - }); -}); - -describe('builderHandoff detection (ADR-0057 P4 — suggest_builder)', () => { - it('lifts the { status:build_handoff, prompt, packageId } envelope', () => { - const h = detectBuilderHandoff({ - status: 'build_handoff', - handoff: 'build', - prompt: 'Add a priority field to tasks', - packageId: 'com.acme.crm', - }); - expect(h).toEqual({ prompt: 'Add a priority field to tasks', packageId: 'com.acme.crm' }); - }); - - it('parses a JSON-string result and the Vercel { type:text, value } wrapper', () => { - const json = JSON.stringify({ status: 'build_handoff', prompt: 'Build a CRM' }); - expect(detectBuilderHandoff(json)).toEqual({ prompt: 'Build a CRM' }); - expect(detectBuilderHandoff({ type: 'text', value: json })).toEqual({ prompt: 'Build a CRM' }); - }); - - it('omits packageId when absent/blank and trims the prompt', () => { - expect(detectBuilderHandoff({ status: 'build_handoff', prompt: ' hi ' })).toEqual({ prompt: 'hi' }); - expect(detectBuilderHandoff({ status: 'build_handoff', prompt: 'x', packageId: ' ' })).toEqual({ prompt: 'x' }); - }); - - it('ignores non-handoff results and an empty prompt', () => { - expect(detectBuilderHandoff({ status: 'blueprint_proposed' })).toBeUndefined(); - expect(detectBuilderHandoff({ status: 'build_handoff', prompt: ' ' })).toBeUndefined(); - expect(detectBuilderHandoff({ foo: 1 })).toBeUndefined(); - expect(detectBuilderHandoff(undefined)).toBeUndefined(); - }); - - it('attaches builderHandoff to the mapped tool invocation', () => { - const [msg] = uiMessagesToChatMessages([ - { - id: 'm1', - role: 'assistant', - parts: [ - { - type: 'tool-suggest_builder', - toolCallId: 't1', - state: 'output-available', - output: { status: 'build_handoff', prompt: 'Add a field', packageId: 'p.kg' }, - }, - ], - }, - ] as never); - expect(msg.toolInvocations?.[0]?.builderHandoff).toEqual({ prompt: 'Add a field', packageId: 'p.kg' }); - }); -}); - describe('uiMessagesToChatMessages', () => { it('returns [] for empty / non-array input', () => { expect(uiMessagesToChatMessages([])).toEqual([]); @@ -741,125 +259,3 @@ describe('uiMessagesToChatMessages', () => { expect(out[0]?.streaming).toBeFalsy(); }); }); - -// Refresh-survival (the user-reported bug): the live `data-build-progress` parts -// are transient and never persisted, so a reloaded whole-app build lost its -// "Built X" panel + Open/Preview affordances. We reconstruct a completed summary -// from the apply_blueprint draft envelope, which IS persisted on the tool result. -describe('buildProgressFromDraftReview (reload synthesis)', () => { - it('synthesizes a done panel from a whole-app draft (includes an app item)', () => { - const bp = buildProgressFromDraftReview({ - items: [ - { type: 'object', name: 'expense' }, - { type: 'view', name: 'expense.list' }, - { type: 'app', name: 'expense_tracker' }, - ], - packageId: 'com.workspace', - }); - expect(bp).toEqual({ - phase: 'done', - appLabel: 'Expense Tracker', - items: [ - { type: 'object', name: 'expense' }, - { type: 'view', name: 'expense.list' }, - { type: 'app', name: 'expense_tracker' }, - ], - done: 3, - total: 3, - }); - }); - - it('returns undefined for an incremental edit (no app item) — keeps the draft card but no build tree', () => { - expect( - buildProgressFromDraftReview({ items: [{ type: 'field', name: 'expense.payment_method' }] }), - ).toBeUndefined(); - }); - - it('returns undefined for empty / missing input', () => { - expect(buildProgressFromDraftReview(undefined)).toBeUndefined(); - expect(buildProgressFromDraftReview({ items: [] })).toBeUndefined(); - }); - - it('uiMessageToChatMessage reconstructs buildProgress from a persisted apply_blueprint result (no live build-progress part)', () => { - const out = uiMessageToChatMessage({ - id: 'm-reload-build', - role: 'assistant', - parts: [ - { - type: 'tool-apply_blueprint', - toolCallId: 'call_reload', - state: 'output-available', - input: { blueprint: {} }, - // The persisted ModelMessage result merged back onto the call part — - // no `data-build-progress` part exists after reload. - output: { - status: 'drafted', - drafted: [ - { type: 'object', name: 'expense' }, - { type: 'app', name: 'expense_tracker' }, - ], - packageId: 'com.workspace', - materialized: true, - }, - }, - ], - }); - expect(out.buildProgress).toMatchObject({ phase: 'done', appLabel: 'Expense Tracker', done: 2, total: 2 }); - // and the draft affordances survive too - expect(out.toolInvocations?.[0]?.draftReview?.packageId).toBe('com.workspace'); - }); - - it('does NOT override a live data-build-progress part with the synthesized summary', () => { - const out = uiMessageToChatMessage({ - id: 'm-live-build', - role: 'assistant', - parts: [ - { - type: 'data-build-progress', - id: 'build-progress', - data: { phase: 'data', appLabel: 'Live', items: [{ type: 'object', name: 'x' }], done: 1, total: 4 }, - }, - { - type: 'tool-apply_blueprint', - toolCallId: 'call_live', - state: 'output-available', - input: {}, - output: { status: 'drafted', drafted: [{ type: 'app', name: 'x_app' }], packageId: 'p' }, - }, - ], - }); - // live progress wins (phase 'data', not the synthesized 'done') - expect(out.buildProgress).toMatchObject({ phase: 'data', appLabel: 'Live', done: 1, total: 4 }); - }); -}); - -describe('detectDraftResult is exported for shared hydration', () => { - it('parses a batch envelope into items', () => { - expect(detectDraftResult({ status: 'drafted', drafted: [{ type: 'app', name: 'a' }] })?.items).toEqual([ - { type: 'app', name: 'a' }, - ]); - }); -}); - -describe('supersededPlanIds — the plans a later plan in the same turn replaced', () => { - const plan = { objects: [{ name: 'book', fieldCount: 1 }], counts: { objects: 1, views: 0, dashboards: 0, seedData: 0 }, questions: [], assumptions: [] }; - const step = (id: string, toolCallId: string, proposedPlan: typeof plan | null = plan) => ({ - id, - role: 'assistant' as const, - content: '', - toolInvocations: [{ toolCallId, toolName: 'propose_blueprint', state: 'output-available' as const, ...(proposedPlan ? { proposedPlan } : {}) }], - }); - const user = (id: string) => ({ id, role: 'user' as const, content: 'build it' }); - - it('one turn spread over several messages keeps only its newest plan', () => { - expect([...supersededPlanIds([user('u1'), step('a1', 'p1'), step('a2', 'p2'), step('a3', 'p3')])]).toEqual(['p1', 'p2']); - }); - - it('a user message starts a new turn; a lone plan of an earlier turn is kept', () => { - expect([...supersededPlanIds([user('u1'), step('a1', 'p0'), user('u2'), step('a2', 'p1'), step('a3', 'p2')])]).toEqual(['p1']); - }); - - it('an invocation with no plan supersedes nothing, and a single plan is never superseded', () => { - expect(supersededPlanIds([user('u1'), step('a1', 'p1'), step('a2', 'x', null)]).size).toBe(0); - }); -}); diff --git a/ui/packages/plugin-chatbot/src/__tests__/recordHandoff.test.ts b/ui/packages/plugin-chatbot/src/__tests__/recordHandoff.test.ts index 04c2a0b01dd..e125a4e6c3e 100644 --- a/ui/packages/plugin-chatbot/src/__tests__/recordHandoff.test.ts +++ b/ui/packages/plugin-chatbot/src/__tests__/recordHandoff.test.ts @@ -5,8 +5,8 @@ * * The server half of this hand-off shipped first and was HALF-ALIVE: the ask * agent emitted `status:'record_handoff'` with a real recordId, the reply said - * "点击上方链接打开", and there was no link — the console had a detector for - * `build_handoff` and none for this. These tests pin the client half. + * "点击上方链接打开", and there was no link — the console had no detector + * for it. These tests pin the client half. * * Wrapper coverage is not optional (the replay-envelope lesson): persisted * tool outputs arrive as `{ type:'text', value:'' }`, so a @@ -56,7 +56,7 @@ describe('detectRecordHandoff', () => { expect(detectRecordHandoff({ status: 'record_handoff', objectName: ' ', recordId: 'r1' })).toBeUndefined(); }); - it('ignores every other status — build_handoff stays the Builder card', () => { + it('ignores every other status', () => { expect(detectRecordHandoff({ status: 'build_handoff', prompt: 'x' })).toBeUndefined(); expect(detectRecordHandoff({ status: 'published' })).toBeUndefined(); expect(detectRecordHandoff(undefined)).toBeUndefined(); diff --git a/ui/packages/plugin-chatbot/src/__tests__/recordWrite-3565.test.ts b/ui/packages/plugin-chatbot/src/__tests__/recordWrite-3565.test.ts index e8053630659..a295d1127e8 100644 --- a/ui/packages/plugin-chatbot/src/__tests__/recordWrite-3565.test.ts +++ b/ui/packages/plugin-chatbot/src/__tests__/recordWrite-3565.test.ts @@ -201,9 +201,8 @@ describe('the live mapper lifts the card beside the approval it rides on', () => expect(tool?.state).toBe('approval-requested'); expect(tool?.pendingActionId).toBe('pa_7'); expect(tool?.recordWrite?.fields.map((f) => f.name)).toEqual(['name', 'company', 'source']); - // Not the sibling cards: a write proposal is neither a hand-off nor a draft. + // Not the sibling card: a write proposal is not a hand-off. expect(tool?.recordHandoff).toBeUndefined(); - expect(tool?.draftReview).toBeUndefined(); }); }); diff --git a/ui/packages/plugin-chatbot/src/__tests__/toolCardHeaderState-7254.test.tsx b/ui/packages/plugin-chatbot/src/__tests__/toolCardHeaderState-7254.test.tsx deleted file mode 100644 index 7d3b487b78a..00000000000 --- a/ui/packages/plugin-chatbot/src/__tests__/toolCardHeaderState-7254.test.tsx +++ /dev/null @@ -1,148 +0,0 @@ -/** - * ObjectUI - * Copyright (c) 2024-present ObjectStack Inc. - * - * objectui#7254 — the tool card's HEADER badge and its BODY badge must be one - * fact. - * - * The header derived "Awaiting Approval" from `isProposalResult(tool.result)` - * alone — a property of the tool's own output, which never changes once the - * tool has returned. Meanwhile the body collapsed to 已生效 / 已搭建 / 未生效 - * from four other memos the header did not read. So a card the user had - * already confirmed, and whose body said so, kept a header telling them it was - * still waiting for them. Same class as the divergence recorded on cloud#787, - * mirrored. - * - * These pins drive the real message stream (proposal turn + replay turn) and - * assert BOTH badges together — asserting either alone is what let them drift. - */ -import '@testing-library/jest-dom/vitest'; -import { describe, it, expect, vi } from 'vitest'; -import { render, screen } from '@testing-library/react'; -import { - ChatbotEnhanced, - resolveProposalCardState, - type ChatbotEnhancedMessage, -} from '../ChatbotEnhanced'; - -/** A granular edit that RETURNED a confirm-gate preview. */ -function proposalMessage(): ChatbotEnhancedMessage { - return { - id: 'a1', - role: 'assistant', - content: '', - toolInvocations: [ - { - toolCallId: 't1', - toolName: 'apply_edit', - state: 'output-available', - // The header reads the RESULT, so the pin has to carry the real - // envelope — `proposedChanges` alone never reached that branch. - result: { status: 'changes_proposed', changes: [{ verb: 'add_field' }] }, - proposedChanges: { - changes: [{ verb: 'add_field', object: 'task', field: 'priority' }], - }, - }, - ], - }; -} - -function replayMessage( - outcome: NonNullable[number]['replayOutcome']>, -): ChatbotEnhancedMessage { - return { - id: 'a2', - role: 'assistant', - content: '', - toolInvocations: [ - { - toolCallId: 'replay_turn_0', - toolName: 'apply_edit', - state: 'output-available', - result: '{}', - replayOutcome: outcome, - }, - ], - }; -} - -/** The header badge text of the (single) tool card on screen. */ -function headerBadgeText(): string { - const trigger = document.querySelector('[data-state]')!; - return trigger.textContent ?? ''; -} - -describe('resolveProposalCardState — one producer for both badges', () => { - it('nothing has happened yet → pending', () => { - expect(resolveProposalCardState({})).toBe('pending'); - }); - - it('a replay verdict outranks the positional heuristics', () => { - expect(resolveProposalCardState({ replayOutcome: { kind: 'published' } })).toBe('settled'); - expect(resolveProposalCardState({ replayOutcome: { kind: 'drafted' } })).toBe('settled'); - expect(resolveProposalCardState({ replayOutcome: { kind: 'applying' } })).toBe('in-progress'); - // A failure with `confirmed` also true stays failed — the user DID confirm, - // and the card must not report the confirmation as the outcome. - expect( - resolveProposalCardState({ replayOutcome: { kind: 'failed' }, confirmed: true }), - ).toBe('failed'); - }); - - it('an observed later commit settles the card; a bare approval only starts it', () => { - expect(resolveProposalCardState({ built: true })).toBe('settled'); - expect(resolveProposalCardState({ confirmed: true })).toBe('settled'); - expect(resolveProposalCardState({ approved: true })).toBe('in-progress'); - // "Built" is an observation of the stream, "approved" is a click — the - // observation wins when both are set. - expect(resolveProposalCardState({ approved: true, built: true })).toBe('settled'); - }); -}); - -describe('ChatbotEnhanced — the header badge follows the card body (objectui#7254)', () => { - it('an unanswered proposal still reads as awaiting on both surfaces', () => { - render(); - expect(headerBadgeText()).toContain('Awaiting approval'); - // The body is still offering the confirm button — nothing has been applied. - expect(screen.getByTestId('proposed-changes-confirm')).toBeInTheDocument(); - }); - - it('a published replay flips the header to Completed, matching the Applied body badge', () => { - render( - , - ); - expect(screen.getByTestId('proposed-changes-applied')).toBeInTheDocument(); - const header = headerBadgeText(); - expect(header).toContain('Completed'); - expect(header).not.toContain('Awaiting'); - }); - - it('a drafted replay is settled too — the change left the proposal state', () => { - render( - , - ); - expect(screen.getByTestId('proposed-changes-drafted')).toBeInTheDocument(); - expect(headerBadgeText()).not.toContain('Awaiting'); - }); - - it('a failed replay reads as an error, not as "still waiting for you"', () => { - render( - , - ); - expect(screen.getByTestId('proposed-changes-failed')).toBeInTheDocument(); - const header = headerBadgeText(); - expect(header).toContain('Error'); - expect(header).not.toContain('Awaiting'); - }); -}); diff --git a/ui/packages/plugin-chatbot/src/__tests__/toolCardI18n-7254.test.tsx b/ui/packages/plugin-chatbot/src/__tests__/toolCardI18n-7254.test.tsx index d4f936f2957..a2767502263 100644 --- a/ui/packages/plugin-chatbot/src/__tests__/toolCardI18n-7254.test.tsx +++ b/ui/packages/plugin-chatbot/src/__tests__/toolCardI18n-7254.test.tsx @@ -27,59 +27,25 @@ function renderZh(ui: React.ReactElement) { ); } -const proposal: ChatbotEnhancedMessage = { +const lookup: ChatbotEnhancedMessage = { id: 'a1', role: 'assistant', content: '', toolInvocations: [ { toolCallId: 't1', - toolName: 'apply_edit', + toolName: 'query_records', state: 'output-available', - result: { status: 'changes_proposed', changes: [{ verb: 'add_field' }] }, - proposedChanges: { changes: [{ verb: 'add_field', object: 'task', field: 'priority' }] }, - }, - ], -}; - -const plan: ChatbotEnhancedMessage = { - id: 'a2', - role: 'assistant', - content: '', - toolInvocations: [ - { - toolCallId: 't2', - toolName: 'propose_blueprint', - state: 'output-available', - result: { status: 'blueprint_proposed', blueprint: {} }, - proposedPlan: { - summary: '', - objects: [], - questions: [], - assumptions: [], - counts: { objects: 1, views: 1, dashboards: 1, seedData: 0 }, - }, + result: { records: [] }, }, ], }; describe('tool cards under a zh console (objectui#7254)', () => { it('names the tool in Chinese instead of title-casing its internal name', () => { - renderZh(); - expect(screen.getByText('应用这次修改')).toBeInTheDocument(); - expect(screen.queryByText('Apply edit')).not.toBeInTheDocument(); - }); - - it('localizes the header status badge, which carried its own English table', () => { - renderZh(); - expect(screen.getByText('待确认')).toBeInTheDocument(); - expect(screen.queryByText(/Awaiting/i)).not.toBeInTheDocument(); - }); - - it('localizes the plan count strip, which was concatenated with an English "+ s" plural', () => { - renderZh(); - expect(screen.getByText('拟定应用方案')).toBeInTheDocument(); - expect(screen.getByText('1 个对象 · 1 个视图 · 1 个仪表盘')).toBeInTheDocument(); + renderZh(); + expect(screen.getByText('查找相关记录')).toBeInTheDocument(); + expect(screen.queryByText('Query records')).not.toBeInTheDocument(); }); it('an unknown / third-party tool still degrades to the English title-caser', () => { diff --git a/ui/packages/plugin-chatbot/src/__tests__/useObjectChat.honestMessages.test.tsx b/ui/packages/plugin-chatbot/src/__tests__/useObjectChat.honestMessages.test.tsx index bbc3065a7b3..056dbaa4339 100644 --- a/ui/packages/plugin-chatbot/src/__tests__/useObjectChat.honestMessages.test.tsx +++ b/ui/packages/plugin-chatbot/src/__tests__/useObjectChat.honestMessages.test.tsx @@ -16,7 +16,7 @@ * with the values flowing through it, so proving either one alone reproduces * exactly the blindness that shipped. * - * Read the ASSERTIONS as type assertions too. Every `messages[0].buildProgress` + * Read the ASSERTIONS as type assertions too. Every `messages[0].charts` * / `.toolInvocations?.[0]?.pendingActionId` below is written WITHOUT a cast — * under the old declaration (`messages: OuiChatMessage[]`, the authoring * contract) not one of them would compile, which is precisely why nothing was @@ -28,39 +28,27 @@ import { renderHook, act } from '@testing-library/react'; import { vi, describe, it, expect } from 'vitest'; import { useObjectChat, type UseObjectChatOptions } from '../useObjectChat'; -const API = 'https://example.test/api/v1/ai/agents/build/chat'; +const API = 'https://example.test/api/v1/ai/agents/ask/chat'; /** * One assistant turn as the AI SDK holds it: text, a tool call whose result is - * an ADR-0033 pending-approval envelope, the reconciled build-progress part and - * an inline chart. Every runtime-only key the card names is reachable from it. + * an ADR-0033 pending-approval envelope and an inline chart. Every runtime-only key the card names is reachable from it. */ const { AI_MESSAGES } = vi.hoisted(() => ({ AI_MESSAGES: [ { - id: 'm-built', + id: 'm-answer', role: 'assistant', metadata: { conversationId: 'conv-1' }, parts: [ - { type: 'text', text: 'Built your app.' }, + { type: 'text', text: 'Here are your loans.' }, { - type: 'tool-apply_blueprint', - toolCallId: 'call_build_1', + type: 'tool-run_action', + toolCallId: 'call_action_1', state: 'output-available', - input: { appLabel: 'Loans' }, + input: { action: 'close_loan' }, output: { status: 'pending_approval', pendingActionId: 'pa_42' }, }, - { - type: 'data-build-progress', - id: 'bp-1', - data: { - phase: 'done', - appLabel: 'Loans', - items: [{ type: 'app', name: 'loans' }], - done: 1, - total: 1, - }, - }, { type: 'data-chart', id: 'chart-1', @@ -90,14 +78,12 @@ vi.mock('@ai-sdk/react', () => ({ })); describe('API mode: the runtime-only keys are on the hook, not just under it', () => { - it('exposes buildProgress, charts and metadata on the returned messages', () => { + it('exposes charts and metadata on the returned messages', () => { const { result } = renderHook(() => useObjectChat({ api: API, conversationId: 'c1' })); const [message] = result.current.messages; - expect(message.content).toBe('Built your app.'); - // The build panel. Erased by the old `as OuiChatMessage[]`. - expect(message.buildProgress).toMatchObject({ phase: 'done', appLabel: 'Loans', total: 1 }); - // Inline charts — same erasure. + expect(message.content).toBe('Here are your loans.'); + // Inline charts. Erased by the old `as OuiChatMessage[]`. expect(message.charts).toHaveLength(1); expect(message.charts?.[0]).toMatchObject({ chartType: 'bar', title: 'Loans by status' }); // `metadata` is the key the hook splices back in; the authoring contract @@ -109,7 +95,7 @@ describe('API mode: the runtime-only keys are on the hook, not just under it', ( const { result } = renderHook(() => useObjectChat({ api: API, conversationId: 'c1' })); const tool = result.current.messages[0]?.toolInvocations?.[0]; - expect(tool?.toolName).toBe('apply_blueprint'); + expect(tool?.toolName).toBe('run_action'); // The approve/reject card's entire wiring: without `pendingActionId` there // is no id to POST a decision for, and `useHitlInChat` indexes nothing. expect(tool?.pendingActionId).toBe('pa_42'); @@ -137,9 +123,9 @@ describe('API mode: the runtime-only keys are on the hook, not just under it', ( >; expect(content).toBe('and now a chart'); // …the thread as it will be after this send: the built turn, then the new - // user message. The built turn still carries its render-only keys. + // user message. The answered turn still carries its render-only keys. expect(messages).toHaveLength(2); - expect(messages[0]?.buildProgress?.phase).toBe('done'); + expect(messages[0]?.charts).toHaveLength(1); expect(messages[0]?.toolInvocations?.[0]?.pendingActionId).toBe('pa_42'); expect(messages[1]).toMatchObject({ role: 'user', content: 'and now a chart' }); }); diff --git a/ui/packages/plugin-chatbot/src/chatMessageAdapter.ts b/ui/packages/plugin-chatbot/src/chatMessageAdapter.ts index 999adb98875..b73ee377944 100644 --- a/ui/packages/plugin-chatbot/src/chatMessageAdapter.ts +++ b/ui/packages/plugin-chatbot/src/chatMessageAdapter.ts @@ -20,7 +20,7 @@ * contract — what the React components actually render, so it is * deliberately narrower (three roles, string timestamps) and carries * render-only keys the authoring surface has no business declaring - * (`buildProgress`, `charts`). + * (`charts`, `recordCitations`). * * Until this module they met as three `messages as any` casts, which erased * ALL of the drift rather than the parts that are intentional: a new authored @@ -43,10 +43,9 @@ * The adapter narrows the drifting fields **by name** and spreads the rest. It * deliberately does NOT rebuild the message field-by-field, because the values * arriving here are not always plain authored ones: in API mode they are - * RUNTIME messages carrying `buildProgress`, `blueprintProgress`, `charts` and - * tool invocations bearing the HITL / draft-review extensions. A field-by-field - * rebuild would silently drop the approval cards, the "Review N changes" - * affordance and the build panel. + * RUNTIME messages carrying `charts`, `recordCitations` and tool invocations + * bearing the HITL approval id. A field-by-field rebuild would silently drop + * the approval cards, the charts and the record citations. * * What changed in objectui#4424: those keys are no longer preserved *by faith*. * The hook used to declare its output as the authoring type and reach the @@ -91,24 +90,15 @@ import type { */ type RuntimeOnlyMessageKeys = Pick< RuntimeChatMessage, - 'buildProgress' | 'blueprintProgress' | 'charts' | 'recordCitations' + 'charts' | 'recordCitations' >; /** - * The render-only TOOL-INVOCATION keys — the HITL approval id, the ADR-0033 - * draft review, the proposed plan / changes cards and the ADR-0057 P4 builder - * handoff. `mapMessages.ts` lifts every one of them out of a tool result; the - * authoring contract declares none of them. objectui#4424. + * The render-only TOOL-INVOCATION keys — the HITL approval id. `mapMessages.ts` + * lifts it out of a tool result; the authoring contract does not declare it. + * objectui#4424. */ -type RuntimeOnlyToolInvocationKeys = Pick< - RuntimeToolInvocation, - | 'pendingActionId' - | 'draftReview' - | 'proposedPlan' - | 'proposedChanges' - | 'builderHandoff' - | 'replayOutcome' ->; +type RuntimeOnlyToolInvocationKeys = Pick; /** * One tool invocation as it actually crosses this seam: the authoring contract, @@ -238,8 +228,7 @@ export function toRuntimeToolState( * One authored tool invocation -> one runtime tool invocation. * * Only `state` drifts; everything else is spread through, which is what keeps - * the runtime-only extensions (`pendingActionId`, `draftReview`, - * `proposedPlan`, `proposedChanges`, `builderHandoff`) alive on the API-mode + * the runtime-only extension (`pendingActionId`) alive on the API-mode * path. Since objectui#4424 the parameter names them ({@link * SeamToolInvocation}), so `passthrough` carries them as declared properties * instead of as keys the compiler cannot see — see the module doc. diff --git a/ui/packages/plugin-chatbot/src/core.ts b/ui/packages/plugin-chatbot/src/core.ts index 5548806fc7b..e88c600aab4 100644 --- a/ui/packages/plugin-chatbot/src/core.ts +++ b/ui/packages/plugin-chatbot/src/core.ts @@ -46,7 +46,7 @@ export { AI_USAGE_REFRESH_EVENT, emitAiUsageRefresh } from './aiUsageEvents'; // ADR-0038 L3 — the publish-health parse every publish-drafts host shares. export { publishHealthFromResponse } from './publishHealth'; -export type { PublishHealth, PublishOutcome } from './publishHealth'; +export type { PublishHealth } from './publishHealth'; // The pending-approval envelope parse the app-shell hydration mapper shares // with the live one (objectui#8442). `toolResultParsers` holds only an diff --git a/ui/packages/plugin-chatbot/src/index.tsx b/ui/packages/plugin-chatbot/src/index.tsx index a2fff24bab8..5584ab71632 100644 --- a/ui/packages/plugin-chatbot/src/index.tsx +++ b/ui/packages/plugin-chatbot/src/index.tsx @@ -300,15 +300,16 @@ export * from './renderer'; // Shared composition layer over the vendored AI Elements (used by both // Studio's sidebar panel and Console's floating chatbot). -export { ChatbotEnhanced, publishHealthFromResponse } from './ChatbotEnhanced'; +export { ChatbotEnhanced } from './ChatbotEnhanced'; +// ADR-0038 L3 — the publish-health parse every publish-drafts host shares. +export { publishHealthFromResponse } from './publishHealth'; +export type { PublishHealth } from './publishHealth'; export type { ChatbotEnhancedProps, ChatbotEnhancedToolInvocation, ChatSource as ChatbotEnhancedSource, ChatbotLabels, ToolDecisionState, - PublishHealth, - PublishOutcome, } from './ChatbotEnhanced'; /** @@ -330,7 +331,7 @@ export type { * Pinned at compile time in `__tests__/chat-message-contract.test.ts`. * * `` renders only the core fields; the enhanced surface (tool calls, - * reasoning, sources, build progress, charts) is ``. + * reasoning, sources, charts) is ``. */ export type { ChatbotEnhancedMessage } from './ChatbotEnhanced'; @@ -345,20 +346,12 @@ export * as AIElements from './elements'; export { uiMessageToChatMessage, uiMessagesToChatMessages, - detectDraftResult, - detectProposedPlan, - detectBuilderHandoff, detectRecordHandoff, detectRecordWrite, detectAnswerSource, detectSampleDataCleanup, detectPackageRemoval, - detectProposedChanges, - detectReplayOutcome, - detectAuthoringVerdict, - detectBuiltAppPackage, detectPendingApproval, - buildProgressFromDraftReview, chartsFromParts, chartAnswerParts, storedAnswerParts, @@ -369,16 +362,11 @@ export type { ChartAnswerPart, StoredAnswerData, StoredAnswerPart, - DraftReview, - ProposedPlan, - BuilderHandoff, RecordWrite, RecordWriteField, SampleDataCleanup, PackageRemoval, PackageRemovalObject, - ProposedChanges, - ReplayOutcome, } from './mapMessages'; // The answer-source block's type: the union of the two published contracts it // is lifted through (an object query's `source`, `query_dataset`'s diff --git a/ui/packages/plugin-chatbot/src/mapMessages.ts b/ui/packages/plugin-chatbot/src/mapMessages.ts index e02aaa1170a..d7de32f9d68 100644 --- a/ui/packages/plugin-chatbot/src/mapMessages.ts +++ b/ui/packages/plugin-chatbot/src/mapMessages.ts @@ -15,8 +15,6 @@ * `prepareSendMessagesRequest` transport). */ import type { - BUILD_PROGRESS_FRAME_TYPE, - BuildProgressPhase, DatasetProvenance, ObjectQuerySource, RecordCitationParsed, @@ -27,7 +25,7 @@ import { RECORD_CITATIONS_PART_TYPE, RecordCitationsSchema, } from '@objectstack/spec/ai'; -import type { ChatbotEnhancedMessage as ChatMessage, ChatbotEnhancedToolInvocation as ChatToolInvocation, ChatSource, ChatBuildProgress, ChatBlueprintProgress } from './ChatbotEnhanced'; +import type { ChatbotEnhancedMessage as ChatMessage, ChatbotEnhancedToolInvocation as ChatToolInvocation, ChatSource } from './ChatbotEnhanced'; import { chartsFromParts, detectPendingApproval, extractCharts, parseResultEnvelope, type AnyPart } from './toolResultParsers'; // The parsers the eager `/core` entry shares live in `./toolResultParsers`, so @@ -99,594 +97,6 @@ function extractReasoning(parts: AnyPart[]): string | undefined { return joined.length > 0 ? joined : undefined; } -/** - * Best-effort detector for the framework's ADR-0033 draft envelopes. Metadata - * authoring tools stage changes as DRAFTS and return one of: - * • single — `{ status:'drafted', type, name, summary, changedKeys }` - * (create_object / add_field / create_metadata / update_metadata / …) - * • batch — `{ status:'drafted', drafted:[{type,name}], failed, summary }` - * (apply_blueprint), or the same batch with `kind:'edit'` (apply_edit, - * an INCREMENTAL edit — objectui#10109) - * We lift the reviewable `{ type, name }` targets so the chat can render a - * "Review N change(s)" affordance that opens the designer's review/diff. - * `blueprint_proposed` (propose_blueprint) has no draft yet → not surfaced here. - */ -export interface DraftReview { - items: Array<{ type: string; name: string }>; - summary?: string; - packageId?: string; - /** - * Backend lifecycle intent (from the tool result). `true` for whole-app - * builds (apply_blueprint) — eligible for the auto-publish "magic moment". - * Omitted for incremental edits, which stay drafts for explicit review. - */ - autoPublishable?: boolean; - /** Count of artifacts that failed in a partial build, surfaced not hidden. */ - failedCount?: number; - /** - * ADR-0045: the build was MATERIALIZED in-turn — real tables and seed - * rows exist; the app is live but `hidden` (unlisted). Preview should - * open the REAL app URL, not the draft overlay. - */ - materialized?: boolean; - /** - * The build envelope's `appHidden`, beside `materialized`: `false` says - * the materialized app is already listed, i.e. published (ADR-0045 - * publish = live AND visible). Absent when the envelope does not say. - */ - appHidden?: boolean; - /** - * ADR-0038 L1 graph-lint verdict for the staged build. Rendered as a - * verified/issues chip so "drafted" and "verified" read as the two - * separate statements they are. Absent on older tool output. - */ - verification?: { errors: number; warnings: number }; - /** - * ADR-0038 L1 — the individual lint findings behind the `verification` - * counts, so the chat can show WHAT is wrong (not just "N issues"). Each - * carries an agent-actionable `message`; `fix` is the mechanical hint. - */ - issues?: Array<{ severity: 'error' | 'warning'; code: string; message: string; fix?: string }>; - /** - * Concrete post-build "what's next" steps the assistant returns on a whole-app - * build (apply_blueprint `nextSteps`), e.g. "replace the sample data", - * "publish from the status panel". Rendered as a short getting-started - * checklist under the build summary so the user has an obvious next action - * instead of a dead end. Lifecycle-neutral (publishing is described via the - * status panel, never asserted as done). - */ - nextSteps?: string[]; - /** - * objectui#10109 — the producer's marker for an INCREMENTAL edit, lifted - * from the envelope's own `kind`: `apply_edit` answers `kind: 'edit'`, and a - * whole-app `apply_blueprint` build carries no `kind`. An edit's `items` may - * honestly include the `app` artifact it re-staged (an `add_object` op - * merges the nav), so the readers that infer a whole-app build from a draft - * review's staged artifact types check this first: `buildProgressFromDraftReview` - * here, and app-shell's built-moment transition (`detectBuiltAppPackage` reads - * the envelope's own `kind` instead). Only the value those readers act on is - * declared: an envelope that does not say `'edit'` lifts nothing here. - */ - kind?: 'edit'; -} - -/** - * The lifecycle stage BEFORE a draft. `propose_blueprint` returns - * `{ status:'blueprint_proposed', blueprint, counts, questions, assumptions }` - * — a PLAN the user reviews (and can adjust) before `apply_blueprint` stages - * it. Nothing is created yet; this is the confirm gate. We lift the reviewable - * shape so the chat can render a "Proposed plan" card — the objects it will - * create, the agent's assumptions, and any structure-deciding questions — - * instead of burying the proposal in a "Propose blueprint — Completed" step. - */ -export interface ProposedPlan { - summary?: string; - /** - * objectui#12724 — the app's display label (`blueprint.app.label`, the - * spec's `BlueprintAppSchema`), for the card's 「方案 · APP」 header. Absent - * when the blueprint names no app label. - */ - appLabel?: string; - /** - * Objects (tables) the build will create — machine name, label, field count. - * objectui#12724 — `fields` lifts the name and label of each declared field - * (`blueprint.objects[].fields`, the spec's `BlueprintFieldSchema`) so the - * card can draw one chip per field. Absent when no entry carries a name (a - * cache-fallback reload keeps only the count), and the card then draws the - * object chip with its count, as before. - */ - objects: Array<{ - name: string; - label?: string; - fieldCount: number; - fields?: Array<{ name: string; label?: string }>; - }>; - /** - * objectui#12724 — the views the build will create (`blueprint.views`, the - * spec's `BlueprintViewSchema`), by name and label. Absent when the - * blueprint declares none. - */ - views?: Array<{ name: string; label?: string }>; - /** Totals for a compact "N objects · N views · …" line. */ - counts: { objects: number; views: number; dashboards: number; seedData: number }; - /** ≤2 structure-deciding questions to confirm before building (may be empty). */ - questions: string[]; - /** - * One-click answer options for the structure-deciding questions, when the - * backend (propose_blueprint `questionChoices`) could derive them. Matched to - * a `questions` entry by `text`; a question with no entry here renders as - * plain text (type-to-answer). Each set has ≥2 options, recommended first. - */ - questionChoices?: Array<{ text: string; options: string[] }>; - /** - * Assumptions the agent made from an underspecified goal (may be empty). - * objectui#12724 — read from `planCard.assumptions` when the envelope - * carries a plan card, else from `blueprint.assumptions` as before. - */ - assumptions: string[]; - /** Extend mode: the existing app the new objects would be added into. */ - targetApp?: string; - /** - * objectui#12724 — the plan card's v2 rows, from the envelope's `planCard`. - * Absent on a producer that predates it, and the card then draws the rows - * above as before. - */ - planCard?: ProposedPlanCard; - /** - * objectui#12724 — one line per view (the envelope's `viewIntents`). The card - * reads it only when there is no `planCard`, whose views carry the same line. - */ - viewIntents?: ProposedPlanViewLine[]; - /** - * objectstack#27480 — the envelope's `decision: 'iterate_or_new'`: the plan - * overlaps an app that already exists (`existingAppOverlap`), so it is a - * QUESTION, not a plan to approve. The card asks whether to keep improving - * that app or build a separate one, and draws no "Build it" button. `app` is - * the overlapping app's `name` / `label`, absent when the envelope names none. - */ - iterateOrNew?: ProposedPlanIterateOrNew; -} - -/** objectstack#27480 — the extend-or-new question a `decision: 'iterate_or_new'` plan asks. */ -export interface ProposedPlanIterateOrNew { - app?: { name: string; label?: string }; -} - -/** One view's intent line: `viewIntents[]` and `planCard.views[]` both carry it. */ -export interface ProposedPlanViewLine { - view: string; - object: string; - label?: string; - line: string; -} - -/** - * objectui#12724 — the keys of `propose_blueprint`'s `planCard` that the plan - * card draws. The producer's contract is objectstack-ai/cloud's - * `ProposeBlueprintCardPayload` (`packages/service-ai-studio/schema/build-cards.schema.json`, - * vendored beside this package's tests); keys this card does not draw are not - * lifted. - */ -export interface ProposedPlanCard { - objects: Array<{ - name: string; - label: string; - fields: Array<{ - name: string; - label: string; - /** The format the sample data is held to, as the chip's words (`format.label`). */ - format?: { label: string }; - /** - * objectui#12994 — the stage field's lifecycle, as the chip's words - * (`lifecycle.label`, e.g. 「借出 · 已还 ✓完成 · 逾期 ⚠」). The producer's - * `options` are not drawn, so they are not lifted. - */ - lifecycle?: { label: string }; - /** The model added this field; the user's words did not name it. */ - suggested?: true; - }>; - /** - * The record's name field, when the plan declares one. `generated` - * (objectui#13004) is present when the title is composed for the user, not - * typed: the card draws its `line` (e.g. 「名称:自动生成「{图书} · {读者} · - * {借出日期}」,表单里不出现」) in place of 「名称:LABEL」. The producer's - * `template` is not drawn, so it is not lifted. - */ - nameField?: { name: string; label: string; generated?: { line: string } }; - }>; - views: ProposedPlanViewLine[]; - assumptions: string[]; - /** The sample data the build stages, as one line. Absent when it stages none. */ - sampleData?: { line: string }; - /** - * cloud#2924 ruling A — how the build will land once approved: `publish` (a - * new app's first build, or an app with no records yet) or `draft` (an app - * live with records), and the card's `line` (e.g. 「首次搭建直接上线;之后的修改 - * 先存草稿,由你发布」). Absent where the build does not publish in the turn, - * and the card then says nothing about it. The producer's `liveRecords` is - * already in the line, so it is not lifted. - */ - posture?: { mode: 'publish' | 'draft'; line: string }; -} - -/** - * One row of the result card's checklist (cloud `build-cards.schema.json`). - * - * - `object` / `view` / `sampleData`: a measured line, drawn by `status` and - * the producer's `line`. - * - `verification` (`ChecklistVerificationLine`): appended when the build's - * verdict has errors; always `failed`, and it carries the producer's `label` - * and the issue `count` instead of a `line`. - * - `other`: a line of a kind this console does not know yet, carrying a - * valid `status` and a string `line`; `kind` is the producer's kind. It is - * drawn by those two fields, so a new kind needs no console change. - */ -export type BuildResultChecklistLine = - | { kind: 'object' | 'view' | 'sampleData'; status: 'passed' | 'failed'; line: string } - | { kind: 'verification'; status: 'failed'; label: string; count: number } - | { kind: 'other'; servedKind: string; status: 'passed' | 'failed'; line: string }; - -/** - * objectui#12724 — the keys of the result card's `checklist` that the card - * draws, from `apply_blueprint`'s and `verify_build`'s envelopes - * (objectstack-ai/cloud's `BuildResultCardPayload`). - */ -export interface BuildResultChecklist { - status: 'passed' | 'failed'; - passed: number; - total: number; - /** Objects, then views, then the sample data, each measured on the build. */ - lines: BuildResultChecklistLine[]; - /** The app 打开应用 opens. */ - app?: { name: string; label?: string }; - /** The package 在 Studio 中查看 opens. */ - packageId?: string; -} - -/** Defensive: keep only non-empty strings from an unknown array. */ -function nonEmptyStrings(v: unknown): string[] { - return Array.isArray(v) - ? v.filter((s): s is string => typeof s === 'string' && s.trim().length > 0) - : []; -} - -/** - * The `{ name, label? }` of each entry of a blueprint array that carries a - * name (the spec's field and view rows both declare these two keys). Entries - * without a string name are dropped, so a count-only cache copy yields none. - */ -function namedEntries(v: unknown): Array<{ name: string; label?: string }> { - return (Array.isArray(v) ? v : []).flatMap((e) => { - const r = e as { name?: unknown; label?: unknown } | null; - if (typeof r?.name !== 'string' || !r.name) return []; - return [{ name: r.name, ...(typeof r.label === 'string' && r.label ? { label: r.label } : {}) }]; - }); -} - -export function detectProposedPlan(result: unknown): ProposedPlan | undefined { - const obj = parseResultEnvelope(result); - if (!obj || obj.status !== 'blueprint_proposed') return undefined; - const rawBlueprint = (obj as { blueprint?: unknown }).blueprint; - const bp = - rawBlueprint && typeof rawBlueprint === 'object' - ? (rawBlueprint as Record) - : {}; - - const objects = (Array.isArray(bp.objects) ? bp.objects : []).flatMap((o) => { - const r = o as { name?: unknown; label?: unknown; fields?: unknown }; - if (typeof r?.name !== 'string' || !r.name) return []; - const fields = namedEntries(r.fields); - return [ - { - name: r.name, - ...(typeof r.label === 'string' && r.label ? { label: r.label } : {}), - fieldCount: Array.isArray(r.fields) ? r.fields.length : 0, - ...(fields.length ? { fields } : {}), - }, - ]; - }); - // objectstack#27480 — an `iterate_or_new` plan is a question; it is drawn - // even when it names no object, because what it asks is the whole card. - const iterateOrNew = liftIterateOrNew(obj); - // No nameable objects → nothing reviewable; don't render an empty card. - if (objects.length === 0 && !iterateOrNew) return undefined; - - const num = (v: unknown, fallback: number): number => - typeof v === 'number' && Number.isFinite(v) ? v : fallback; - const rawCounts = ((obj as { counts?: unknown }).counts ?? {}) as Record; - const counts = { - objects: num(rawCounts.objects, objects.length), - views: num(rawCounts.views, Array.isArray(bp.views) ? bp.views.length : 0), - dashboards: num(rawCounts.dashboards, Array.isArray(bp.dashboards) ? bp.dashboards.length : 0), - seedData: num(rawCounts.seedData, Array.isArray(bp.seedData) ? bp.seedData.length : 0), - }; - - // `questions` ride on the envelope; older shapes carried them on the - // blueprint — accept either. - const questions = nonEmptyStrings((obj as { questions?: unknown }).questions); - // One-click options for the questions (propose_blueprint `questionChoices`). - // Defensive: keep only entries with a text and ≥2 non-empty string options. - const rawChoices = (obj as { questionChoices?: unknown }).questionChoices; - const questionChoices = Array.isArray(rawChoices) - ? rawChoices.flatMap((c) => { - const r = c as { text?: unknown; options?: unknown }; - if (typeof r?.text !== 'string' || !r.text) return []; - const options = Array.isArray(r.options) - ? r.options.filter((o): o is string => typeof o === 'string' && o.trim().length > 0) - : []; - return options.length >= 2 ? [{ text: r.text, options }] : []; - }) - : []; - const summary = - typeof obj.summary === 'string' && obj.summary - ? obj.summary - : typeof bp.summary === 'string' && bp.summary - ? bp.summary - : undefined; - const targetApp = (obj as { targetApp?: unknown }).targetApp; - const rawApp = bp.app && typeof bp.app === 'object' ? (bp.app as { label?: unknown }) : undefined; - const appLabel = typeof rawApp?.label === 'string' && rawApp.label ? rawApp.label : undefined; - const views = namedEntries(bp.views); - const planCard = liftPlanCard((obj as { planCard?: unknown }).planCard); - const rawIntents = (obj as { viewIntents?: unknown }).viewIntents; - const viewIntents = Array.isArray(rawIntents) ? viewLines(rawIntents) : []; - - return { - ...(summary ? { summary } : {}), - ...(appLabel ? { appLabel } : {}), - objects, - ...(views.length ? { views } : {}), - counts, - questions: questions.length ? questions : nonEmptyStrings(bp.questions), - ...(questionChoices.length ? { questionChoices } : {}), - assumptions: planCard ? planCard.assumptions : nonEmptyStrings(bp.assumptions), - ...(typeof targetApp === 'string' && targetApp ? { targetApp } : {}), - ...(planCard ? { planCard } : {}), - ...(viewIntents.length ? { viewIntents } : {}), - ...(iterateOrNew ? { iterateOrNew } : {}), - }; -} - -const isText = (v: unknown): v is string => typeof v === 'string' && v.length > 0; -const recordOf = (v: unknown): Record | undefined => - v && typeof v === 'object' && !Array.isArray(v) ? (v as Record) : undefined; - -/** `{ view, object, label?, line }` rows, as `viewIntents[]` and `planCard.views[]` spell them. */ -function viewLines(v: unknown[]): ProposedPlanViewLine[] { - return v.flatMap((e) => { - const r = recordOf(e); - if (!r || !isText(r.view) || !isText(r.object) || !isText(r.line)) return []; - return [{ view: r.view, object: r.object, ...(isText(r.label) ? { label: r.label } : {}), line: r.line }]; - }); -} - -/** - * objectstack#27480 — lift the extend-or-new question off an envelope whose - * `decision` is `iterate_or_new`. The overlapping app is read from - * `existingAppOverlap`'s own `name` / `label`, the keys the card that asked - * for this names; an overlap without a name leaves `app` absent, and the card - * then asks without naming the app. Any other `decision` lifts nothing. - */ -function liftIterateOrNew(envelope: Record): ProposedPlanIterateOrNew | undefined { - if (envelope.decision !== 'iterate_or_new') return undefined; - const overlap = recordOf(envelope.existingAppOverlap); - if (!overlap || !isText(overlap.name)) return {}; - return { app: { name: overlap.name, ...(isText(overlap.label) ? { label: overlap.label } : {}) } }; -} - -/** - * objectui#12724 — lift the plan card's drawn keys off `planCard`. The schema - * requires `objects`, `views` and `assumptions`; a value without all three is - * not a plan card, and the card keeps its earlier rows. - */ -function liftPlanCard(raw: unknown): ProposedPlanCard | undefined { - const card = recordOf(raw); - if (!card || !Array.isArray(card.objects) || !Array.isArray(card.views) || !Array.isArray(card.assumptions)) { - return undefined; - } - const objects = card.objects.flatMap((o) => { - const r = recordOf(o); - if (!r || !isText(r.name) || !isText(r.label) || !Array.isArray(r.fields)) return []; - const fields = r.fields.flatMap((f) => { - const fr = recordOf(f); - if (!fr || !isText(fr.name) || !isText(fr.label)) return []; - const format = recordOf(fr.format); - const lifecycle = recordOf(fr.lifecycle); - return [ - { - name: fr.name, - label: fr.label, - ...(format && isText(format.label) ? { format: { label: format.label } } : {}), - ...(lifecycle && isText(lifecycle.label) ? { lifecycle: { label: lifecycle.label } } : {}), - ...(fr.suggested === true ? { suggested: true as const } : {}), - }, - ]; - }); - const nameField = recordOf(r.nameField); - const generated = recordOf(nameField?.generated); - return [ - { - name: r.name, - label: r.label, - fields, - ...(nameField && isText(nameField.name) && isText(nameField.label) - ? { - nameField: { - name: nameField.name, - label: nameField.label, - ...(generated && isText(generated.line) ? { generated: { line: generated.line } } : {}), - }, - } - : {}), - }, - ]; - }); - const sampleData = recordOf(card.sampleData); - const posture = recordOf(card.posture); - return { - objects, - views: viewLines(card.views), - assumptions: nonEmptyStrings(card.assumptions), - ...(sampleData && isText(sampleData.line) ? { sampleData: { line: sampleData.line } } : {}), - ...(posture && (posture.mode === 'publish' || posture.mode === 'draft') && isText(posture.line) - ? { posture: { mode: posture.mode, line: posture.line } } - : {}), - }; -} - -const isLineStatus = (v: unknown): v is 'passed' | 'failed' => v === 'passed' || v === 'failed'; -const isMeasuredLineKind = (v: unknown): v is 'object' | 'view' | 'sampleData' => - v === 'object' || v === 'view' || v === 'sampleData'; -const isCount = (v: unknown): v is number => typeof v === 'number' && Number.isInteger(v) && v >= 0; - -/** - * One served checklist line, or none when it does not carry its kind's keys. - * A known kind is read by its own shape only; a kind outside the known four is - * kept when it carries a valid `status` and a string `line`. - */ -function checklistLineOf(l: unknown): BuildResultChecklistLine[] { - const r = recordOf(l); - if (!r || !isText(r.kind)) return []; - if (r.kind === 'verification') { - return r.status === 'failed' && isText(r.label) && isCount(r.count) - ? [{ kind: 'verification', status: 'failed', label: r.label, count: r.count }] - : []; - } - if (!isLineStatus(r.status) || !isText(r.line)) return []; - return isMeasuredLineKind(r.kind) - ? [{ kind: r.kind, status: r.status, line: r.line }] - : [{ kind: 'other', servedKind: r.kind, status: r.status, line: r.line }]; -} - -/** - * objectui#12724 — the result card's `checklist`, on `apply_blueprint`'s - * envelope (drafted, or published in-turn) and on `verify_build`'s, which - * re-measures it after a repair. The schema requires `status`, `passed`, - * `total` and `lines`; without all four there is no checklist, and the card - * keeps its earlier rows. - */ -export function detectBuildChecklist(result: unknown): BuildResultChecklist | undefined { - const raw = recordOf(parseResultEnvelope(result)?.checklist); - if (!raw || !isLineStatus(raw.status) || !isCount(raw.passed) || !isCount(raw.total) || !Array.isArray(raw.lines)) { - return undefined; - } - const lines = raw.lines.flatMap(checklistLineOf); - const app = recordOf(raw.app); - return { - status: raw.status, - passed: raw.passed, - total: raw.total, - lines, - ...(app && isText(app.name) ? { app: { name: app.name, ...(isText(app.label) ? { label: app.label } : {}) } } : {}), - ...(isText(raw.packageId) ? { packageId: raw.packageId } : {}), - }; -} - -/** - * cloud#2924 — how a copilot change to a package lands, as the change envelopes - * carry it (cloud `postureEnvelope`): `draft` when the app is live and its - * tables hold `liveRecords` records, so the change is saved as a Studio draft; - * `publish` when it goes live in the turn (a first build, an app holding no - * records, a platform package). - */ -export interface ChangePosture { - mode: 'draft' | 'publish'; - /** Records the package's live tables hold. */ - liveRecords: number; - /** The package is a platform package; the posture by state is not read there. */ - platformPackage?: true; - /** In the turn that applied a blueprint: the rows that build seeded, left out of `liveRecords`. */ - buildTurnRows?: number; -} - -/** - * A granular metadata-change preview (confirm-before-change). A mutating tool - * that has NOT been approved this turn returns - * { status: 'changes_proposed', changes: [...], summary? } instead of - * committing, so the chat renders a "确认修改" card. Mirrors detectProposedPlan. - * - * objectui#12894 — cloud#2924 adds `posture` and `primaryAction`, read before - * the card is shown. Both are absent from an older cloud, and from an - * environment that does not publish AI changes in the turn; the card then - * draws as it did before. - */ -export interface ProposedChanges { - summary?: string; - changes: Array<{ - verb: string; - object?: string; - field?: string; - type?: string; - name?: string; - /** cloud#2924 — the row's parameters in small type (label · default · required), in the user's language. */ - details?: string; - }>; - /** cloud#2924 — how the change will land once confirmed. */ - posture?: ChangePosture; - /** cloud#2924 — the card's primary action: `save_draft` reads 存为草稿, `confirm` keeps the host's label. */ - primaryAction?: 'save_draft' | 'confirm'; -} - -/** One pending draft, as Studio's 变更 list names it (cloud `PendingDraft`). */ -export interface PendingDraftItem { - type: string; - name: string; -} - -/** - * cloud#2924 — the package's pending drafts, read after the change landed - * through `listDrafts`, the read Studio's 变更 badge makes (cloud `DraftState`). - */ -export interface ChangeDraftState { - /** Pending drafts in the package — the number Studio's 变更 badge shows. */ - pending: number; - items: PendingDraftItem[]; - /** Pending drafts this change did not stage (an earlier edit, the user's own). */ - others: number; -} - -/** - * cloud#2924 — a field the change added to a table that already holds records: - * every one of those `rows` has no value for it (cloud `ExistingRowsLine`). - */ -export interface ExistingRowsLine { - object: string; - field: string; - label: string; - rows: number; -} - -/** - * cloud#2924 — the applied card of a change saved as a draft, in the user's - * language: its title (「已存为草稿 · 2 项未发布」) and its lines - * (「已有 12 条记录的续借次数为空」, 「核对:结构 ✓」). - */ -export interface AppliedCard { - title: string; - lines: string[]; -} - -/** - * ADR-0057 P4 — the `ask` agent's `suggest_builder` structured decline. Result - * envelope `{ status:'build_handoff', handoff:'build', prompt, packageId? }`. - * Lifted so the chat renders an explicit "Open in Builder →" action that opens - * the build surface seeded with `prompt` (never a silent re-route; ADR-0063). - */ -export interface BuilderHandoff { - prompt: string; - packageId?: string; -} - -export function detectBuilderHandoff(result: unknown): BuilderHandoff | undefined { - const obj = parseResultEnvelope(result); - if (!obj || obj.status !== 'build_handoff') return undefined; - const prompt = typeof obj.prompt === 'string' ? obj.prompt.trim() : ''; - if (!prompt) return undefined; - const rawPkg = (obj as { packageId?: unknown }).packageId; - const packageId = typeof rawPkg === 'string' && rawPkg.trim().length > 0 ? rawPkg.trim() : undefined; - return { prompt, ...(packageId ? { packageId } : {}) }; -} - /** * cloud#1658 — the ask agent's `open_record` structured hand-off: the OTHER * ending of a write request. Envelope @@ -1017,401 +427,6 @@ export function detectPackageRemovedResult( return { status: r.status, failed: Array.isArray(r.failed) ? r.failed.length : 0 }; } -export function detectProposedChanges(result: unknown): ProposedChanges | undefined { - const obj = parseResultEnvelope(result); - if (!obj || obj.status !== 'changes_proposed') return undefined; - const str = (v: unknown): string | undefined => (typeof v === 'string' && v ? v : undefined); - const rawChanges = (obj as { changes?: unknown }).changes; - const changes = (Array.isArray(rawChanges) ? rawChanges : []).flatMap((c) => { - const r = c as Record; - if (typeof r?.verb !== 'string' || !r.verb) return []; - return [ - { - verb: r.verb, - ...(str(r.object) ? { object: str(r.object) } : {}), - ...(str(r.field) ? { field: str(r.field) } : {}), - ...(str(r.type) ? { type: str(r.type) } : {}), - ...(str(r.name) ? { name: str(r.name) } : {}), - ...(str(r.details) ? { details: str(r.details) } : {}), - }, - ]; - }); - if (changes.length === 0) return undefined; - const posture = changePostureOf(obj.posture); - const primaryAction = - obj.primaryAction === 'save_draft' || obj.primaryAction === 'confirm' ? obj.primaryAction : undefined; - return { - ...(str(obj.summary) ? { summary: str(obj.summary) } : {}), - changes, - ...(posture ? { posture } : {}), - ...(primaryAction ? { primaryAction } : {}), - }; -} - -/** - * cloud#2924 — the posture as `postureEnvelope` writes it. `mode` and - * `liveRecords` are the declared required pair: a value missing either is not - * a posture, and nothing of it is kept. - */ -function changePostureOf(raw: unknown): ChangePosture | undefined { - const r = recordOf(raw); - if (!r || (r.mode !== 'draft' && r.mode !== 'publish') || !isCount(r.liveRecords)) return undefined; - return { - mode: r.mode, - liveRecords: r.liveRecords, - ...(r.platformPackage === true ? { platformPackage: true as const } : {}), - ...(isCount(r.buildTurnRows) ? { buildTurnRows: r.buildTurnRows } : {}), - }; -} - -/** - * cloud#2924 — `draftState` as `readDraftState` writes it. A state without its - * two counts is not one: the card's 撤销 warning reads `others`, and a guessed - * count would be worse than none. - */ -function draftStateOf(raw: unknown): ChangeDraftState | undefined { - const r = recordOf(raw); - if (!r || !isCount(r.pending) || !isCount(r.others)) return undefined; - const items = (Array.isArray(r.items) ? r.items : []).flatMap((i) => { - const it = recordOf(i); - return it && isText(it.type) && isText(it.name) ? [{ type: it.type, name: it.name }] : []; - }); - return { pending: r.pending, items, others: r.others }; -} - -/** cloud#2924 — `existingRows`: the well-formed lines only; none left is no key. */ -function existingRowsOf(raw: unknown): ExistingRowsLine[] | undefined { - if (!Array.isArray(raw)) return undefined; - const rows = raw.flatMap((l) => { - const r = recordOf(l); - return r && isText(r.object) && isText(r.field) && isText(r.label) && isCount(r.rows) - ? [{ object: r.object, field: r.field, label: r.label, rows: r.rows }] - : []; - }); - return rows.length > 0 ? rows : undefined; -} - -/** cloud#2924 — `appliedCard`: a title is required; its lines are the non-empty strings. */ -function appliedCardOf(raw: unknown): AppliedCard | undefined { - const r = recordOf(raw); - if (!r || !isText(r.title)) return undefined; - const lines = Array.isArray(r.lines) ? r.lines.filter(isText) : []; - return { title: r.title, lines }; -} - -/** - * objectui#5695 — the terminal verdict of a confirm-replay. - * - * When the user approves a 确认修改 card, the runtime re-dispatches the - * proposal deterministically and appends the result under a synthetic - * `replay__` tool-call id (cloud `runApprovedProposalReplay`). The - * envelope is the ordinary authoring envelope — `status:'published'`, - * or `status:'drafted'` optionally stamped `publishFailed:true` + - * `publishOutcome`/`publishError` when the in-turn publish rolled back - * (cloud#1467). Lifted into a dedicated shape so the confirm card can render - * a UI-owned terminal state — the layer a model cannot narrate over. - */ -export interface ReplayOutcome { - kind: 'published' | 'drafted' | 'failed'; - /** Machine verdict of a failed publish (`rejected` / `rolled_back` / `nothing_published`). */ - outcome?: string; - /** First line of `publishError`, for the 未生效 headline. */ - error?: string; - /** Owning package of a drafted outcome, for the inline publish affordance. */ - packageId?: string; - /** - * The replay DISPATCH itself errored (bare `{error: …}` envelope) rather - * than the publish being refused — measured live 2026-08-24: an apply_edit - * replay carrying a blueprint-local object name errored `object "task" not - * found`, after which the MODEL self-repaired with different tool calls - * that succeeded. A dispatch error is therefore only provisionally - * `failed`: the card walk may supersede it with a later successful - * authoring verdict from the same turn (see `detectAuthoringVerdict`), - * so the card never says 未生效 over a change that actually landed. - */ - dispatchError?: boolean; - /** - * objectui#12894 — on a `drafted` outcome only, what cloud#2924's - * `describeLandedChange` stamps after the change landed: the package's - * pending drafts, the existing rows a new field leaves empty, and the - * applied card's title and lines. Each is absent from an older cloud, and - * the card then draws the drafted badge as before. - */ - draftState?: ChangeDraftState; - existingRows?: ExistingRowsLine[]; - appliedCard?: AppliedCard; - /** - * objectui#12968 — on a `drafted` outcome only, the items THIS replay - * drafted (the envelope's `drafted[]`, lifted as {@link detectDraftResult} - * lifts it), so the applied card can preview them. Not `draftState.items`, - * which lists every pending draft of the package. Absent when the envelope - * names none. - */ - items?: Array<{ type: string; name: string }>; -} - -/** - * The drafted `{ type, name }` items of an authoring envelope: its `drafted[]`, - * or the single `type` / `name` pair a one-item stage reports. - */ -function draftedItemsOf(obj: Record): Array<{ type: string; name: string }> { - const items: Array<{ type: string; name: string }> = []; - if (Array.isArray(obj.drafted)) { - for (const d of obj.drafted) { - if (d && typeof d === 'object') { - const { type, name } = d as Record; - if (typeof type === 'string' && typeof name === 'string') items.push({ type, name }); - } - } - } else if (typeof obj.type === 'string' && typeof obj.name === 'string') { - items.push({ type: obj.type, name: obj.name }); - } - return items; -} - -export function detectReplayOutcome( - toolCallId: string | undefined, - result: unknown, -): ReplayOutcome | undefined { - if (!toolCallId || !toolCallId.startsWith('replay_')) return undefined; - const obj = parseResultEnvelope(result); - if (!obj) return undefined; - if (obj.status === 'published') return { kind: 'published' }; - const rawDispatchErr = (obj as { error?: unknown }).error; - if (typeof rawDispatchErr === 'string' && rawDispatchErr.trim() && obj.status === undefined) { - return { - kind: 'failed', - dispatchError: true, - error: rawDispatchErr.trim().split('\n')[0], - }; - } - if (obj.status !== 'drafted') return undefined; - const rawPkg = (obj as { packageId?: unknown }).packageId; - const packageId = - typeof rawPkg === 'string' && rawPkg ? { packageId: rawPkg } : {}; - if ((obj as { publishFailed?: unknown }).publishFailed === true) { - const rawErr = (obj as { publishError?: unknown }).publishError; - const error = - typeof rawErr === 'string' && rawErr.trim() ? rawErr.trim().split('\n')[0] : undefined; - const rawOutcome = (obj as { publishOutcome?: unknown }).publishOutcome; - return { - kind: 'failed', - ...(typeof rawOutcome === 'string' && rawOutcome ? { outcome: rawOutcome } : {}), - ...(error ? { error } : {}), - ...packageId, - }; - } - const draftState = draftStateOf(obj.draftState); - const existingRows = existingRowsOf(obj.existingRows); - const appliedCard = appliedCardOf(obj.appliedCard); - const items = draftedItemsOf(obj); - return { - kind: 'drafted', - ...packageId, - ...(items.length > 0 ? { items } : {}), - ...(draftState ? { draftState } : {}), - ...(existingRows ? { existingRows } : {}), - ...(appliedCard ? { appliedCard } : {}), - }; -} - -/** - * objectui#5695 — classify ANY tool result as an authoring verdict, for the - * confirm card's self-repair supersede: after a replay DISPATCH error, the - * model may land the same change through different tool calls; those results - * carry the ordinary authoring envelope, and the latest one in the turn is - * the truthful terminal state for the card. - */ -export function detectAuthoringVerdict( - result: unknown, -): { kind: 'published' | 'drafted' | 'failed'; packageId?: string } | undefined { - const obj = parseResultEnvelope(result); - if (!obj) return undefined; - if (obj.status === 'published') return { kind: 'published' }; - if (obj.status !== 'drafted') return undefined; - const rawPkg = (obj as { packageId?: unknown }).packageId; - const packageId = typeof rawPkg === 'string' && rawPkg ? { packageId: rawPkg } : {}; - if ((obj as { publishFailed?: unknown }).publishFailed === true) return { kind: 'failed', ...packageId }; - return { kind: 'drafted', ...packageId }; -} - -/** - * objectui#5799 — did this tool result finish a WHOLE-APP build, and for which - * package? Posture-independent on purpose: an auto-publish environment - * rewrites the apply_blueprint envelope to `status:'published'` (keeping - * `drafted[]` + `packageId`), so keying the built-moment transition on - * `draftReview` (drafted-only) missed every staging/cloud build — measured - * live: reopening a built conversation stayed on the full page. - * - * objectui#10109 — an envelope that says `kind: 'edit'` is an INCREMENTAL - * edit (`apply_edit`), never a whole-app build, even when its `drafted[]` - * honestly lists the `app` artifact it re-staged (an `add_object` op merges - * the nav). The producer declares the difference on the envelope, so it is - * read here rather than inferred from which artifact types were staged. - */ -export function detectBuiltAppPackage(result: unknown): string | undefined { - const obj = parseResultEnvelope(result); - if (!obj) return undefined; - if (obj.kind === 'edit') return undefined; - if (obj.status !== 'drafted' && obj.status !== 'published') return undefined; - const pkg = (obj as { packageId?: unknown }).packageId; - if (typeof pkg !== 'string' || !pkg) return undefined; - const drafted = (obj as { drafted?: unknown }).drafted; - const hasApp = - Array.isArray(drafted) && - drafted.some( - (d) => d && typeof d === 'object' && (d as { type?: unknown }).type === 'app', - ); - return hasApp ? pkg : undefined; -} - -export function detectDraftResult(result: unknown): DraftReview | undefined { - const obj = parseResultEnvelope(result); - if (!obj || obj.status !== 'drafted') return undefined; - return draftReviewOf(obj); -} - -/** - * objectstack#25887 — the review of a whole-app build an auto-publish - * environment already published. Its envelope answers `status: 'published'` - * and keeps `drafted[]`, `packageId` and `nextSteps` (see - * {@link detectBuiltAppPackage}), but {@link detectDraftResult} lifts `drafted` - * envelopes only, so a reloaded build, and a replayed one even live (a replay - * emits no `data-build-progress` frames), drew no result card. Never an - * invocation's `draftReview`: nothing about a published build is left to - * publish or review, so it feeds the result card alone. - */ -export function detectPublishedBuildReview(result: unknown): DraftReview | undefined { - const obj = parseResultEnvelope(result); - if (!obj || obj.status !== 'published' || !detectBuiltAppPackage(obj)) return undefined; - return draftReviewOf(obj); -} - -/** - * objectstack#25887 — the one confirm-replay that keeps its draft review: a - * WHOLE-APP build (approving the proposed plan replays its `apply_blueprint`) - * that drafted. It has no confirm card to carry its verdict, so suppressing - * the review (objectui#5695) drew it nowhere; it gets the draft review, and - * with it the result card, that a model-driven build of the same envelope - * gets. A failed publish keeps the suppression (no live Publish over a - * rollback), and so does an incremental edit (`kind: 'edit'`). - */ -function replayedBuildReview( - outcome: ReplayOutcome, - result: unknown, -): DraftReview | undefined { - if (outcome.kind !== 'drafted' || !detectBuiltAppPackage(result)) return undefined; - return detectDraftResult(result); -} - -function draftReviewOf(obj: Record): DraftReview | undefined { - const items = draftedItemsOf(obj); - if (items.length === 0) return undefined; - // The owning package (when the staging tool reported it) lets the chat offer - // a one-click "publish" — POST /packages/:packageId/publish-drafts — so the - // approval gate is reachable from the conversation, not just a deep link into - // the designer. - // - // `autoPublishable` is the backend's lifecycle intent: whole-app builds - // (apply_blueprint) set it so the chat can auto-publish the magic moment; - // incremental edits omit it and stay drafts for explicit review. `failedCount` - // surfaces partial build failures so the UI never hides them. - const failedCount = Array.isArray(obj.failed) ? obj.failed.length : 0; - // ADR-0038 L1 — the build's graph-lint verdict (`verification: {errors, - // warnings}` on apply_blueprint results). Lifted so the chat can render a - // verified/issues chip; absent on older tool output → no chip. - const rawVerification = (obj as { verification?: unknown }).verification; - const verification = - rawVerification && typeof rawVerification === 'object' && - typeof (rawVerification as { errors?: unknown }).errors === 'number' && - typeof (rawVerification as { warnings?: unknown }).warnings === 'number' - ? { - errors: (rawVerification as { errors: number }).errors, - warnings: (rawVerification as { warnings: number }).warnings, - } - : undefined; - // The lint findings themselves (`issues: BuildIssue[]`) ride alongside the - // counts on the same envelope. Lift the user-facing fields so the chip can - // expand into "WHAT is wrong" instead of a bare "N issues". Defensive: only - // well-formed entries with a string message survive. - const rawIssues = (obj as { issues?: unknown }).issues; - const issues = Array.isArray(rawIssues) - ? rawIssues.flatMap((i) => { - const r = i as { severity?: unknown; code?: unknown; message?: unknown; fix?: unknown }; - if (typeof r?.message !== 'string' || !r.message) return []; - return [ - { - severity: r.severity === 'error' ? ('error' as const) : ('warning' as const), - code: typeof r.code === 'string' ? r.code : 'issue', - message: r.message, - ...(typeof r.fix === 'string' && r.fix ? { fix: r.fix } : {}), - }, - ]; - }) - : []; - // Post-build "what's next" steps (apply_blueprint `nextSteps: string[]`). - // Surfaced as a getting-started checklist; only well-formed non-empty strings. - const rawNextSteps = (obj as { nextSteps?: unknown }).nextSteps; - const nextSteps = Array.isArray(rawNextSteps) - ? rawNextSteps.filter((s): s is string => typeof s === 'string' && s.trim().length > 0) - : []; - return { - items, - summary: typeof obj.summary === 'string' ? obj.summary : undefined, - ...(typeof obj.packageId === 'string' && obj.packageId ? { packageId: obj.packageId } : {}), - ...(obj.autoPublishable === true ? { autoPublishable: true } : {}), - ...(failedCount > 0 ? { failedCount } : {}), - ...(nextSteps.length ? { nextSteps } : {}), - // ADR-0045: the build was materialized in-turn (real tables + data, app - // hidden). The canvas then previews the REAL app URL, not the draft overlay. - ...(obj.materialized === true ? { materialized: true } : {}), - ...(typeof obj.appHidden === 'boolean' ? { appHidden: obj.appHidden } : {}), - ...(verification ? { verification } : {}), - ...(issues.length ? { issues } : {}), - // objectui#10109 — the producer's incremental-edit marker rides the draft - // review, so a reader that only sees the review can still tell an edit - // from a whole-app build. - ...(obj.kind === 'edit' ? { kind: 'edit' as const } : {}), - }; -} - -/** snake/kebab artifact name → human title, e.g. `expense_tracker` → `Expense Tracker`. */ -function humanizeArtifactName(name: string): string { - return name - .replace(/[._-]+/g, ' ') - .replace(/\s+/g, ' ') - .trim() - .replace(/\b\w/g, (c) => c.toUpperCase()); -} - -/** - * Synthesize a COMPLETED build-progress summary from a persisted apply_blueprint - * draft envelope. The live "build tree" (`buildProgress`) is driven by transient - * `data-build-progress` stream parts that are never persisted — so a reloaded - * conversation loses the "Built X" panel (ADR-0037/0045). On hydration we - * reconstruct the done-state from the draft result, which IS persisted, so the - * summary + its preview/open affordances survive a refresh. Only whole-app - * builds (a draft set that includes an `app`) get a panel — incremental edits - * keep their draft card but no build tree, matching the live behaviour. An - * edit is known by the producer's `kind: 'edit'`, not by its staged types: it - * can re-stage the `app` artifact too (objectui#10109). - */ -export function buildProgressFromDraftReview( - draft: DraftReview | undefined, -): ChatBuildProgress | undefined { - if (!draft || !Array.isArray(draft.items) || draft.items.length === 0) return undefined; - if (draft.kind === 'edit') return undefined; - const app = draft.items.find((it) => it.type === 'app'); - if (!app) return undefined; - return { - phase: 'done', - appLabel: humanizeArtifactName(app.name), - items: draft.items, - done: draft.items.length, - total: draft.items.length, - }; -} - /** * Lift the chat runtime's approval envelope off a tool part. * @@ -1475,21 +490,6 @@ function extractToolInvocations( p.toolCallId ?? p.id ?? `${p.type ?? 'tool'}-${Math.random().toString(36).slice(2, 8)}`; const result = p.output ?? p.result; const pending = detectPendingApproval(result); - // A confirm-replay result renders as a terminal state on the ORIGINAL - // confirm card, never as its own card — in particular a failed in-turn - // publish must NOT surface as an ordinary draft card with a live Publish - // button (that is exactly the "narrated success over a rollback" the - // card exists to prevent, #5695). So a matched replay suppresses the - // draft-review lift for this invocation — except a drafted whole-app - // build, which has no confirm card and is drawn as a build - // (objectstack#25887, `replayedBuildReview`). - const replayOutcome = detectReplayOutcome(toolCallId, result); - const draftReview = replayOutcome - ? replayedBuildReview(replayOutcome, result) - : detectDraftResult(result); - const proposedPlan = detectProposedPlan(result); - const proposedChanges = detectProposedChanges(result); - const builderHandoff = detectBuilderHandoff(result); const recordHandoff = detectRecordHandoff(result); const recordWrite = detectRecordWrite(result); const answerSource = detectAnswerSource(result); @@ -1525,16 +525,11 @@ function extractToolInvocations( state, approval: liftApproval(p), pendingActionId: pending?.pendingActionId, - draftReview, - proposedPlan, - proposedChanges, - builderHandoff, recordHandoff, recordWrite, answerSource, sampleDataCleanup, packageRemoval, - replayOutcome, } satisfies ChatToolInvocation; }); } @@ -1551,144 +546,6 @@ function extractSources(parts: AnyPart[]): ChatSource[] | undefined { return sources.length > 0 ? sources : undefined; } -/** - * The build-progress frame vocabulary of `@objectstack/spec/ai`, read through - * its TYPES (objectui#11988). Both constants are typed by the spec's own - * declarations, so the compiler refuses a value the spec does not declare and, - * for the phases, requires a row for every phase it does: neither can drift - * from the vocabulary. The spec's runtime `BUILD_PROGRESS_PHASES` is not - * imported: its module does not tree-shake, and a value import of it moved the - * console's eager closure about 27 KB gzipped over budget (a one-time reading - * of `pnpm check:eager-closure` against `fff07fbba`, objectui#11988). The - * type-only import is erased from the published typings, so it asks nothing of - * the package's spec floor. `buildVerify-11988.test.tsx` reads the runtime - * array and pins every member. - */ -const BUILD_FRAME_TYPE: typeof BUILD_PROGRESS_FRAME_TYPE = 'data-build-progress'; -const BUILD_PHASES: Record = { structure: true, data: true, verify: true, done: true }; - -/** - * The part id cloud's post-apply verification loop reports on (cloud PR #2721's - * wire shape, cloud#2172 ruling A). It rides the same `data-build-progress` - * type as the apply_blueprint tree but under its own stable id, so the two - * reconcile side by side on one message (objectui#11988). - */ -const BUILD_VERIFY_PART_ID = 'build-verify'; - -/** - * A frame's phase, read against the spec's closed vocabulary. A value outside - * it is `unknown` — never coerced to a neighbouring phase, which is how a - * finished build used to read as "Building" (objectui#7388). - */ -function readBuildPhase(phase: unknown): ChatBuildProgress['phase'] { - return typeof phase === 'string' && Object.prototype.hasOwnProperty.call(BUILD_PHASES, phase) - ? (phase as BuildProgressPhase) - : 'unknown'; -} - -/** The `data` of the LAST `data-build-progress` part on the message that `pick` keeps. */ -function buildFrame(parts: AnyPart[], pick: (id?: string) => boolean): Record | undefined { - const data = parts.filter((p) => p.type === BUILD_FRAME_TYPE && pick(p.id)).pop()?.data; - return data && typeof data === 'object' ? (data as Record) : undefined; -} - -/** - * The post-apply verification state, from the `build-verify` part: the hop - * the loop is on and the tool it runs, until a `done` frame closes it. - */ -function extractBuildVerify(parts: AnyPart[]): ChatBuildProgress['verify'] { - const d = buildFrame(parts, (id) => id === BUILD_VERIFY_PART_ID); - if (!d) return undefined; - return { - phase: readBuildPhase(d.phase), - ...(typeof d.hop === 'number' ? { hop: d.hop } : {}), - ...(typeof d.tool === 'string' ? { tool: d.tool } : {}), - }; -} - -/** - * Lift the live build TREE from the stream's reconciled `data-build-progress` - * part (emitted by apply_blueprint via `ctx.onProgress`). With a stable id the - * SDK keeps a single, in-place-updated part, so we just read the latest one — - * of the parts that are not the `build-verify` part, which never displaces the - * tree (objectui#11988). - */ -function extractBuildProgress(parts: AnyPart[]): ChatBuildProgress | undefined { - const d = buildFrame(parts, (id) => id !== BUILD_VERIFY_PART_ID); - if (!d) return undefined; - const items = Array.isArray(d.items) - ? (d.items as Array>) - .filter((i) => typeof i?.type === 'string' && typeof i?.name === 'string') - .map((i) => ({ - type: i.type as string, - name: i.name as string, - // The item's display label, when the frame carries one; the panel - // falls back to the machine name without it. - ...(typeof i.label === 'string' && i.label ? { label: i.label } : {}), - })) - : []; - const phase = readBuildPhase(d.phase); - return { - phase, - ...(typeof d.appLabel === 'string' ? { appLabel: d.appLabel } : {}), - items, - done: typeof d.done === 'number' ? d.done : items.length, - total: typeof d.total === 'number' ? d.total : items.length, - // Monotonic emit counter — advances even on keep-alive heartbeats (identical - // content), so the build panel can keep its liveness "live" during long - // quiet seed-generation awaits. Absent on older runtimes. - ...(typeof d.seq === 'number' ? { seq: d.seq } : {}), - }; -} - -/** - * Lift the live blueprint-DESIGN progress from the stream's reconciled - * `data-blueprint-progress` part (emitted by `propose_blueprint` via - * `ctx.onProgress` while it drafts the plan). Same single-reconciled-part - * mechanism as `data-build-progress` — a stable id keeps one in-place-updated - * part, so we read the latest frame (objects accrue across frames). Transient: - * never persisted, so on reload the authoritative `proposedPlan` card (lifted - * from the persisted tool result) is the record instead of this panel. - */ -function extractBlueprintProgress(parts: AnyPart[]): ChatBlueprintProgress | undefined { - const part = parts.filter((p) => p.type === 'data-blueprint-progress').pop(); - const data = part?.data; - if (!data || typeof data !== 'object') return undefined; - const d = data as Record; - const objects = Array.isArray(d.objects) - ? (d.objects as Array>) - .filter((o) => typeof o?.name === 'string') - .map((o) => ({ - name: o.name as string, - ...(typeof o.label === 'string' ? { label: o.label } : {}), - ...(typeof o.fields === 'number' ? { fields: o.fields } : {}), - })) - : []; - // Only `done` is authoritative; anything else (incl. absent) is still designing. - const phase: ChatBlueprintProgress['phase'] = d.phase === 'done' ? 'done' : 'designing'; - let counts: ChatBlueprintProgress['counts']; - if (d.counts && typeof d.counts === 'object') { - const c = d.counts as Record; - const out: { objects?: number; views?: number; dashboards?: number } = {}; - if (typeof c.objects === 'number') out.objects = c.objects; - if (typeof c.views === 'number') out.views = c.views; - if (typeof c.dashboards === 'number') out.dashboards = c.dashboards; - if (Object.keys(out).length > 0) counts = out; - } - return { - phase, - ...(typeof d.summary === 'string' ? { summary: d.summary } : {}), - ...(typeof d.appLabel === 'string' ? { appLabel: d.appLabel } : {}), - ...(typeof d.targetApp === 'string' ? { targetApp: d.targetApp } : {}), - objects, - ...(counts ? { counts } : {}), - // Monotonic emit counter — advances even on keep-alive heartbeats (identical - // content), so the design panel keeps its liveness "live" during the long, - // quiet plan-design await. Absent on older runtimes. - ...(typeof d.seq === 'number' ? { seq: d.seq } : {}), - }; -} - /** * Map a single Vercel AI SDK v6 `UIMessage` to the `ChatMessage` shape that * `` renders. @@ -1707,24 +564,6 @@ export function uiMessageToChatMessage( const tools = extractToolInvocations(parts, { liveTail: opts.streaming }); const legacyTools = Array.isArray(msg.toolInvocations) ? msg.toolInvocations : []; const resolvedTools = tools.length > 0 ? tools : legacyTools; - // The live `data-build-progress` parts are transient (never persisted), so a - // reloaded whole-app build loses its "Built X" panel. Fall back to a summary - // synthesized from the apply_blueprint draft envelope — which IS persisted on - // the tool result — so the panel + its open/preview affordances survive a - // refresh. Re-derived on every map (incl. useObjectChat's round-trip), so it - // cannot be lost the way a one-shot hydration value would. An auto-publish - // environment's `published` envelope is read too (objectstack#25887): a - // replayed build has no live frames, so it is the only tree it gets. - const tree = - extractBuildProgress(parts) ?? - resolvedTools - .map((tool) => - buildProgressFromDraftReview(tool.draftReview ?? detectPublishedBuildReview(tool.result)), - ) - .find((bp): bp is ChatBuildProgress => Boolean(bp)); - // The verification line rides on the tree it verifies (objectui#11988). - const verify = extractBuildVerify(parts); - const buildProgress = tree && verify ? { ...tree, verify } : tree; const recordCitations = extractRecordCitations(parts); return { id: (msg.id ?? `msg-${Math.random().toString(36).slice(2, 8)}`) as string, @@ -1733,11 +572,6 @@ export function uiMessageToChatMessage( reasoning: extractReasoning(parts), toolInvocations: resolvedTools, sources: extractSources(parts), - buildProgress, - // Live blueprint-DESIGN progress (propose_blueprint) — a transient stream - // part like buildProgress. No persisted fallback needed: the `proposedPlan` - // card (from the persisted tool result) is the post-reload record. - blueprintProgress: extractBlueprintProgress(parts), charts: extractCharts(parts, { anchored: typeof msg.content !== 'string' }), // ADR-0160 D9 — the answer's verified record citations, drawn as chips. ...(recordCitations ? { recordCitations } : {}), @@ -1745,34 +579,6 @@ export function uiMessageToChatMessage( }; } -/** - * The plans a later plan in the same build turn replaced, by `toolCallId`. - * - * A turn is everything after a user message up to the next one. The model may - * call `propose_blueprint` several times in one turn, and the runtime builds - * only the newest plan, so the chat draws that one as the turn's plan card and - * every earlier plan of the turn as a completed step. The turn is read across - * messages because stored history keeps one assistant message per step, while - * the live stream keeps the whole turn in one message. A plan from an earlier - * turn is never in the set. - */ -export function supersededPlanIds(messages: readonly ChatMessage[]): ReadonlySet { - const superseded = new Set(); - let newest: string | undefined; - for (const message of messages) { - if (message.role === 'user') { - newest = undefined; - continue; - } - for (const tool of message.toolInvocations ?? []) { - if (!tool.proposedPlan || !tool.toolCallId) continue; - if (newest !== undefined && newest !== tool.toolCallId) superseded.add(newest); - newest = tool.toolCallId; - } - } - return superseded; -} - /** * Map an array of `UIMessage`s. The trailing assistant message gets the * `streaming` flag when `isStreaming` is true (mirrors `useObjectChat`). diff --git a/ui/packages/plugin-chatbot/src/publishHealth.ts b/ui/packages/plugin-chatbot/src/publishHealth.ts index de5bb714054..82302b09379 100644 --- a/ui/packages/plugin-chatbot/src/publishHealth.ts +++ b/ui/packages/plugin-chatbot/src/publishHealth.ts @@ -7,13 +7,13 @@ * * Publish-health extraction, dependency-free so `@object-ui/plugin-chatbot/core` * can serve it to the console shell without the chat UI (objectui#13410). - * `ChatbotEnhanced` re-exports all three names unchanged. + * The package root re-exports both names unchanged. */ /** * ADR-0038 L3 — what a publish actually did at runtime. Hosts extract this - * from the publish-drafts response (`seedApplied` + `probes`) so the chat can - * render a build-health line: "Published" and "actually works" are two + * from the publish-drafts response (`seedApplied` + `probes`) so the publish + * report says it: "Published" and "actually works" are two * separately-verified statements, and the second one must be visible too. */ export interface PublishHealth { @@ -56,17 +56,11 @@ export interface PublishHealthIssue { userMessage?: string; } -/** Structured result of `onPublishDrafts` — richer alternative to a bare boolean. */ -export interface PublishOutcome { - ok: boolean; - health?: PublishHealth; -} - /** * Extract {@link PublishHealth} from a publish-drafts response body (tolerant * of the dispatcher's `{ success, data }` envelope). Shared by the hosts that - * wire `onPublishDrafts` so they all read `seedApplied` + `probes` the same - * way; returns undefined when the server reported neither (older runtimes). + * publish drafts so they all read `seedApplied` + `probes` the same way; + * returns undefined when the server reported neither (older runtimes). */ export function publishHealthFromResponse(payload: unknown): PublishHealth | undefined { const root = (payload ?? {}) as Record; diff --git a/ui/packages/plugin-chatbot/src/tool-state.test.ts b/ui/packages/plugin-chatbot/src/tool-state.test.ts index 1d9d70945a6..010b2f6f31c 100644 --- a/ui/packages/plugin-chatbot/src/tool-state.test.ts +++ b/ui/packages/plugin-chatbot/src/tool-state.test.ts @@ -1,96 +1,33 @@ // Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. // -// #772 — a granular metadata edit that RETURNED a confirm-before-change -// preview (status:'changes_proposed') must read as AWAITING the user, not -// "Completed": the change only commits when they approve on the next turn. +// `getToolState` — the activity chip's state for one tool invocation, read +// from the invocation's own lifecycle state (or, for a legacy invocation that +// carries none, from whether it holds a result or an error). import { describe, it, expect } from 'vitest'; -import { getToolState, isProposalResult } from './ChatbotEnhanced'; +import { getToolState } from './ChatbotEnhanced'; -describe('isProposalResult', () => { - it('detects the confirm-gate preview envelopes (object or JSON string)', () => { - expect(isProposalResult({ status: 'changes_proposed', changes: [] })).toBe(true); - expect(isProposalResult({ status: 'blueprint_proposed', blueprint: {} })).toBe(true); - expect(isProposalResult({ status: 'awaiting_confirmation' })).toBe(true); - expect(isProposalResult('{"status":"changes_proposed"}')).toBe(true); - }); - - // #787 finding B / #2362: the REAL tool.result is the Vercel AI SDK tool - // output shell `{ type:'text', value:'' }`, not a bare object/string. - // isProposalResult must peel that shell (via parseResultEnvelope) or the - // collapsed header reads "Completed" instead of "Awaiting Approval". - it('peels the Vercel {type,value} tool-output envelope', () => { - expect( - isProposalResult({ type: 'text', value: '{"status":"changes_proposed","changes":[]}' }), - ).toBe(true); - expect( - isProposalResult({ type: 'text', value: '{"status":"blueprint_proposed","blueprint":{}}' }), - ).toBe(true); - // A wrapped, genuinely-applied result stays "Completed". - expect(isProposalResult({ type: 'text', value: '{"status":"drafted","drafted":["x"]}' })).toBe( - false, - ); - }); - - it('is false for applied / other results and junk', () => { - expect(isProposalResult({ status: 'drafted', drafted: ['x'] })).toBe(false); - expect(isProposalResult({ ok: true })).toBe(false); - expect(isProposalResult('not json')).toBe(false); - expect(isProposalResult(undefined)).toBe(false); - expect(isProposalResult(null)).toBe(false); - }); -}); - -describe('getToolState — proposed preview reads as awaiting', () => { - it('a returned changes_proposed tool → awaiting (not completed)', () => { +describe('getToolState', () => { + it('a returned tool → completed', () => { expect( getToolState({ toolCallId: 't1', - toolName: 'apply_edit', - result: { status: 'changes_proposed', changes: [{ verb: 'add_field' }] }, - }), - ).toBe('awaiting'); - }); - - it('a returned blueprint_proposed tool → awaiting', () => { - expect( - getToolState({ - toolCallId: 't2', - toolName: 'propose_blueprint', - result: { status: 'blueprint_proposed', blueprint: {} }, - }), - ).toBe('awaiting'); - }); - - it('a returned changes_proposed WRAPPED in the Vercel {type,value} shell → awaiting', () => { - // The exact shape headerState/renderToolDetail receive at runtime (#787 B). - expect( - getToolState({ - toolCallId: 't2b', - toolName: 'apply_edit', - result: { type: 'text', value: '{"status":"changes_proposed","changes":[{"verb":"add_field"}]}' }, - }), - ).toBe('awaiting'); - }); - - it('a genuinely applied (drafted) tool → completed', () => { - expect( - getToolState({ - toolCallId: 't3', - toolName: 'apply_blueprint', - result: { status: 'drafted', drafted: ['customer'] }, + toolName: 'query_records', + result: { records: [] }, }), ).toBe('completed'); }); - it('an errored tool → failed; a running one → running', () => { - expect(getToolState({ toolCallId: 't4', toolName: 'x', errorText: 'boom' })).toBe('failed'); - expect(getToolState({ toolCallId: 't5', toolName: 'x' })).toBe('running'); + it('an errored or denied tool → failed; a running one → running', () => { + expect(getToolState({ toolCallId: 't2', toolName: 'x', errorText: 'boom' })).toBe('failed'); + expect(getToolState({ toolCallId: 't3', toolName: 'x', state: 'output-denied' })).toBe('failed'); + expect(getToolState({ toolCallId: 't4', toolName: 'x' })).toBe('running'); }); - it('an explicit approval-requested state → awaiting', () => { + it('an explicit approval-requested or approval-responded state → awaiting', () => { expect( - getToolState({ toolCallId: 't6', toolName: 'x', state: 'approval-requested', result: undefined }), + getToolState({ toolCallId: 't5', toolName: 'x', state: 'approval-requested', result: undefined }), ).toBe('awaiting'); + expect(getToolState({ toolCallId: 't6', toolName: 'x', state: 'approval-responded' })).toBe('awaiting'); }); }); diff --git a/ui/packages/plugin-chatbot/src/toolResultParsers.ts b/ui/packages/plugin-chatbot/src/toolResultParsers.ts index 9c667345034..ba29ce545c9 100644 --- a/ui/packages/plugin-chatbot/src/toolResultParsers.ts +++ b/ui/packages/plugin-chatbot/src/toolResultParsers.ts @@ -51,7 +51,7 @@ export interface AnyPart { url?: string; href?: string; title?: string; - /** Payload of a Vercel custom data part (`data-*`), e.g. build progress. */ + /** Payload of a Vercel custom data part (`data-*`). */ data?: unknown; } @@ -69,10 +69,9 @@ export interface AnyPart { * peel one layer if present, then fall back to the raw value. Returns the first * candidate that parses to a plain object. * - * Exported so `isProposalResult` (ChatbotEnhanced) shares the exact same - * envelope-peeling logic — otherwise a wrapped `{type:'text', value:'…'}` - * result slips past its `.status` check and the activity chip mis-reads a - * still-pending proposal as "Completed" (#787 finding B / #2362). + * Exported so every result detector shares the exact same envelope-peeling + * logic — otherwise a wrapped `{type:'text', value:'…'}` result slips past a + * detector's `.status` check. */ export function parseResultEnvelope(result: unknown): Record | undefined { const tryParse = (value: unknown): Record | undefined => { diff --git a/ui/packages/plugin-chatbot/src/useObjectChat.ts b/ui/packages/plugin-chatbot/src/useObjectChat.ts index e5a15961113..937f63a65a8 100644 --- a/ui/packages/plugin-chatbot/src/useObjectChat.ts +++ b/ui/packages/plugin-chatbot/src/useObjectChat.ts @@ -24,8 +24,7 @@ import type { SeamChatMessage, SeamToolInvocation } from './chatMessageAdapter'; * In local mode that was true; in API mode it was a cast over values produced * by the RUNTIME mapper, so the declared type was narrower than the values in * exactly the direction that hides capability: anyone rebuilding a message - * field-by-field from its declared type deleted the HITL approval card, the - * "Review N changes" affordance, the proposed-plan card, the build panel and + * field-by-field from its declared type deleted the HITL approval card and * the inline charts, with the compiler agreeing. * * This type is what the survey found to be true of BOTH modes — neither the @@ -46,8 +45,7 @@ import type { SeamChatMessage, SeamToolInvocation } from './chatMessageAdapter'; * `normalizeMessages` before it is ever handed out. Declaring `Date` here * asks every consumer to handle a value that cannot arrive. * - **plus the render-only keys API mode really carries** — - * `buildProgress`, `blueprintProgress`, `charts`, and the HITL / - * draft-review / proposed-plan / builder-handoff extensions on each tool + * `charts`, `recordCitations`, and the HITL approval id on each tool * invocation. * * ⚠️ It is NOT a subtype of `@object-ui/types`' `ChatMessage` (objectui#10018). @@ -1034,8 +1032,8 @@ export function useObjectChat(options: UseObjectChatOptions = {}): UseObjectChat // but the authoring contract does. // // objectui#4424: this used to end in `as OuiChatMessage[]`, and that cast was - // the card. It erased `buildProgress`, `blueprintProgress`, `charts` and - // every HITL / draft-review extension on the tool invocations, because the + // the card. It erased `charts`, `recordCitations` and + // the HITL approval id on the tool invocations, because the // authoring type declares none of them — the values survived only because // nothing downstream rebuilt a message. There is no assertion here now: the // mapper's output IS an `ObjectChatMessage`, so the compiler checks the diff --git a/ui/packages/plugin-form/src/affordanceGrantMap-12082.test.tsx b/ui/packages/plugin-form/src/affordanceGrantMap-12082.test.tsx index 627550a7229..296405d0c65 100644 --- a/ui/packages/plugin-form/src/affordanceGrantMap-12082.test.tsx +++ b/ui/packages/plugin-form/src/affordanceGrantMap-12082.test.tsx @@ -662,7 +662,6 @@ const LIST_VIEW = 'packages/plugin-list/src/ListView.tsx'; const RECORD_PANEL = 'packages/plugin-detail/src/RecordDetailPanel.tsx'; const OBJECT_GANTT = 'packages/plugin-gantt/src/ObjectGantt.tsx'; const MASTER_DETAIL = 'packages/plugin-form/src/MasterDetailForm.tsx'; -const EXCEL_IMPORT_BAR = 'packages/app-shell/src/console/ai/ExcelImportBar.tsx'; const RELATED_LIST = 'packages/plugin-detail/src/RelatedList.tsx'; const RELATED_LIST_BLOCK = 'packages/plugin-detail/src/renderers/record-related-list.tsx'; // Setup's holders sections: each reads its own rows, so every mount (the @@ -902,8 +901,8 @@ const WRITE_SITES: Record = { 'packages/plugin-gantt/src/ObjectGantt.tsx :: ObjectGantt > renderRecordOverlay :: delete': mapped(['recordDelete'], DETAIL_VIEW), // ── plugin-grid ── 'packages/plugin-grid/src/ImportWizard.tsx :: ImportWizard > legacyImport :: create': { - ...mapped(['listImport'], CONSOLE_LIST, 'packages/app-shell/src/views/importTargetFields.ts', EXCEL_IMPORT_BAR), - note: "one site, two mounts: the console list's Import and the AI build panel's spreadsheet import (`ExcelImportBar`) each read the row where they offer Import; HOST_GATED below holds every mount of the wizard to this list", + ...mapped(['listImport'], CONSOLE_LIST, 'packages/app-shell/src/views/importTargetFields.ts'), + note: "the console list's Import reads the row where it offers Import; HOST_GATED below holds every mount of the wizard to this list", } as WriteSite, // The inline-edit saves (objectui#12292): `defaultRowSave` and // `defaultBatchSave` both write through `writeRowGuarded`, the `If-Match` @@ -1236,6 +1235,6 @@ describe('the write census: every write call site sits behind a map row, or says // A derivation that found nothing would pass the pin above over every // tree; this is the site the hand-written list it replaced held. expect(hostGatedSites(mountsBy).map(([component]) => component)).toEqual(expect.arrayContaining(['ImportWizard'])); - expect([...(mountsBy.get('ImportWizard') ?? [])]).toEqual(expect.arrayContaining([CONSOLE_LIST, EXCEL_IMPORT_BAR])); + expect([...(mountsBy.get('ImportWizard') ?? [])]).toEqual(expect.arrayContaining([CONSOLE_LIST])); }); }); diff --git a/ui/packages/plugin-grid/src/index.tsx b/ui/packages/plugin-grid/src/index.tsx index 2c1ea5671c1..a1706b87541 100644 --- a/ui/packages/plugin-grid/src/index.tsx +++ b/ui/packages/plugin-grid/src/index.tsx @@ -394,7 +394,7 @@ ComponentRegistry.register('grid', ObjectGridRenderer, { * the seat's ruling on that card, by the objectui#10393 / objectui#8760 route). * The React export stays (the ruling's words): `ImportWizard` is still exported * from this package, and app-shell mounts it directly (`ObjectView`'s import - * flow, `ExcelImportBar`). + * flow). * * ## What was here, and why it went * diff --git a/ui/scripts/check-hand-rolled-comment-mask.mjs b/ui/scripts/check-hand-rolled-comment-mask.mjs index 9521edbde28..676951f164d 100644 --- a/ui/scripts/check-hand-rolled-comment-mask.mjs +++ b/ui/scripts/check-hand-rolled-comment-mask.mjs @@ -147,8 +147,6 @@ export const CORPUS_FLOOR = 1000; export const DEBT = Object.freeze({ 'packages/components/src/__tests__/empty-base-classes-override-friendly-8525.test.tsx': 'Subject is CSS, not JavaScript. `js-comment-mask.mjs` is graded against a JavaScript parser and its narrowness is a decision, not a gap, so conversion is the WRONG remedy here; paying this off means a CSS-aware reader, or a ruling that the shape is fine where it stands.', - 'packages/i18n/src/__tests__/console-namespace-3546.test.tsx': - 'In class: strips whole-line comments out of a TSX source before a census counts identifier reads. Convertible as-is; outside the file surface objectui#9751 was claimed on.', 'scripts/check-doc-example-shared-reader.mjs': 'In class, and the only carrier here that is a LIVE GATE rather than a test: `canonical()` deletes block comments from expression text before comparing two expressions, so a phantom comment makes two different expressions read as equal -- the fabricating direction. Convertible as-is.', 'scripts/__tests__/console-vite-alias-closure-4925.test.ts': diff --git a/ui/scripts/check-i18n-dead-keys.mjs b/ui/scripts/check-i18n-dead-keys.mjs index 1856ebe6c07..2de813288fe 100644 --- a/ui/scripts/check-i18n-dead-keys.mjs +++ b/ui/scripts/check-i18n-dead-keys.mjs @@ -176,10 +176,11 @@ * the reason is the whole point of deriving the population rather than listing * it. That card made nine of the ten catalogues lazy, so a module that holds a * pack OBJECT and indexes into it no longer has to NAME a pack in its import — - * it asks the registry for whatever is resident. `outboundAgentText.ts` is - * exactly that module and it changed in precisely that way: same dynamic - * `ai?.[key]` read, same four keys kept alive, and it fell straight out of a - * derivation keyed on pack NAMES. ⇒ the class this leg covers is "reaches a + * it asks the registry for whatever is resident. The console's outbound-text + * resolver was exactly that module (until objectstack#37682 retired it with + * the plan cards whose text it sent): same dynamic `ai?.[key]` read, and it + * fell straight out of a derivation keyed on pack NAMES; `flowResponse.ts` + * below reaches its pack the same way. ⇒ the class this leg covers is "reaches a * pack object and indexes into it", ⛔ never "writes a pack's name in an * import"; a widening here is the correct response to a new way of reaching * one, and a bullet quietly disappearing is not. @@ -223,20 +224,6 @@ * is exactly the server-down boot it exists to explain, so it deliberately * does not call `useObjectTranslation` (its own comment says so). It reads * its pack subtree through a local binding. Covered BY DESIGN. - * - `packages/app-shell/src/console/ai/outboundAgentText.ts` — indexes its - * pack subtree DYNAMICALLY (`ai?.[key]`), so NEITHER leg sees the read: no - * dotted key, no property chain, no call site. Its four keys land in - * NEEDS-REVIEW anyway, but only because those property names happen to - * appear as string literals in the `OutboundAgentTextKey` union a few lines - * above them — BY LUCK, NOT BY DESIGN. Do NOT read this file as covered by - * the leg. Replace that union with anything generated and all four keys - * drop to CONFIRMED with a live consumer still reading them. - * ⚠️ Since objectui#7479 it reaches the pack through - * `getLoadedBuiltInLocales()` rather than a static `zh`/`en` import. NOTHING - * about the reading above changed — same dynamic index, same four keys, same - * luck — but the DERIVATION had to be widened to keep seeing it (see the - * alternation above). It is the one importer in this list whose membership - * depends on that widening, which is why it is said here as well as there. * - `packages/plugin-grid/demo/main.tsx` and * `packages/plugin-grid/demo/bulk-actions.tsx` — whole-pack `resources` * wiring only, no per-key property reads: nothing for the leg to see and @@ -263,8 +250,7 @@ * the first argument of the `t()` call each default sits inside, so the AST * pass reads them directly and neither is ever a candidate (measured: both * absent from CONFIRMED and from NEEDS-REVIEW). ⇒ read this bullet as - * covered BY COINCIDENCE, the same tier as `outboundAgentText` above and - * for an unrelated reason. Build either key from a template, or move the + * covered BY COINCIDENCE. Build either key from a template, or move the * default away from its call site, and both go dark to every leg while a * shipping component still renders them — and that edit would read as a * tidy-up. @@ -274,12 +260,12 @@ * import. Two chains, each written straight off the call so the * derivation can follow them: the table tag the active locale reads as * (`resolveBuiltInLanguage`, objectstack#30511) is RUNTIME-indexed (an - * opaque row, class 1 below, like `outboundAgentText`), and the `en` + * opaque row, class 1 below), and the `en` * fallback is spelled in full and resolves to that leaf. It is * a TWO-segment key, under the property-chain leg's three-segment floor, * so that leg is blind to it; the full-key probe sees it only because the * same dotted key is spelled in this file's own comments. ⇒ covered BY - * COINCIDENCE, the same tier as the two bullets above. Nothing is at risk + * COINCIDENCE, the same tier as the bullet above. Nothing is at risk * today for a second, unrelated reason: the record form reads the same key * as a literal `t()` argument, so the AST pass keeps it live. Drop both the * comment spelling and the form's call and this read goes dark while a @@ -355,14 +341,13 @@ * somewhere else going stale (this sentence used to open with one, and it said * three while four were listed): * - * 1. A pack-object reader that indexes DYNAMICALLY — the `outboundAgentText` - * shape above. No dotted key, no property chain, no call site. Measured on - * this checkout, and it corrects the note above: its four keys are demoted - * to NEEDS-REVIEW by CHANGELOG entries and test files that spell them, NOT - * by the neighbouring type union, whose members are bare property names - * (`'planApproveMessage'`) and therefore match neither probe. The luck is - * real, it is not where objectui#6666 recorded it, and nothing holds it in - * place — a CHANGELOG is not a liveness argument. + * 1. A pack-object reader that indexes DYNAMICALLY — the `ai?.[key]` shape + * the outbound-text resolver had (objectui#6666). No dotted key, no + * property chain, no call site. Its keys were demoted to NEEDS-REVIEW + * only by CHANGELOG entries and test files that spelled them, NOT by the + * neighbouring type union, whose members were bare property names and + * therefore matched neither probe — and a CHANGELOG is not a liveness + * argument. * 2. A key built by CONCATENATION (`'console.' + 'objectView.' + 'new'`), or * by a builder shape the key-builder leg does not read: anything but one * returned template literal, and anything that composes the head across @@ -773,7 +758,6 @@ const IMPORTER_SEARCH_DIRS = ['packages', 'apps', 'examples', 'e2e']; */ export const ANALYSED_PACK_OBJECT_IMPORTERS = Object.freeze([ 'packages/app-shell/src/chrome/LoadingScreen.tsx', - 'packages/app-shell/src/console/ai/outboundAgentText.ts', 'packages/plugin-grid/demo/main.tsx', 'packages/plugin-grid/demo/bulk-actions.tsx', 'packages/react/src/utils/nonGridRowCeiling.tsx', From dc257c07017d9dfbf87a8a9eb4f14460498de554 Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 26 Nov 2026 23:49:26 +0000 Subject: [PATCH 2/4] test(studio): drop the noTopBar suite's mock of the deleted copilot module check-vi-mock-specifiers flags a vi.mock whose relative path resolves to nothing; #37579 added it against StudioAiCopilot, which this branch deletes. Co-authored-by: Claude Claude-Session: https://claude.ai/code/session_01Q4EjjMnLQVLzcho6g8WAL3 --- .../studio-design/StudioDesignSurface.noTopBar-37456.test.tsx | 1 - 1 file changed, 1 deletion(-) diff --git a/ui/packages/app-shell/src/views/studio-design/StudioDesignSurface.noTopBar-37456.test.tsx b/ui/packages/app-shell/src/views/studio-design/StudioDesignSurface.noTopBar-37456.test.tsx index 4c1ff4d48f1..082bbb3d1e9 100644 --- a/ui/packages/app-shell/src/views/studio-design/StudioDesignSurface.noTopBar-37456.test.tsx +++ b/ui/packages/app-shell/src/views/studio-design/StudioDesignSurface.noTopBar-37456.test.tsx @@ -53,7 +53,6 @@ vi.mock('sonner', () => ({ })); vi.mock('../../components/SuggestedBindingsPanel', () => ({ SuggestedBindingsPanel: () => null })); vi.mock('../metadata-admin/AccessExplainPanel', () => ({ AccessExplainPanel: () => null })); -vi.mock('./StudioAiCopilot', () => ({ StudioChatDock: () => null })); /** * The changes panel, as a probe: the Pending tab's (`embedded`) draws a Publish From 2f5c6af662e4678d31f1acb7f3f1f0e36dd587a5 Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 27 Nov 2026 00:21:42 +0000 Subject: [PATCH 3/4] chore(changeset): list core, plugin-grid and plugin-form as comment- and test-only patches Co-authored-by: Claude Claude-Session: https://claude.ai/code/session_01Q4EjjMnLQVLzcho6g8WAL3 --- .changeset/37682-retire-build-chat-frontend.md | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/.changeset/37682-retire-build-chat-frontend.md b/.changeset/37682-retire-build-chat-frontend.md index 1131dc9a191..3dcf7d44722 100644 --- a/.changeset/37682-retire-build-chat-frontend.md +++ b/.changeset/37682-retire-build-chat-frontend.md @@ -1,6 +1,9 @@ --- '@object-ui/plugin-chatbot': patch '@object-ui/app-shell': patch +'@object-ui/core': patch +'@object-ui/plugin-grid': patch +'@object-ui/plugin-form': patch --- feat(chatbot)!: the build chat's frontend is retired — the plan, change, build-result and handoff cards, their detectors and the props that fed them are removed @@ -16,6 +19,8 @@ Metadata-protocol: none In `@object-ui/app-shell`, `ConversationsSidebar` no longer takes `includeAskConversations`: the sidebar lists the active agent's conversations. Delete the prop where a host passes it. +`@object-ui/core`, `@object-ui/plugin-grid` and `@object-ui/plugin-form` carry comment and test edits only, which drop references to the deleted build-chat code. They change no behaviour. + ## What leaves, and what to write instead Every name below leaves `@object-ui/plugin-chatbot`; `PublishOutcome` also leaves `@object-ui/plugin-chatbot/core`. `ChatbotEnhancedProps` loses the same 59 props as `FloatingChatbotProps`, and the seam types `SeamToolInvocation` and `SeamChatMessage` lose the same fields as `ChatbotEnhancedToolInvocation` and `ChatbotEnhancedMessage`; the fix for those is the same deletion. From 18cec5f4028a0d9ae642d677152c59c1bb69c41e Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 27 Nov 2026 01:02:55 +0000 Subject: [PATCH 4/4] docs(chatbot): drop the retired build fields from the README and docs page; declare the narrowing MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The plugin-chatbot README (shipped in the tarball) and the docs page still described the build cards and their props. Both changesets now read Clause-② no (narrowing), and the frontend one names ObjectChatMessage. Co-authored-by: Claude Claude-Session: https://claude.ai/code/session_01Q4EjjMnLQVLzcho6g8WAL3 --- .../37682-i18n-retire-build-chat-keys.md | 2 +- .../37682-retire-build-chat-frontend.md | 4 +- .../docs/frontend/plugins/plugin-chatbot.mdx | 44 ++----------------- ui/packages/plugin-chatbot/README.md | 25 +++-------- 4 files changed, 11 insertions(+), 64 deletions(-) diff --git a/.changeset/37682-i18n-retire-build-chat-keys.md b/.changeset/37682-i18n-retire-build-chat-keys.md index cc492e2f67c..75e5cedcccf 100644 --- a/.changeset/37682-i18n-retire-build-chat-keys.md +++ b/.changeset/37682-i18n-retire-build-chat-keys.md @@ -4,7 +4,7 @@ feat(i18n)!: the 280 translation keys `@object-ui/i18n@18.6.0` shipped for the retired build chat are removed -Clause-②: no +Clause-②: no (narrowing) Metadata-protocol: none diff --git a/.changeset/37682-retire-build-chat-frontend.md b/.changeset/37682-retire-build-chat-frontend.md index 3dcf7d44722..9abdebf8973 100644 --- a/.changeset/37682-retire-build-chat-frontend.md +++ b/.changeset/37682-retire-build-chat-frontend.md @@ -8,7 +8,7 @@ feat(chatbot)!: the build chat's frontend is retired — the plan, change, build-result and handoff cards, their detectors and the props that fed them are removed -Clause-②: no +Clause-②: no (narrowing) Metadata-protocol: none @@ -23,7 +23,7 @@ In `@object-ui/app-shell`, `ConversationsSidebar` no longer takes `includeAskCon ## What leaves, and what to write instead -Every name below leaves `@object-ui/plugin-chatbot`; `PublishOutcome` also leaves `@object-ui/plugin-chatbot/core`. `ChatbotEnhancedProps` loses the same 59 props as `FloatingChatbotProps`, and the seam types `SeamToolInvocation` and `SeamChatMessage` lose the same fields as `ChatbotEnhancedToolInvocation` and `ChatbotEnhancedMessage`; the fix for those is the same deletion. +Every name below leaves `@object-ui/plugin-chatbot`; `PublishOutcome` also leaves `@object-ui/plugin-chatbot/core`. `ChatbotEnhancedProps` loses the same 59 props as `FloatingChatbotProps`, and the seam types `SeamToolInvocation` and `SeamChatMessage`, with `ObjectChatMessage` built on them, lose the same fields as `ChatbotEnhancedToolInvocation` and `ChatbotEnhancedMessage`; the fix for those is the same deletion. | FROM | TO | |:--|:--| diff --git a/content/docs/frontend/plugins/plugin-chatbot.mdx b/content/docs/frontend/plugins/plugin-chatbot.mdx index 00e86b86351..eea9b9d48c3 100644 --- a/content/docs/frontend/plugins/plugin-chatbot.mdx +++ b/content/docs/frontend/plugins/plugin-chatbot.mdx @@ -491,7 +491,7 @@ const systemMessage: ChatMessage = { Tool messages represent results from tool invocations during AI streaming. They are generated automatically by the vercel/ai SDK when the backend performs tool calls (e.g., fetching weather, querying a database). The SDK may emit tool messages as well as populate the assistant message's `toolInvocations` array. -By default, `ChatbotEnhanced` renders tool invocations as a compact agent activity summary. Repeated calls are grouped, raw tool names are hidden, and reasoning text is not shown. Use `processVisibility="debug"` for developer/admin views that need the full reasoning panel, raw tool names, parameters, and results. Use `processVisibility="hidden"` to suppress non-interactive activity entirely; approval and draft-review actions remain visible. +By default, `ChatbotEnhanced` renders tool invocations as a compact agent activity summary. Repeated calls are grouped, raw tool names are hidden, and reasoning text is not shown. Use `processVisibility="debug"` for developer/admin views that need the full reasoning panel, raw tool names, parameters, and results. Use `processVisibility="hidden"` to suppress non-interactive activity entirely; approval actions remain visible. In every mode, an answer whose data tools returned a `source` block ends with one collapsed "How this was computed" block: per tool, the object, the filter, the grouping, the aggregations, how many records the figures cover, and whether only the reader's visible records were read. An answer computed through `query_dataset` draws that tool's `provenance` block in the same place instead: the dataset, each metric by its label with its name beside it, the grouping, and the filter the question added (a dataset's own filter is never shown, so no added filter reads as such rather than as all records). It draws that block alone, never the rest of the tool payload. @@ -501,42 +501,6 @@ Each step is named by the locale pack's `chatbot.tool.` entry, a short sentence in the user's language ("List the existing objects"). A tool the pack has no entry for falls back to its name, title-cased. -The AI build conversation's two cards draw only what the build agent's tool -results declare. The plan card (`propose_blueprint`) reads the result's -`planCard`: a chip per field with the format its sample data is held to, a -dashed chip for a field the agent added on its own, the record's name field, -one line per view, the assumptions, the sample data the build will stage, and -how the build will land (`posture`: live at once, or saved as a draft). -A plan whose result says `decision: 'iterate_or_new'` overlaps an app the user -already has (`existingAppOverlap`, by `name` and `label`). Its card draws no -"Build it" button: in its place it asks whether to keep improving that app or -build a separate one, naming the app, and each choice sends its answer as a -chat message (`planExtendExistingMessage(app)` and `planBuildNewAppMessage`, -which the console picks by the conversation's language). The question survives -a reload from server history and from the console's message cache. -The result card (`apply_blueprint`, then a later `verify_build` in the same -turn) reads `checklist`: a passed/total chip, the verified lines in two -columns, and the app and package that "Open app" and "View in Studio" open. -A result without those keys keeps the simpler rows the cards drew before. - -The change card (a `changes_proposed` result) draws what the copilot's tools -say about how a change will land. When the result carries a `posture`, the -card is headed "Change plan · N changes" and draws one row per change: a -symbol for add, change or remove, the kind (field, view, object), the -`object · field` it touches, and its type and parameters in small type. A -change to an app that is live and holds records (`posture.mode: 'draft'`) is -saved as a Studio draft: the card's note says so in amber, and the primary -button reads "Save as draft" when `primaryAction` is `save_draft` (the message -it sends is still `changesConfirmMessage`). Once applied, the card shows the -result's `appliedCard` title and lines, "Review changes and publish" through -`onReviewDrafts(packageId)`, and "Undo" through `onDiscardDrafts(packageId)`. -Undo is meant for `POST /api/v1/packages/:id/discard-drafts`, which discards -every pending draft of the package, so the card asks first whenever other -drafts are pending: it reads `draftState.others` from the result, and the live -count from `fetchPendingDraftCount` when the host provides one. A host without -`onReviewDrafts` keeps the inline Publish button; a result without these keys -draws the card as before. - Use `surface="plain"` for full-page chat workspaces where the surrounding app already provides navigation chrome. The default `surface="card"` remains a better fit for embedded dashboards, side panels, and floating chat windows. @@ -849,10 +813,8 @@ import type { ObjectChatMessage } from '@object-ui/plugin-chatbot' ``` It is the authoring shape plus the render-only keys API mode really carries -(`buildProgress`, `blueprintProgress`, `charts`, and `pendingActionId` / -`draftReview` / `proposedPlan` / `proposedChanges` / `builderHandoff` on each -tool invocation — the approval card, the "Review N changes" affordance, the plan -card, the build panel, the inline charts), with `timestamp` narrowed to `string` +(`charts`, and `pendingActionId` on each tool invocation — the inline charts +and the approval card), with `timestamp` narrowed to `string` because both modes absorb an authored `Date` before emitting. In API mode its tool invocations can also carry the AI SDK's three approval diff --git a/ui/packages/plugin-chatbot/README.md b/ui/packages/plugin-chatbot/README.md index fa72a3001b9..d0eedbb0dba 100644 --- a/ui/packages/plugin-chatbot/README.md +++ b/ui/packages/plugin-chatbot/README.md @@ -124,12 +124,10 @@ neither of the two message contracts nearby, because neither is true of both modes (objectui#4424): - **Not `@object-ui/types`' authoring `ChatMessage`.** In API mode the values - come from the runtime mapper and carry `buildProgress`, `blueprintProgress`, - `charts`, and `pendingActionId` / `draftReview` / `proposedPlan` / - `proposedChanges` / `builderHandoff` on each tool invocation — the approval - card, the "Review N changes" affordance, the plan card, the build panel and - the inline charts. The authoring contract declares none of them, so rebuilding - a message field-by-field from it deletes all of them, and the compiler agrees. + come from the runtime mapper and carry `charts`, and `pendingActionId` on + each tool invocation — the inline charts and the approval card. The + authoring contract declares neither, so rebuilding + a message field-by-field from it deletes both, and the compiler agrees. API mode also produces the AI SDK's three approval states (`'approval-requested'` / `'approval-responded'` / `'output-denied'`), which the authoring contract refuses — they are runtime-only (objectui#10018). @@ -202,18 +200,6 @@ safe side gutters, stays above the mobile bottom navigation area, and hides the FAB while open so the close button in the panel header is the only active dismiss control. -A host that wants to signal a waiting approval outside the chat can pass -`ChatbotEnhanced` the optional `onPlanApprovalPendingChange(pending, count)` -callback. `pending` is `true` while the thread's newest proposal still waits -for the user: a proposed plan that offers "Build it", or a change plan whose -card still offers its confirm button. It is `false` otherwise: no proposal, -the user approved or confirmed it, or its build or confirm landed. `count` is -how many items that proposal asks the user to confirm: the rows of a change -plan, 1 for a proposed plan, 0 when nothing is pending. It fires once on mount -and again on every change of either value. The console uses it to put a -marker on its chat launchers while the chat is closed (objectui#11666), and -Studio's right slot shows the count beside the folded copilot. - During a conversation, the chat surface renders an inline assistant responding indicator while the backend is streaming, keeps message actions quiet until hover/focus, and summarizes backend failures into a compact retryable notice @@ -309,8 +295,7 @@ import { AIElements } from '@object-ui/plugin-chatbot'; `` renders and the mappers below produce. On top of the core `id` / `role` / `content` / `timestamp` / `avatar` / `avatarFallback` fields it carries the streaming and agent-process keys (`streaming`, `toolInvocations`, -`reasoning`, `sources`, `traceId`, `buildProgress`, `blueprintProgress`, -`charts`), all optional. +`reasoning`, `sources`, `traceId`, `charts`), all optional. ```tsx import type { ChatbotEnhancedMessage } from '@object-ui/plugin-chatbot';