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..75e5cedcccf --- /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 (narrowing) +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..9abdebf8973 --- /dev/null +++ b/.changeset/37682-retire-build-chat-frontend.md @@ -0,0 +1,40 @@ +--- +'@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 + +Clause-②: no (narrowing) +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. + +`@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`, with `ObjectChatMessage` built on them, 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/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/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 77cecb41d3a..879f06e79d4 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 092e8596cb6..84f375dad19 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 { MetadataListCreateDialog } from '../metadata-admin/MetadataListCreateDialog'; 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 f15640046fb..b2dc8f7f921 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 0e98aaf8a01..3045cf60798 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.copilotDoors-12894.test.tsx b/ui/packages/app-shell/src/views/studio-design/StudioDesignSurface.copilotDoors-12894.test.tsx deleted file mode 100644 index 08a9d4e82c1..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-menu-overview-pending')).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-menu-overview-pending')).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-menu-overview-pending')).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 36366703ef2..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-menu-overview-pending')).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-menu-overview-pending')).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-menu-overview-pending')).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-menu-overview-pending')).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-menu-overview-pending')).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-menu-overview-pending')).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-menu-overview-pending')).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-menu-overview-pending')).toHaveTextContent('2')); - } finally { - unsubscribe(); - } - }); -}); 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 4b5ef4d6a12..42bfe2074b6 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 { ListFlowCreate } from './__tests__/listFlowCreateHost'; 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 c73d12385ea..cb9aafbcf53 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 6563a0dd012..34627bda852 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 @@ -51,7 +51,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 42b79e4f55e..cb911a23f26 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 e8258f838b5..52201b33f7f 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 top-left rows, the page and its buttons sit under it', async () => { + it('the surface\'s root carries Studio\'s accent: its top-left rows and the page sit under it', async () => { render(); const host = await screen.findByTestId('studio-pillars-host'); const scope = host.closest(ACCENT_SCOPE); @@ -166,7 +158,6 @@ describe('a non-default app theme does not tint Studio (objectstack#37455)', () expect(carriesAccent(scope as Element)).toBe(true); // objectstack#37456 — no top bar: the left column's top rows stand where it was. expect(scope).toContainElement(screen.getByTestId('studio-top-left')); - 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 41d975adbd5..fc15c36983d 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 f55ae7c8338..ab2adc6c2d7 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 63e5cbcbcc7..193a0eca63f 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 }) => ( - -
- ) : ( - - {showsProps ? ( - - )} - {planPending && ( - - )} + + - {copilotShown && onHistoryOpenChange ? ( - - ) : null} - {copilotShown && onWideChange && !overlay ? ( - - ) : null} {onClose ? (
- {/* objectui#12725 — the one right slot: properties OR the copilot. - * The copilot is the same package-scoped build thread the dock held, - * self-gating on the agent catalog as it always has. */} + {/* objectui#12725 — the one right slot: the open item's properties. */} {rightSlot} {/* objectui#11553 — the package-less scope reviews exactly what its diff --git a/ui/packages/app-shell/src/views/studio-design/StudioSurfacePage.tsx b/ui/packages/app-shell/src/views/studio-design/StudioSurfacePage.tsx index ad8c5b76b52..1148ac78620 100644 --- a/ui/packages/app-shell/src/views/studio-design/StudioSurfacePage.tsx +++ b/ui/packages/app-shell/src/views/studio-design/StudioSurfacePage.tsx @@ -28,7 +28,6 @@ import type { useStudioPackageApps, useStudioPackageFacts, useStudioSurfaceScope import type { useStudioSurfaceSave } from './studioSurfaceSave.js'; import type { useStudioChangesSheet, useStudioDraftLedger } from './studioSurfaceDrafts.js'; import type { useStudioPublishAction } from './studioSurfacePublish.js'; -import type { useStudioSurfaceRightSlot } from './studioSurfaceRightSlot.js'; export type StudioSurfacePageProps = Pick< ReturnType, @@ -45,8 +44,7 @@ export type StudioSurfacePageProps = Pick< 'onDraftSaved' | 'publishRefusalFor' | 'shownPendingCount' | 'renderPublishRefusal' > & Pick, 'doPublish'> & - Pick, 'packageApp' | 'publishedApps'> & - Pick, 'setSurfaceLabel'> & { + Pick, 'packageApp' | 'publishedApps'> & { locale: SupportedLocale; shellNavigate: NavigateFunction; /** objectstack#36908 — where the package-not-found state's way out leads. */ @@ -85,7 +83,6 @@ export function StudioSurfacePage({ doPublish, packageApp, publishedApps, - setSurfaceLabel, locale, shellNavigate, notFoundExit, @@ -117,7 +114,6 @@ export function StudioSurfacePage({ publishNonce={publishNonce} onDraftSaved={onDraftSaved} onHeldEditChange={setHeldEdit} - onSurfaceLabelChange={setSurfaceLabel} /> ) : ( @@ -154,7 +150,6 @@ export function StudioSurfacePage({ publishRefusalFor={publishRefusalFor} // objectstack#36904, objectstack#36903 — the object and flow designers' reports, as the pillars' are. onHeldEditChange={setHeldEdit} - onSurfaceLabelChange={setSurfaceLabel} onReviewChanges={() => { setChangesOpen(true); }} 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/studioSurfaceRightSlot.tsx b/ui/packages/app-shell/src/views/studio-design/studioSurfaceRightSlot.tsx index f548d0ec27a..81c7b7b7fa8 100644 --- a/ui/packages/app-shell/src/views/studio-design/studioSurfaceRightSlot.tsx +++ b/ui/packages/app-shell/src/views/studio-design/studioSurfaceRightSlot.tsx @@ -3,26 +3,20 @@ /** * The design surface's right slot and its assistant, moved out of * `StudioDesignSurface.tsx` unchanged by objectstack#37553 (a move-only - * split): where the one right slot is hosted, its shown-or-hidden and - * properties-or-copilot state, `⌘.`, the title row's assistant control, and - * the slot itself with the copilot inside it. + * split): where the one right slot is hosted, its shown-or-hidden state, + * `⌘.`, the title row's toggle, and the slot itself. */ import * as React from 'react'; import { cn, useIsMobile } from '@object-ui/components'; import { PanelRightClose, PanelRightOpen } from 'lucide-react'; -import { StudioChatDock, type StudioCopilotStatus, type StudioSurfaceLabel } from './StudioAiCopilot.js'; import { StudioRightSlot } from './StudioRightSlot.js'; -import { AssistantTopBarButton } from '../../layout/AssistantTopBarButton.js'; -import { ChatDockControlProvider, type ChatDockControl } from '../../layout/chatDockControl.js'; import { matchStudioSlotShortcut, type StudioRightSlotHandle, - type StudioSlotMode, } from './studioRightSlotState.js'; import { DOCK_STUDIO_EXPANDED_STORAGE_KEY, - maximizedDockWidth, readStoredDockExpanded, writeStoredDockExpanded, } from '../../layout/chatDockState.js'; @@ -42,9 +36,7 @@ export function useStudioSurfaceRightSlot({ locale: SupportedLocale; }) { // objectui#12725 — the Studio grid is `[left: nav/tree] [center: canvas] - // [right: ONE slot, properties OR copilot]`. NOT keyed on the async agent - // catalog (that would flip the whole grid after load): on an agent-less env - // the slot holds the properties alone. An injected `aiSlot` (the cloud seam, + // [right: ONE slot, the properties]`. An injected `aiSlot` (the cloud seam, // ADR-0080) keeps the legacy left panel and the pillars' own asides — the // cloud edition migrates on its own schedule. const chatDockMode = !aiSlot; @@ -52,24 +44,14 @@ export function useStudioSurfaceRightSlot({ // in one line under the header, rather than leave the cramped layout to // speak for itself. const isMobile = useIsMobile(); - // objectui#8219 — the Interfaces pillar's open leaf, lifted to the dock so - // the copilot's "discussing" chip reads its display label (objectui#7254). - // Display-only; the agent's context stays URL-derived. Other pillars report - // nothing, so their chip keeps reading `type · name`. - const [surfaceLabel, setSurfaceLabel] = React.useState(null); - // objectui#12725 — the one right slot (`StudioRightSlot`): the open item's - // properties OR the copilot, the maintainer's 「按「右栏二选一」定稿」. Not in - // the package-less scope: its one pillar keeps its own aside, and its build - // thread would be a package's, with no package here to build into - // (objectui#11553). - // objectstack#32615 — nor in a package that is not there (`pkgMissing`): its - // copilot would offer to "edit this app" and write drafts under an id no - // package has. + // properties. Not in the package-less scope: its one pillar keeps its own + // aside (objectui#11553). + // objectstack#32615 — nor in a package that is not there (`pkgMissing`). const slotHost = chatDockMode && packageId !== null && !pkgMissing; - // Shown or hidden from the top bar, remembered per tab under the key the + // Shown or hidden from the title row, remembered per tab under the key the // Studio dock kept its collapse in (#2477 item 2): an author who hid the - // copilot finds the slot hidden. Under `md` the slot overlays the page and + // slot finds it hidden. Under `md` the slot overlays the page and // starts closed — a phone must not open on a panel over the Studio. const [slotOpenStored, setSlotOpenStored] = React.useState(() => readStoredDockExpanded(DOCK_STUDIO_EXPANDED_STORAGE_KEY, true), @@ -87,25 +69,9 @@ export function useStudioSurfaceRightSlot({ }, [isMobile], ); - // The copilot first: nothing is selected yet, and the card's slot opens on - // the conversation. A selection asks for the properties (`showProps`). - const [slotMode, setSlotMode] = React.useState('copilot'); const [slotPropsTarget, setSlotPropsTarget] = React.useState(null); const [slotPropsClaims, setSlotPropsClaims] = React.useState(0); - const [copilotStatus, setCopilotStatus] = React.useState({ - available: false, - planPendingCount: 0, - }); - // objectstack#34610 — the copilot's expand control widens the slot in place - // (it used to navigate to `/ai/build`, losing this page). - const [copilotWide, setCopilotWide] = React.useState(false); - // objectstack#34725 — the copilot's history list, behind the slot header's History button. - const [copilotHistoryOpen, setCopilotHistoryOpen] = React.useState(false); const slotHasProps = slotPropsClaims > 0; - const copilotAvailable = copilotStatus.available; - // What the slot SHOWS: a missing half never shows. - const shownSlotMode: StudioSlotMode = !copilotAvailable ? 'props' : !slotHasProps ? 'copilot' : slotMode; - const slotHasContent = slotHasProps || copilotAvailable; const claimSlotProps = React.useCallback(() => { setSlotPropsClaims((n) => n + 1); return () => setSlotPropsClaims((n) => n - 1); @@ -120,57 +86,28 @@ export function useStudioSurfaceRightSlot({ setSlotOpenRef.current = setSlotOpen; }); const [showSlotProps] = React.useState(() => () => { - setSlotMode('props'); setSlotOpenRef.current(true); }); const slotHandle = React.useMemo( () => slotHost - ? { propsTarget: slotPropsTarget, mode: shownSlotMode, claimProps: claimSlotProps, showProps: showSlotProps } + ? { propsTarget: slotPropsTarget, claimProps: claimSlotProps, showProps: showSlotProps } : null, - [slotHost, slotPropsTarget, shownSlotMode, claimSlotProps, showSlotProps], + [slotHost, slotPropsTarget, claimSlotProps, showSlotProps], ); - // `⌘.` / `Ctrl+.` — a hidden slot opens; a shown one switches its halves. + // `⌘.` / `Ctrl+.` — a hidden slot opens. React.useEffect(() => { if (!slotHost) return; const onKey = (e: KeyboardEvent) => { if (!matchStudioSlotShortcut(e)) return; e.preventDefault(); - if (!slotOpen) { - setSlotOpen(true); - return; - } - if (slotHasProps && copilotAvailable) setSlotMode(shownSlotMode === 'props' ? 'copilot' : 'props'); + if (!slotOpen) setSlotOpen(true); }; document.addEventListener('keydown', onKey); return () => document.removeEventListener('keydown', onKey); - }, [slotHost, slotOpen, setSlotOpen, slotHasProps, copilotAvailable, shownSlotMode]); - // objectstack#34725 — the top-bar robot's handle on the slot: pressed while - // the slot shows; a press hides it, or shows it on the AI assistant. - const openSlotOnCopilot = React.useCallback(() => { - setSlotMode('copilot'); - setSlotOpen(true); - }, [setSlotOpen]); - const slotRobotControl = React.useMemo( - () => ({ - expanded: slotOpen, - fullWindow: copilotWide, - toggle: () => (slotOpen ? setSlotOpen(false) : openSlotOnCopilot()), - open: openSlotOnCopilot, - }), - [slotOpen, copilotWide, setSlotOpen, openSlotOnCopilot], - ); - // objectui#12725 — the title row's right-most icon shows or hides the right - // slot; `⌘.` switches what it shows. objectstack#34725 — with a copilot - // served, that icon is the console top bar's robot (the same component), - // and it opens the slot on the AI assistant. Without one, the panel icon - // stays for the properties. + }, [slotHost, slotOpen, setSlotOpen]); const titleRowAssistant = - !slotHost || !slotHasContent ? null : copilotAvailable ? ( - - - - ) : ( + !slotHost || !slotHasProps ? null : ( - -
-
- ) : ( - <> - {onReview || onPublish || onPreview || onDiscard ? ( -
- {onReview ? ( - - ) : onPublish ? ( - - ) : null} - {onPreview ? ( - - ) : null} - {onDiscard ? ( - - ) : null} -
- ) : null} - {discard?.phase === 'failed' ? ( - - {t('chatbot.changes.undoFailed', { defaultValue: 'Undo failed' })} - {discard.error ? {discard.error} : null} - - ) : null} - - )} -
- ); -} - -/** - * True when this tool is the build agent's "propose a plan" step - * (`propose_blueprint`). Matched by name so we can recognise it even when its - * result did NOT parse into a structured `proposedPlan` — the case that used to - * leave the user with a bare "reply 确认 to build" text and no button. - */ -function isBuildProposalTool(tool: ChatbotEnhancedToolInvocation): boolean { - return tool.toolName === 'propose_blueprint'; -} - -/** - * An invocation as the message list draws it. `planSuperseded` marks a plan a - * later plan in the same build turn replaced (`supersededPlanIds`): its - * `proposedPlan` is withheld, so it draws as a completed step, not as a plan - * card and not as the unstructured confirm card below. - */ -type RenderedToolInvocation = ChatbotEnhancedToolInvocation & { planSuperseded?: true }; - -function withoutSupersededPlan( - tool: ChatbotEnhancedToolInvocation, - superseded: ReadonlySet, -): RenderedToolInvocation { - if (!tool.proposedPlan || !superseded.has(tool.toolCallId)) return tool; - return { ...tool, proposedPlan: undefined, planSuperseded: true }; -} - -/** - * A COMPLETED propose_blueprint whose result the detector could not turn into a - * rich `proposedPlan` card (e.g. the model returned a thin/oddly-shaped envelope, - * or proposed in prose). We still owe the user an explicit confirm gate, so the - * detailed body renders a minimal "ready to build — Build it / Adjust" card - * instead of collapsing the step into a chip and forcing them to guess the magic - * "确认" phrase. Only the finished, non-error state qualifies: a running proposal - * keeps its live timer, an errored one keeps its error card. - */ -function isUnstructuredBuildProposal(tool: RenderedToolInvocation): boolean { - return ( - isBuildProposalTool(tool) && - getToolState(tool) === 'completed' && - !tool.proposedPlan && - !tool.planSuperseded && - !tool.proposedChanges && - !tool.draftReview?.items.length - ); -} - -/** - * Phrases (Chinese + English, case-insensitive) that mark a plan `assumption` as - * a business rule the build will NOT implement THIS turn — it is explicitly left - * for a later flow/permission/approval pass. These read as "…will be added - * later" / "…需要后续单独补权限" rather than a design note about what the build - * already does, and the user must not mistake them for delivered behaviour. - * - * Kept deliberately conservative: only an explicit deferral marker matches. A - * neutral design note (e.g. "设备通过所属客户建立归属关系") has none of these and - * stays a normal assumption. Anchored on forward-looking / "not yet" cues, not on - * the mere mention of "flow" or "permission" (a built rule can mention those too). - */ -const DEFERRED_ASSUMPTION_MARKERS: readonly string[] = [ - // Chinese deferral cues. - '待补', - '后续', // covers 后续 / 需要后续 / 后续单独 / 后续配置 - '将在', - '稍后', - '暂不', - '暂未', - '尚未', - '确认后一起补', - '一起补', - '另行', // 另行配置 / 另行补充 - '日后', - // English deferral cues (matched lowercase). - 'not yet', - 'will be implemented', - 'will be added', - 'to be added', - 'to be implemented', - 'later', - 'deferred', - 'follow-up', - 'follow up', - 'future', - 'subsequent', - 'coming soon', - 'tbd', -]; - -/** - * Splits a plan's `assumptions` into ordinary design notes vs. business rules the - * build is explicitly deferring ("待补 / Not yet built"). Pure + side-effect-free - * so it is unit-tested directly; the card renders the two groups distinctly so a - * user can tell "already built" from "still to come" at a glance (improvement 2). - * - * Order within each group is preserved. A blank/whitespace assumption is dropped. - */ -export function classifyAssumptions(assumptions: readonly string[]): { - designNotes: string[]; - deferred: string[]; -} { - const designNotes: string[] = []; - const deferred: string[] = []; - for (const raw of assumptions) { - if (typeof raw !== 'string') continue; - const text = raw.trim(); - if (!text) continue; - const haystack = text.toLowerCase(); - if (DEFERRED_ASSUMPTION_MARKERS.some((m) => haystack.includes(m))) { - deferred.push(text); - } else { - designNotes.push(text); - } - } - return { designNotes, deferred }; -} - -function shouldRenderDetailedTool(tool: RenderedToolInvocation): boolean { - const state = getToolState(tool); - return ( - state === 'awaiting' || - state === 'failed' || - Boolean(tool.pendingActionId) || - Boolean(tool.draftReview?.items.length) || - // The pre-build "Proposed plan" card lives in the detailed tool body; route - // a propose_blueprint result there instead of collapsing it into a chip. - Boolean(tool.proposedPlan) || - Boolean(tool.proposedChanges) || - // ADR-0057 P4 — the "Open in Builder →" handoff lives in the detailed body. - Boolean(tool.builderHandoff) || - Boolean(tool.recordHandoff) || - // A completed propose_blueprint that produced NO structured plan still needs - // the detailed body — that's where the fallback "Build it" confirm gate - // renders so the user is never left guessing the confirmation phrase. - isUnstructuredBuildProposal(tool) - ); -} - -function getToolStateRank(state: ToolSummaryState): number { - switch (state) { - case 'failed': - return 4; - case 'awaiting': - return 3; - case 'running': - return 2; - case 'completed': - return 1; - } -} - -/** - * The conversation store persists tool-call-only assistant turns with an - * internal placeholder as their text ("(called todo_write, propose_blueprint)" - * / "(tool call)" / "(no content)"). On re-hydration that placeholder used to - * render as a normal prose bubble — internal jargon spliced into the thread - * (#772). Detect it so the renderer can collapse it to a quiet activity note. - */ -function isToolCallPlaceholder(content: string): boolean { - return /^\((?:called [^)]*|tool call|no content)\)$/.test(content.trim()); -} - -/** One run of an assistant answer: a slice of its text, or the charts drawn at one point. */ -type AnswerBlock = - | { kind: 'text'; text: string } - | { kind: 'charts'; charts: ChatChart[] }; - -/** - * objectui#13492 — an assistant answer in the order the stream produced it: - * the text up to each chart's `textOffset`, the chart, then the text after. - * The mapper used to flatten every text part into one `content` and every - * `data-chart` part into one trailing `charts[]` block, so a chart the model - * drew first still landed below six paragraphs of analysis. - * - * A chart without an offset (a host-built message, the legacy string-content - * shape) or with one past the text's end trails all of it, which is exactly - * the old layout. Charts at the same offset share one block, and a slice that - * is only whitespace is dropped rather than painted as an empty answer box. - */ -function layoutAnswer(content: string, charts: ChatChart[] | undefined): AnswerBlock[] { - const placed = (charts ?? []) - .map((chart, order) => ({ - chart, - order, - at: - typeof chart.textOffset === 'number' && Number.isFinite(chart.textOffset) - ? Math.min(Math.max(chart.textOffset, 0), content.length) - : content.length, - })) - .sort((a, b) => a.at - b.at || a.order - b.order); - const blocks: AnswerBlock[] = []; - let cursor = 0; - for (const { chart, at } of placed) { - if (at > cursor) { - const text = content.slice(cursor, at); - if (text.trim().length > 0) blocks.push({ kind: 'text', text }); - cursor = at; - } - const last = blocks[blocks.length - 1]; - if (last?.kind === 'charts') last.charts.push(chart); - else blocks.push({ kind: 'charts', charts: [chart] }); - } - const rest = content.slice(cursor); - if (rest.trim().length > 0) blocks.push({ kind: 'text', text: rest }); - return blocks; -} - -/** The charts drawn at one point of an assistant answer, each through the SDUI ``. */ -function AnswerCharts({ charts }: { charts: ChatChart[] }) { - return ( -
- {charts.map((chart, i) => ( -
- {chart.title ? ( -
- {chart.title} -
- ) : null} - -
- ))} -
- ); -} - -/** - * The "1 object · 1 view · 1 dashboard" strip under a proposed plan / a live - * design panel, localized (objectui#7254). - * - * It was assembled by string concatenation with an English `+ 's'` plural, so - * it read as English inside an otherwise Chinese conversation AND could only - * ever be right for the two-form languages. Each noun is a plural FAMILY (base - * key + `_one`): i18next asks `Intl.PluralRules` for the one suffix the active - * language needs and lands on the base key for every category a pack does not - * enumerate, so `ru` (few/many) and `ar` (two/few/many/zero) stay in their own - * language instead of falling through to English — the rule - * `all-locales-key-parity.test.ts` states for plural families. - * - * Returned as a hook-bound formatter because both call sites live in different - * components (the proposed-plan card body and `BlueprintProgressPanel`), and - * two hand-rolled copies is how they drifted in the first place. - */ -function useMetadataCountBits(): (counts: { - objects?: number; - views?: number; - dashboards?: number; - seedData?: number; -}) => string[] { - const { t } = useObjectTranslation(); - return React.useCallback( - (counts) => { - const bits: string[] = []; - if (counts?.objects) - bits.push( - t('chatbot.plan.countObjects', { - count: counts.objects, - defaultValue: '{{count}} objects', - }), - ); - if (counts?.views) - bits.push( - t('chatbot.plan.countViews', { count: counts.views, defaultValue: '{{count}} views' }), - ); - if (counts?.dashboards) - bits.push( - t('chatbot.plan.countDashboards', { - count: counts.dashboards, - defaultValue: '{{count}} dashboards', - }), - ); - if (counts?.seedData) - bits.push(t('chatbot.plan.countSeedData', { defaultValue: 'sample data' })); - return bits; - }, - [t], - ); -} - -/** - * objectui#11658 — the extend-mode scope chip's text ("Adding to existing app: - * APP"), shared by the proposed-plan card and `BlueprintProgressPanel`. - * - * The chip names the target app by its display label, resolved by the host - * (`resolveAppLabel`), never by the machine name the plan carries — that name - * moves to the chip's tooltip. The sentence is the locale pack's - * `chatbot.plan.extendTarget`, so a zh user no longer reads the English literal - * the component used to default to. A host `planExtendLabel` still wins, in the - * `PREFIX "APP"` shape it always rendered. - */ -function useExtendChip( - override: string | undefined, - resolveAppLabel: ((appName: string) => string | undefined) | undefined, -): (targetApp: string) => string { - const { t } = useObjectTranslation(); - return React.useCallback( - (targetApp: string) => { - const app = resolveAppLabel?.(targetApp) || targetApp; - if (override) return `${override} "${app}"`; - return t('chatbot.plan.extendTarget', { app, defaultValue: 'Adding to existing app: {{app}}' }); - }, - [t, override, resolveAppLabel], - ); -} - -/** - * objectstack#27480 — the extend-or-new question a `decision: 'iterate_or_new'` - * plan asks, drawn in place of the plan card's "Build it" gate. The plan - * overlaps an app the user already has, so one click on "Build it" could build - * a duplicate of it; the card asks instead, and each choice sends its answer - * as a chat message (`onChoose`), the same channel the user would type into. - * - * The app is named by the envelope's `label`, else by the host's - * `resolveAppLabel`, else by its machine name. An overlap that names no app - * gets the question without a name and a reply hint, not a one-click - * "keep improving" that could not say which app it means. - * - * `mode`: `choose` draws the two choices; `reply` (the host wired no message - * sending) draws the reply hint; `settled` (a build already ran after this - * question) draws the question alone. - */ -function IterateOrNewQuestion({ - iterateOrNew, - resolveAppLabel, - mode, - onChoose, - disabled, - extendMessage, - buildNewMessage, -}: { - iterateOrNew: NonNullable; - resolveAppLabel: ((appName: string) => string | undefined) | undefined; - mode: 'choose' | 'reply' | 'settled'; - onChoose: (message: string) => void; - disabled: boolean; - extendMessage: (app: string) => string; - buildNewMessage: string; -}) { - const { t } = useObjectTranslation(); - const { app } = iterateOrNew; - const appName = app ? app.label || resolveAppLabel?.(app.name) || app.name : undefined; - const question = appName - ? t('chatbot.plan.iterateOrNew.question', { - app: appName, - defaultValue: 'This overlaps "{{app}}", an app you already have. Keep improving it, or build a separate app?', - }) - : t('chatbot.plan.iterateOrNew.questionUnnamed', { - defaultValue: 'This overlaps an app you already have. Keep improving that app, or build a separate one?', - }); - const choiceClass = - 'inline-flex h-7 items-center rounded-md border bg-background px-3 text-xs font-medium hover:bg-accent disabled:cursor-not-allowed disabled:opacity-50'; - return ( -
- - - {question} - - {mode === 'choose' && appName ? ( -
- - -
- ) : mode === 'settled' ? null : ( - - {t('chatbot.plan.iterateOrNew.replyHint', { defaultValue: 'Reply to say which.' })} - - )} -
+/** The charts drawn at one point of an assistant answer, each through the SDUI ``. */ +function AnswerCharts({ charts }: { charts: ChatChart[] }) { + return ( +
+ {charts.map((chart, i) => ( +
+ {chart.title ? ( +
+ {chart.title} +
+ ) : null} + +
+ ))} +
); } @@ -2585,143 +1111,6 @@ function summarizeTools( }); } -/** - * ADR-0038 L3 — the build-health line under a Published badge. Reads the - * publish's `seedApplied` + runtime-probe results and answers the question - * the badge alone can't: did the published app actually work when exercised? - * Renders nothing without health data (older hosts return a bare boolean). - */ -function PublishHealthLine({ health }: { health: PublishHealth | undefined }) { - // objectstack#32984 — the line's own words come from the pack, as count - // families (`chatbot.build.health.*`). A finding speaks on the line only - // through its producer's customer sentence (`issues[].userMessage`, ruling - // B: the producer writes it). Agent text (`message`, `fix`) and the seed - // loader's engine text (`seedError`) never do: without a `userMessage` the - // line says the generic sentence the draft-issues block says, and that text - // folds under the same "Technical details". - const { t } = useObjectTranslation(); - if (!health) return null; - // `defaultValue` is the English a provider-less host reads; with a pack, - // i18next picks the family's slot for `count` and never consults it. - const en = (count: number, one: string, other: string): string => (count === 1 ? one : other); - const issues = health.issues ?? []; - const errors = issues.filter((i) => i.severity === 'error'); - const seedFailed = health.seedFailed === true || !!health.seedError; - const checked = health.checked; - const probesRan = !!checked && checked.seeds + checked.views + checked.widgets > 0; - const okParts: string[] = []; - if (typeof health.seededRows === 'number' && health.seededRows > 0 && !seedFailed) { - const count = health.seededRows; - okParts.push( - t('chatbot.build.health.sampleRowsLive', { - count, - defaultValue: en(count, '{{count}} sample row live', '{{count}} sample rows live'), - }), - ); - } - if (probesRan && errors.length === 0) { - const planes: string[] = []; - const { views, widgets, seeds } = checked!; - if (views > 0) { - planes.push(t('chatbot.build.health.views', { count: views, defaultValue: en(views, '{{count}} view', '{{count}} views') })); - } - if (widgets > 0) { - planes.push( - t('chatbot.build.health.widgets', { count: widgets, defaultValue: en(widgets, '{{count}} widget', '{{count}} widgets') }), - ); - } - if (seeds > 0) { - planes.push( - t('chatbot.build.health.seeds', { - count: seeds, - defaultValue: en(seeds, '{{count}} sample data set', '{{count}} sample data sets'), - }), - ); - } - if (planes.length) { - okParts.push(t('chatbot.build.health.verified', { checks: planes.join(' · '), defaultValue: '{{checks}} verified' })); - } - } - if (okParts.length === 0 && !seedFailed && issues.length === 0) return null; - // Errors first, as the line always listed them. - const ordered = [...errors, ...issues.filter((i) => i.severity !== 'error')]; - const voiced = ordered.filter((i) => i.userMessage); - // One generic sentence speaks for every finding its producer left without a - // customer sentence, chosen by the whole set as the draft-issues block does. - const unvoiced = issues.some((i) => !i.userMessage); - const details = [ - ...(health.seedError ? [health.seedError] : []), - ...ordered.map((i) => (i.fix ? `${i.message} — ${i.fix}` : i.message)), - ]; - return ( -
- {okParts.length > 0 ? ( -
- - {okParts.join(' · ')} -
- ) : null} - {seedFailed ? ( -
- - {t('chatbot.build.health.seedFailed', { defaultValue: 'Sample data failed to load.' })} -
- ) : null} - {voiced.map((i, idx) => ( -
- {i.severity === 'error' ? ( - - ) : ( - - )} - {i.userMessage} -
- ))} - {unvoiced ? ( -
0 ? 'text-red-600' : 'text-amber-600')} - data-testid="publish-health-summary" - > - {errors.length > 0 ? ( - - ) : ( - - )} - - {errors.length > 0 - ? t('chatbot.build.issuesSummary', { - defaultValue: - 'Some parts of this build need fixing before it is ready. Reply "fix the problems" and the assistant will repair them.', - }) - : t('chatbot.build.warningsSummary', { - defaultValue: - 'The build is ready, with a few things worth checking. Ask the assistant what they are if you want to improve them.', - })} - -
- ) : null} - {details.length > 0 ? ( -
- - {t('chatbot.build.issuesDetails', { defaultValue: 'Technical details' })} - -
    - {details.map((text, idx) => ( -
  • - {text} -
  • - ))} -
-
- ) : null} -
- ); -} - const ChatbotEnhanced = React.forwardRef( ( { @@ -2769,31 +1158,6 @@ const ChatbotEnhanced = React.forwardRef( toolDenyLabel = 'Deny', toolDenyReason = 'User denied the operation', toolDecisions, - onReviewDraft, - toolReviewLabel = (n) => `Review ${n} change${n === 1 ? '' : 's'}`, - onPublishDrafts, - publishFromShellBar = false, - onReviewDrafts, - onDiscardDrafts, - onOpenBuiltApp, - openBuiltAppLabel = 'Open app', - onDesignBuiltApp, - designBuiltAppLabel = 'Design in Studio', - getArtifactAction, - onPreviewDraftApp, - previewDraftLabel = 'Preview', - onPreviewDraft, - onDraftArtifacts, - onBuildMaterialized, - onBuildResult, - onPlanApprovalPendingChange, - publishDraftsLabel = 'Publish', - publishedLabel = 'Published', - verifiedLabel = 'Verified', - nextStepsLabel = "What's next", - planTitleLabel = 'Proposed plan', - builderHandoffTitleLabel = 'Build this in the Builder', - builderHandoffOpenLabel = 'Open in Builder →', recordHandoffTitleLabel = 'Open this record', recordHandoffOpenLabel = 'Open record →', onOpenRecordForm, @@ -2827,44 +1191,10 @@ const ChatbotEnhanced = React.forwardRef( packageRemovalRemovedLabel = 'The package was deleted.', packageRemovalPartialLabel = (failed) => `The package was partly deleted: ${failed} ${failed === 1 ? 'item was' : 'items were'} not removed.`, - builderHandoffSupersededTitle = 'A newer request is available', - onOpenBuilder, onOpenRecord, onOpenList, - planExtendLabel, - resolveAppLabel, - resolveObjectLabel, - resolveFieldLabel, - resolveFieldTypeLabel, - planQuestionsLabel = 'Confirm before building', - planAssumptionsLabel = 'Assumptions', - planDeferredLabel = 'Not yet built', - planApproveHintLabel = 'Reply to approve or adjust this plan.', - planApproveLabel = 'Build it', - planAdjustLabel = 'Adjust', - planBuiltLabel = 'Built', - planBuildingLabel = 'Building…', - planReadyLabel = 'The plan is ready. Build it now, or tell me what to adjust.', - planApproveMessage = 'Looks good — build it as proposed.', - planApproveDefaultsMessage = 'Build it with your best assumptions; use sensible defaults for the open questions.', - planAnswerMessage = (question: string, option: string) => `For "${question}", go with: ${option}.`, - planExtendExistingMessage = (app: string) => `Keep improving "${app}" instead of building a new app.`, - planBuildNewAppMessage = 'Build a separate, new app.', - changesTitleLabel = 'Confirm changes', - changesConfirmedLabel = 'Confirmed', - changesConfirmLabel = 'Confirm', - changesConfirmHintLabel = 'Reply to confirm or adjust this change.', - changesConfirmMessage = 'Confirm — apply the change you just proposed.', - changeVerbLabels = DEFAULT_CHANGE_VERB_LABELS, - changesApplyingLabel = 'Applying…', - changesAppliedLabel = 'Applied', - changesDraftedLabel = 'Saved as draft', - changesFailedLabel = 'Not applied', surfaceContextLabel, surfaceContextTitle, - fetchPendingDraftCount, - subscribeMetadataRefresh, - autoPublishDrafts = false, processVisibility = 'summary', surface = 'card', ...props @@ -2882,14 +1212,6 @@ const ChatbotEnhanced = React.forwardRef( // re-render while the error sits in state). const restoredErrorRef = React.useRef(null); - // The localized "N objects · N views · N dashboards" strip, shared with - // `BlueprintProgressPanel` so the plan card and the live design panel can - // not word the same counts differently (objectui#7254). - const countBitsOf = useMetadataCountBits(); - // objectui#11658 — the extend-mode scope chip, shared with - // `BlueprintProgressPanel` so both name the target app the same way. - const extendChip = useExtendChip(planExtendLabel, resolveAppLabel); - // objectui#7254 — the pack lookup for every string this component owns. // `useSafeTranslate` is provider-safe: with no I18nProvider (tests, // standalone hosts) each call returns the English fallback passed beside @@ -2900,24 +1222,10 @@ const ChatbotEnhanced = React.forwardRef( // never success wording. Borrowed from the inbox's status label so the // badge and the card say the same words. const heldForApprovalLabel = tt('aiApprovals.statusHeld', 'Waiting for approval'); - // objectui#12724 — the plan card's section heads and its 等待确认 chip. - const planAwaitingLabel = tt('chatbot.plan.awaitingConfirm', 'Awaiting confirmation'); // objectstack#32984 — a message typed during a running turn waits here. const queuedLabel = tt('chatbot.composer.queued', 'Sends when the current reply finishes'); const queuedCancelLabel = tt('chatbot.composer.queuedCancel', 'Cancel'); - const changeLabelResolvers = React.useMemo( - () => ({ object: resolveObjectLabel, field: resolveFieldLabel, fieldType: resolveFieldTypeLabel }), - [resolveObjectLabel, resolveFieldLabel, resolveFieldTypeLabel], - ); - // objectstack#32984 — the issues chip spoke English in every locale. const { t: tCount, language: composerLanguage } = useObjectTranslation(); - const buildIssuesCountLabel = (count: number): string => - tCount('chatbot.build.issuesCount', { count, defaultValue: '{{count}} to fix' }); - const planObjectsLabel = tt('chatbot.plan.objectsAndFields', 'Objects and fields'); - const planViewsLabel = tt('chatbot.plan.views', 'Views'); - // objectui#12894 — the change card's primary action when the envelope says - // the change will be saved as a draft (`primaryAction: 'save_draft'`). - const saveDraftLabel = tt('chatbot.changes.saveDraft', 'Save as draft'); // Resolve localizable strings once. Precedence is host `labels` prop -> // locale pack -> the English default this component always shipped, so a @@ -2976,10 +1284,6 @@ const ChatbotEnhanced = React.forwardRef( connectionWaiting: labels?.connectionWaiting ?? 'Waiting for server…', connectionStalledLabel: labels?.connectionStalledLabel ?? 'Still working…', connectionOfflineLabel: labels?.connectionOfflineLabel ?? 'Connection lost — reconnecting…', - designingPlanLabel: labels?.designingPlanLabel ?? 'Designing your app…', - // `?? DEFAULT_DESIGNING_PLAN_HINTS` (not `||`) so a caller can pass `[]` - // to deliberately disable the rotation while keeping the lead-in label. - designingPlanHints: labels?.designingPlanHints ?? DEFAULT_DESIGNING_PLAN_HINTS, }), [labels, tt], ); @@ -3000,307 +1304,6 @@ const ChatbotEnhanced = React.forwardRef( [L], ); - // Draft tool calls this chat has published (auto or via the manual button), - // so each card flips from a "Publish" button to a "Published" state instead - // of leaving a stale, now-meaningless button. Keyed by the draft's - // `toolCallId`, NOT its packageId: publishing a package promotes the drafts - // PENDING AT THAT MOMENT, but a later edit into the same package is a new, - // still-pending draft — it must NOT inherit the earlier build's "Published" - // badge (that would falsely tell the user an unpublished change is live). - const [publishedToolCalls, setPublishedToolCalls] = React.useState>( - () => new Set(), - ); - // ADR-0038 L3 — per published card, what the publish actually did at - // runtime (rows seeded, probes run, findings). Rendered under the - // Published badge as the build-health line. - const [publishHealthByToolCall, setPublishHealthByToolCall] = React.useState< - ReadonlyMap - >(() => new Map()); - - // Live publish-state (panel-as-source-of-truth, made literal): the server's - // CURRENT pending-draft count per package, when the host wires - // `fetchPendingDraftCount`. The in-memory `publishedToolCalls` snapshot - // above is an optimistic overlay for THIS session; this map is what keeps a - // RELOADED conversation honest — published work shows "Published" (count - // 0), and a package that gained new drafts offers Publish again, no matter - // which session staged them. - const [pendingByPackage, setPendingByPackage] = React.useState< - ReadonlyMap - >(() => new Map()); - const pendingFetchedRef = React.useRef>(new Set()); - // Every package a draft card on screen is bound to — what a metadata - // pulse re-reads. - const pendingPackagesRef = React.useRef>(new Set()); - const refreshPendingCount = React.useCallback( - async (packageId: string) => { - if (!fetchPendingDraftCount) return; - try { - const count = await fetchPendingDraftCount(packageId); - setPendingByPackage((prev) => { - if (prev.get(packageId) === count) return prev; - const next = new Map(prev); - next.set(packageId, count); - return next; - }); - } catch { - // Leave the package unknown — the card falls back to the - // in-memory snapshot rather than guessing. - } - }, - [fetchPendingDraftCount], - ); - // Resolve the live count as draft cards appear (incl. on mount for - // reloaded conversations). Keyed by the card's toolCallId — a NEW build - // into an already-seen package must refresh that package's count, or the - // older card would keep claiming "Published" while drafts are pending. - // Waits for the turn to finish so a mid-build fetch doesn't race the - // still-staging drafts. - React.useEffect(() => { - if (!fetchPendingDraftCount || isLoading) return; - const due = new Set(); - for (const message of messages) { - for (const tool of message.toolInvocations ?? []) { - const pkg = tool.draftReview?.packageId; - const key = tool.toolCallId; - if (pkg && key && !pendingFetchedRef.current.has(key)) { - pendingFetchedRef.current.add(key); - pendingPackagesRef.current.add(pkg); - due.add(pkg); - } - } - } - for (const pkg of due) void refreshPendingCount(pkg); - }, [messages, isLoading, fetchPendingDraftCount, refreshPendingCount]); - // A publish this card did not run (the chat banner, Studio, another - // card's package) changes the server's count without touching this - // component; the host's metadata pulse is the one signal that it did. - // Subscribed once per host subscriber, not per render; the pulse re-reads - // the same source the first fetch used. - React.useEffect(() => { - if (!subscribeMetadataRefresh || !fetchPendingDraftCount) return; - return subscribeMetadataRefresh(() => { - for (const pkg of pendingPackagesRef.current) void refreshPendingCount(pkg); - }); - }, [subscribeMetadataRefresh, fetchPendingDraftCount, refreshPendingCount]); - // Publish a package's drafts and reflect success on exactly the cards that - // were pending for it at publish time. The host's onPublishDrafts returns - // `false` / `{ok:false}` on failure (and surfaces its own error); any other - // outcome (incl. void) counts as success. A structured outcome may carry - // `health` (seedApplied + runtime probes) for the health line. - const handlePublishDrafts = React.useCallback( - async (packageId: string) => { - if (!onPublishDrafts) return; - // Snapshot the on-screen draft cards this publish will promote, BEFORE - // awaiting — later edits into the same package won't be in this set. - const promoted: string[] = []; - for (const message of messages) { - for (const tool of message.toolInvocations ?? []) { - if (tool.draftReview?.packageId === packageId && tool.toolCallId) { - promoted.push(tool.toolCallId); - } - } - } - const res = await onPublishDrafts(packageId); - const outcome: PublishOutcome | undefined = - res && typeof res === 'object' ? (res as PublishOutcome) : undefined; - const ok = outcome ? outcome.ok !== false : res !== false; - if (ok && promoted.length > 0) { - setPublishedToolCalls((prev) => { - const next = new Set(prev); - for (const id of promoted) next.add(id); - return next; - }); - const health = outcome?.health; - if (health) { - setPublishHealthByToolCall((prev) => { - const next = new Map(prev); - for (const id of promoted) next.set(id, health); - return next; - }); - } - } - // Re-read the server's pending count so every card bound to this - // package reflects the post-publish truth (0 on success; unchanged - // on failure — the button stays). - void refreshPendingCount(packageId); - }, - [onPublishDrafts, messages, refreshPendingCount], - ); - - // objectui#12894 — 撤销 on the applied card of a change saved as a draft - // (cloud#2924). The door the host wires (`discard-drafts`) discards EVERY - // pending draft of the package, so the card asks before it runs whenever it - // cannot show that only this change is pending. Per card, keyed by the - // proposal's toolCallId; UI-owned like `confirmPendingIds`. - const [discardByToolCall, setDiscardByToolCall] = React.useState< - ReadonlyMap - >(() => new Map()); - const setDiscardState = React.useCallback( - (toolCallId: string, state: DraftDiscardState | undefined) => { - setDiscardByToolCall((prev) => { - const next = new Map(prev); - if (state) next.set(toolCallId, state); - else next.delete(toolCallId); - return next; - }); - }, - [], - ); - const runDiscardDrafts = React.useCallback( - async (toolCallId: string, packageId: string) => { - if (!onDiscardDrafts) return; - setDiscardState(toolCallId, { phase: 'running' }); - try { - const res = await onDiscardDrafts(packageId); - const outcome = res && typeof res === 'object' ? res : undefined; - const ok = outcome ? outcome.ok !== false : res !== false; - setDiscardState( - toolCallId, - ok ? { phase: 'done' } : { phase: 'failed', ...(outcome?.error ? { error: outcome.error } : {}) }, - ); - } catch (e) { - const message = e instanceof Error ? e.message : typeof e === 'string' ? e : ''; - setDiscardState(toolCallId, { phase: 'failed', ...(message ? { error: message } : {}) }); - } - // Every card bound to this package reads the post-discard count. - void refreshPendingCount(packageId); - }, - [onDiscardDrafts, setDiscardState, refreshPendingCount], - ); - // The click on 撤销: run at once only when the drafts pending are this - // change's alone. The snapshot is `draftState` (read when the change - // landed); the host's live count, when it gives one, wins over it — a - // later change in the same conversation stages more drafts into the same - // package, and the snapshot on this older card cannot know that. - const requestDiscardDrafts = React.useCallback( - async ( - toolCallId: string, - packageId: string, - draftState: ReplayOutcome['draftState'], - ) => { - if (!onDiscardDrafts) return; - let others = draftState?.others; - let total = draftState?.pending; - if (fetchPendingDraftCount) { - setDiscardState(toolCallId, { phase: 'running' }); - try { - const live = await fetchPendingDraftCount(packageId); - if (typeof live === 'number' && Number.isInteger(live) && live >= 0) { - total = live; - others = draftState ? Math.max(0, live - (draftState.pending - draftState.others)) : undefined; - } - } catch { - // Unreadable: the snapshot stands. - } - } - if (others === 0) { - await runDiscardDrafts(toolCallId, packageId); - return; - } - setDiscardState(toolCallId, { - phase: 'confirm', - ...(others !== undefined ? { others } : {}), - ...(total !== undefined ? { total } : {}), - }); - }, - [onDiscardDrafts, fetchPendingDraftCount, runDiscardDrafts, setDiscardState], - ); - - // Auto-publish "magic moment": when the environment enables autoPublishDrafts - // and a WHOLE-APP build finishes (the backend marks it `autoPublishable`), - // fire the same publish-drafts call the manual button uses — objects go live - // and seed data loads, so the user lands on a populated, running app instead - // of hunting for Publish. Incremental edits are NOT auto-published: they omit - // `autoPublishable` and stay drafts for explicit review (a destructive edit - // must never go live silently). Drafts already on screen when the chat mounts - // are seeded as "seen" so reopening a conversation never republishes prior - // work; only NEW builds fire, each at most once, after streaming completes. - // - // Dedup is keyed by the draft tool's `toolCallId`, NOT its packageId: every - // build is a distinct tool call and several can target the SAME workspace - // package in one session. Keying by packageId would publish it only once and - // silently leave later builds staged. Keyed by toolCallId, each new build - // publishes its package once (publish-drafts only promotes rows still - // pending, so re-publishing a package is safe). - const autoPublishedRef = React.useRef>(new Set()); - const autoPublishSeededRef = React.useRef(false); - React.useEffect(() => { - const builds: Array<{ key: string; packageId: string }> = []; - for (const message of messages) { - for (const tool of message.toolInvocations ?? []) { - const dr = tool.draftReview; - if (dr?.autoPublishable && dr.packageId && tool.toolCallId && dr.items.length > 0) { - builds.push({ key: tool.toolCallId, packageId: dr.packageId }); - } - } - } - if (!autoPublishSeededRef.current) { - autoPublishSeededRef.current = true; - for (const b of builds) autoPublishedRef.current.add(b.key); - return; - } - // Wait for the turn to finish so we publish the complete build once. - if (!autoPublishDrafts || !onPublishDrafts || isLoading) return; - const fresh = builds.filter((b) => !autoPublishedRef.current.has(b.key)); - if (fresh.length === 0) return; - for (const b of fresh) autoPublishedRef.current.add(b.key); - // One publish per distinct package, even if a turn made several build calls. - for (const pkg of [...new Set(fresh.map((b) => b.packageId))]) void handlePublishDrafts(pkg); - }, [messages, isLoading, autoPublishDrafts, onPublishDrafts, handlePublishDrafts]); - - // ADR-0037 Live Canvas: surface every AI-authored draft artifact to the - // host as it lands — both the streaming build tree's items and drafted - // envelopes. Deduped cumulatively; the callback fires only when the set - // actually grows, so hosts can refresh a preview pane without storms. - const draftArtifactKeysRef = React.useRef>(new Set()); - React.useEffect(() => { - if (!onDraftArtifacts) return; - const artifacts = new Map(); - // The preview pane routes on the app's PACKAGE id (ADR-0048), not its - // name — take it from the draft set that includes the app. - let appSegment: string | undefined; - for (const message of messages) { - for (const item of message.buildProgress?.items ?? []) { - if (item?.type && item?.name) artifacts.set(`${item.type}:${item.name}`, item); - } - for (const tool of message.toolInvocations ?? []) { - const dr = tool.draftReview; - for (const item of dr?.items ?? []) { - if (item?.type && item?.name) artifacts.set(`${item.type}:${item.name}`, item); - } - if (dr?.packageId && dr.items?.some((i) => i.type === 'app')) appSegment = dr.packageId; - } - } - const seen = draftArtifactKeysRef.current; - let grew = false; - for (const key of artifacts.keys()) { - if (!seen.has(key)) { - seen.add(key); - grew = true; - } - } - if (grew) onDraftArtifacts([...artifacts.values()], appSegment); - }, [messages, onDraftArtifacts]); - - // ADR-0045: announce materialized builds (real app live, unlisted) so the - // host flips its canvas from the draft overlay to the real app URL. Once - // per build (keyed by toolCallId), including on conversation reload — - // a reopened materialized build should still preview the real app. - const materializedKeysRef = React.useRef>(new Set()); - React.useEffect(() => { - if (!onBuildMaterialized) return; - for (const message of messages) { - for (const tool of message.toolInvocations ?? []) { - const dr = tool.draftReview; - if (!dr?.materialized || !tool.toolCallId) continue; - const app = dr.items.find((i) => i.type === 'app'); - if (!app || materializedKeysRef.current.has(tool.toolCallId)) continue; - materializedKeysRef.current.add(tool.toolCallId); - onBuildMaterialized(app.name, dr.packageId ? { appSegment: dr.packageId } : undefined); - } - } - }, [messages, onBuildMaterialized]); - /** * The thread's stick-to-bottom controls, reached from OUTSIDE the * `` subtree (the composer and the cards live beside it, so @@ -3341,10 +1344,6 @@ const ChatbotEnhanced = React.forwardRef( // clears any prior send-failure restore guard. lastSubmittedRef.current = text; restoredErrorRef.current = null; - // A newer send supersedes any pending approve as "the last send" — an - // unsent failure of THIS message must not roll back a plan card whose - // approval already reached the server (#2627). - lastApprovedPlanIdRef.current = null; onSendMessage?.(text, files); followThreadToBottom(); }, @@ -3456,7 +1455,6 @@ const ChatbotEnhanced = React.forwardRef( const handleSuggestionClick = React.useCallback( (text: string) => { - lastApprovedPlanIdRef.current = null; // Not typed by the user — nothing to restore if this send is rejected // (see the send-failure effect below). lastSubmittedRef.current = ''; @@ -3466,95 +1464,7 @@ const ChatbotEnhanced = React.forwardRef( [onSendMessage, followThreadToBottom] ); - // The "Proposed plan" card's one-click confirm gate. Approving sends a plain - // chat message — the same channel the user would type into — so the agent - // proceeds to apply_blueprint. When the plan still carries open questions, - // approval explicitly authorizes sensible defaults so a click never silently - // drops them. const promptInputWrapRef = React.useRef(null); - // Optimistic per-card feedback (#2627): the approval's visible effect (a - // new user bubble + a streaming turn) lands at the BOTTOM of the thread — - // outside the viewport when the plan card is scrolled into view — so the - // card itself looked untouched for the ~10s until apply_blueprint started - // and users clicked again. Flip the clicked card to a 「已确认」 badge - // immediately; every later state (building / built / failed) derives from - // the message stream (`resolvePlanBuildStates`). A send that never left the - // client (rate limit / offline) rolls the flip back so the buttons return. - // - // objectstack#32984 — keyed to the number of tool invocations in the thread - // when the user clicked, so a click AFTER a failed attempt reads 已确认 - // again, and only an attempt that started after the click speaks over it. - const [approvedPlanIds, setApprovedPlanIds] = React.useState>( - () => new Map(), - ); - const toolInvocationCount = React.useMemo( - () => messages.reduce((n, m) => n + (m.toolInvocations?.length ?? 0), 0), - [messages], - ); - const lastApprovedPlanIdRef = React.useRef(null); - const handlePlanApprove = React.useCallback( - (hasOpenQuestions: boolean, toolCallId?: string) => { - // Canned approval text, not the user's typing — see `handleSubmit`. - lastSubmittedRef.current = ''; - if (toolCallId) { - lastApprovedPlanIdRef.current = toolCallId; - setApprovedPlanIds((prev) => { - const next = new Map(prev); - next.set(toolCallId, toolInvocationCount); - return next; - }); - } - onSendMessage?.(hasOpenQuestions ? planApproveDefaultsMessage : planApproveMessage); - followThreadToBottom(); - }, - [onSendMessage, planApproveMessage, planApproveDefaultsMessage, followThreadToBottom, toolInvocationCount] - ); - // objectui#5695 — same optimistic pattern for the 确认修改 card: flip it to - // an "Applying…" badge the moment the approval is sent (double-click guard + - // immediate feedback); the durable terminal state derives from the replay - // envelope in the message stream (replayOutcomeByProposalId). A send that - // never left the client rolls the flip back so the buttons return. - const [confirmPendingIds, setConfirmPendingIds] = React.useState>( - () => new Set(), - ); - const lastConfirmedChangeIdRef = React.useRef(null); - // objectui#7253 — cards whose confirm was refused by the AI quota guardrail - // (429), keyed to the refusal that blocked them. UI-owned and terminal for - // this mount: the refusal never reached the server, so no message-stream - // envelope will ever speak for it, and the paywall does not lift on a retry. - // The error is KEPT (not just a flag) so the card's next step still reads - // correctly after `error` clears — the user typing again must not silently - // strip the reason off a card that is still blocked. - const [quotaBlockedChanges, setQuotaBlockedChanges] = React.useState< - ReadonlyMap - >(() => new Map()); - const handleChangesConfirm = React.useCallback( - (toolCallId?: string) => { - // Canned confirmation text, not the user's typing — see `handleSubmit`. - lastSubmittedRef.current = ''; - if (toolCallId) { - lastConfirmedChangeIdRef.current = toolCallId; - setConfirmPendingIds((prev) => { - const next = new Set(prev); - next.add(toolCallId); - return next; - }); - } - onSendMessage?.(changesConfirmMessage); - followThreadToBottom(); - }, - [onSendMessage, changesConfirmMessage, followThreadToBottom], - ); - - // "Adjust" doesn't send anything — it just drops the cursor into the input so - // the user can describe the change in their own words. - const handlePlanAdjust = React.useCallback(() => { - const textarea = promptInputWrapRef.current?.querySelector('textarea'); - if (textarea) { - textarea.focus(); - textarea.scrollIntoView({ block: 'nearest' }); - } - }, []); // Restore the composer text when a send was REJECTED before reaching the // model (rate-limit / network — `notSent`). The composer's own form.reset @@ -3565,339 +1475,36 @@ const ChatbotEnhanced = React.forwardRef( if (!error || !isUnsentSendError(error)) return; if (restoredErrorRef.current === error) return; restoredErrorRef.current = error; - // The approval message never left the client — roll the optimistic - // "Building…" badge back so the Build-it button returns (#2627). - if (lastApprovedPlanIdRef.current) { - const failedId = lastApprovedPlanIdRef.current; - lastApprovedPlanIdRef.current = null; - setApprovedPlanIds((prev) => { - if (!prev.has(failedId)) return prev; - const next = new Map(prev); - next.delete(failedId); - return next; - }); - } - // Same rollback for an unsent 确认修改 approval (objectui#5695) — with one - // split (objectui#7253): a QUOTA refusal is not a retry, so the card must - // not quietly re-offer the buttons that just failed. Returning them is - // right for a transient failure (rate limit, offline) and a dead end for a - // paywall — the user clicks Confirm again and hits the same 429, with the - // card still reading "awaiting approval". A quota refusal parks the card - // in an explicit blocked state carrying the next step instead. - if (lastConfirmedChangeIdRef.current) { - const failedId = lastConfirmedChangeIdRef.current; - lastConfirmedChangeIdRef.current = null; - setConfirmPendingIds((prev) => { - if (!prev.has(failedId)) return prev; - const next = new Set(prev); - next.delete(failedId); - return next; - }); - if (parseAiQuotaError(error)) { - setQuotaBlockedChanges((prev) => { - if (prev.has(failedId)) return prev; - const next = new Map(prev); - next.set(failedId, error); - return next; - }); - } - } // What is restored is what was NOT sent, never an older delivered prompt. // On its own the composer knows only text the user TYPED here: // `lastSubmittedRef` is written by `handleSubmit` alone and cleared by - // every card-driven send (a chip, a plan or changes card), because those + // every card-driven send (a suggestion chip), because those // send a canned message — leaving the ref stale refilled the composer // with the user's PREVIOUS prompt, a message that had already been // delivered and answered, reading as "resend this" (objectui#7253). // A host that held the message itself names it as `unsentText` // (objectstack#33562), and that text is restored too, whichever way it // was sent: what the composer last submitted may be only part of it, - // and a suggestion chip's text the host held for a create that then - // failed is the message that was not sent, not a stale one. - const text = unsentText ?? lastSubmittedRef.current; - if (!text) return; - const textarea = promptInputWrapRef.current?.querySelector('textarea'); - if (textarea && textarea.value.trim() === '') { - textarea.value = text; - // Nudge the auto-grow sizing + any onInputChange listener. - textarea.dispatchEvent(new Event('input', { bubbles: true })); - textarea.focus(); - } - }, [error, unsentText]); - - const handleCopy = React.useCallback((message: ChatbotEnhancedMessage) => { - void navigator.clipboard?.writeText(message.content); - setCopiedId(message.id); - window.setTimeout(() => setCopiedId((prev) => (prev === message.id ? null : prev)), 1500); - }, []); - - // issue #432: a "Proposed plan" card whose build has already run must not - // keep offering an active "Build it" — clicking it re-sent the approval and - // re-triggered the entire build. A plan is "built" once an `apply_blueprint` - // tool invocation appears AFTER it in the conversation. Keyed on `toolName` - // (not the rich `draftReview`, which a reloaded conversation strips), so the - // done-state survives a refresh. Positional so a later, not-yet-built plan - // (e.g. after "make it simpler") keeps its live button. - // - // objectui#8343 — the name alone is NOT enough. When the user didn't say the - // magic "直接搭建", `apply_blueprint` hits its own confirm gate and returns - // `{status:'awaiting_confirmation'}`: it built nothing and is itself waiting - // for the user. Counting that as a build collapsed the plan card to the inert - // 已搭建 badge and took its "Build it" button with it, while the - // apply_blueprint card has no button of its own — the turn was left with - // nothing to click and the only way out was guessing "确认" into the composer. - // So a build only counts when the invocation is not a confirm-gate preview, - // the same fact `getToolState` already reads to say "Awaiting Approval". - // - // objectstack#32984 — and an invocation that is not a preview is still not - // a build until it SAYS it built (`resolvePlanBuildStates`): a running one - // reads 正在搭建…, a refused one 未搭建成功. Running and built both keep the - // #432 guard (no live Build it); a failed one gives the button back. - const planBuildStates = React.useMemo( - () => resolvePlanBuildStates(messages, { turnLive: isLoading, approvedAt: approvedPlanIds }), - [messages, isLoading, approvedPlanIds], - ); - const planBuildStateOf = (toolCallId: string | undefined): PlanBuildState => - (toolCallId ? planBuildStates.get(toolCallId) : undefined) ?? 'pending'; - // Built, building and confirmed replace the buttons (the #432 guard: no - // second Build it while one is asked for or running); failed shows its - // badge BESIDE them, so the user can ask again. - const planBuildSettledOrMoving = (state: PlanBuildState): boolean => - state === 'built' || state === 'building' || state === 'confirmed'; - const planConfirmedLabel = tt('chatbot.plan.confirmed', 'Confirmed'); - const planBuildFailedLabel = tt('chatbot.plan.buildFailed', 'Not built — nothing was created'); - const renderPlanBuildBadge = (state: PlanBuildState): React.ReactNode => { - switch (state) { - case 'built': - return ( - - - {planBuiltLabel} - - ); - case 'building': - return ( - - - {planBuildingLabel} - - ); - case 'confirmed': - return ( - - - {planConfirmedLabel} - - ); - case 'failed': - return ( - - - {planBuildFailedLabel} - - ); - default: - return null; - } - }; - - // #2458 UX#5 — only the LATEST "Open in Builder →" handoff card stays - // actionable; older cards carry a now-stale prompt and go inert, so a thread - // that accumulated several can't re-fire an outdated request. Derived from - // message order (not click state), so it survives the navigation the button - // triggers and the pane remount that follows. - const latestHandoffToolCallId = React.useMemo(() => { - let latest: string | undefined; - for (const message of messages) { - for (const tool of message.toolInvocations ?? []) { - if (tool.builderHandoff && tool.toolCallId) latest = tool.toolCallId; - } - } - return latest; - }, [messages]); - - // A granular 确认修改 card collapses to a static 已确认 badge once the change - // has been applied — i.e. a LATER invocation of the SAME tool committed (no - // longer a changes_proposed preview). Positional + per-tool so an earlier - // confirmed change doesn't silence a later still-pending one. - // - // objectui#8343 — "no longer a preview" was inferred from the ABSENCE of the - // rich `proposedChanges` card, which is a stricter thing: that detector also - // needs ≥1 parseable change row. So a later same-tool call that WAS a preview - // but produced no card (an empty `changes:[]`, an `awaiting_confirmation`) - // silently counted as the commit and settled the pending card — the same - // defect the plan cards' build reading had above. Read the preview fact directly instead. - const confirmedChangeIds = React.useMemo(() => { - const ids = new Set(); - const proposals: Array<{ id: string; toolName: string; order: number }> = []; - const lastCommitByTool = new Map(); - let order = 0; - for (const message of messages) { - for (const tool of message.toolInvocations ?? []) { - if (tool.proposedChanges && tool.toolCallId) { - proposals.push({ id: tool.toolCallId, toolName: tool.toolName ?? '', order }); - } else if (tool.toolName && !isProposalResult(tool.result)) { - lastCommitByTool.set(tool.toolName, order); - } - order += 1; - } - } - for (const p of proposals) { - const commit = lastCommitByTool.get(p.toolName); - if (commit !== undefined && commit > p.order) ids.add(p.id); - } - return ids; - }, [messages]); - - // objectui#5695 — correlate each confirm-replay result back to the 确认修改 - // card it replays, so the card carries a UI-owned terminal state (已生效 / - // 已暂存为草稿 / 未生效) instead of going dark after the click. A replay - // re-dispatches the SAME tool, so the match is "latest earlier proposal of - // the same tool" — the same positional+per-tool convention as - // `confirmedChangeIds` above. A replay invocation still awaiting its result - // marks the card 'applying'; later replays of the same card overwrite - // earlier ones (an adjusted-and-reconfirmed change reports its LAST run). - // - // Self-repair supersede (measured live 2026-08-24): a replay whose DISPATCH - // errored (`dispatchError`) may be followed, in the same turn, by the model - // landing the change through different tool calls. Any LATER non-replay - // invocation whose result parses as an authoring verdict overrides the - // provisional failure — the card must never say 未生效 over a change that - // actually landed (that would be the original bug, mirrored). - const replayOutcomeByProposalId = React.useMemo(() => { - const byId = new Map< - string, - NonNullable | { kind: 'applying' } - >(); - const dispatchErrorTargets = new Map(); // proposalId → replay order - const proposals: Array<{ id: string; toolName: string; order: number }> = []; - let order = 0; - for (const message of messages) { - for (const tool of message.toolInvocations ?? []) { - if (tool.proposedChanges && tool.toolCallId) { - proposals.push({ id: tool.toolCallId, toolName: tool.toolName ?? '', order }); - dispatchErrorTargets.delete(tool.toolCallId); - } else if (tool.toolCallId?.startsWith('replay_')) { - let target: { id: string } | undefined; - for (const p of proposals) { - if (p.order < order && p.toolName === (tool.toolName ?? '')) target = p; - } - if (target) { - if (tool.replayOutcome) { - byId.set(target.id, tool.replayOutcome); - if (tool.replayOutcome.dispatchError) dispatchErrorTargets.set(target.id, order); - else dispatchErrorTargets.delete(target.id); - } else if (tool.result === undefined && !tool.errorText) { - byId.set(target.id, { kind: 'applying' }); - } - } - } else if (tool.result !== undefined && dispatchErrorTargets.size > 0) { - const verdict = detectAuthoringVerdict(tool.result); - if (verdict) { - for (const [pid, replayOrder] of dispatchErrorTargets) { - if (order > replayOrder) byId.set(pid, verdict); - } - } - } - order += 1; - } - } - return byId; - }, [messages]); - - // objectui#10925 — the proposed-plan card's actions (Build it, Adjust and - // the one-click answer chips) wait until no turn is in flight. The card - // renders as soon as `propose_blueprint` returns, but the proposing turn - // keeps streaming after that (a `todo_write`, the closing prose), and the - // server stores each of those steps as it goes. A Build it clicked in that - // window sent the next turn while the previous one was still being stored, - // and the stored history interleaved the two turns. - // - // The signal is `isLoading`, the same one that turns the composer's send - // into a stop button. It falls only once the response stream has been - // read to its end. The cloud agent loop (`streamChatWithTools`) stores the - // turn's final reply before it writes `finish`; that is the server's - // ordering, read once for this card, and nothing in this repo re-checks - // it. A message's own `streaming` flag is derived from `isLoading` - // (`uiMessagesToChatMessages` sets it on the trailing assistant message - // only), so it would miss two windows that overlap turns the same way: - // the `submitted` phase before the first chunk, and a newer turn - // streaming below an older plan card. - const planActionsLocked = isLoading; - - // objectui#11666 — is this thread's newest proposed plan still waiting for - // the user? Read off the SAME producer the plan card's header and body read - // (`resolveProposalCardState`, objectui#7254), so the host's mirror can - // never disagree with the card: `pending` is exactly the state that renders - // "Build it". The newest plan card is the one awaiting — an older card a - // newer proposal followed is superseded by it. Computed on every render - // rather than memoised: it is one pass over the tool calls, and its inputs - // are memo results whose identity this must not key on (Commandment #10). - // - // objectstack#25943 — a change plan (the copilot's 「修改方案 · N 项」 card) - // is a proposal too, and its rows are the count Studio's right slot shows. - // "Pending" for it is the card still offering its confirm button: no replay - // verdict, no later same-tool commit, no click in flight (`confirmPendingIds`) - // and no quota refusal (`quotaBlockedChanges`). - let newestProposal: ChatbotEnhancedToolInvocation | undefined; - for (const message of messages) { - for (const tool of message.toolInvocations ?? []) { - if ((tool.proposedPlan || tool.proposedChanges || isUnstructuredBuildProposal(tool)) && tool.toolCallId) { - newestProposal = tool; - } + // and a suggestion chip's text the host held for a create that then + // failed is the message that was not sent, not a stale one. + const text = unsentText ?? lastSubmittedRef.current; + if (!text) return; + const textarea = promptInputWrapRef.current?.querySelector('textarea'); + if (textarea && textarea.value.trim() === '') { + textarea.value = text; + // Nudge the auto-grow sizing + any onInputChange listener. + textarea.dispatchEvent(new Event('input', { bubbles: true })); + textarea.focus(); } - } - const newestProposalId = newestProposal?.toolCallId; - const planApprovalPending = - newestProposalId !== undefined && - !quotaBlockedChanges.has(newestProposalId) && - resolveProposalCardState({ - replayOutcome: replayOutcomeByProposalId.get(newestProposalId), - built: planBuildStateOf(newestProposalId) === 'built', - building: planBuildStateOf(newestProposalId) === 'building', - buildFailed: planBuildStateOf(newestProposalId) === 'failed', - confirmed: confirmedChangeIds.has(newestProposalId), - approved: planBuildStateOf(newestProposalId) === 'confirmed' || confirmPendingIds.has(newestProposalId), - }) === 'pending'; - const planApprovalPendingCount = planApprovalPending - ? (newestProposal?.proposedChanges?.changes.length ?? 1) - : 0; - // The host's callback is read through a ref so the effect keys on the - // reading alone — a host that passes a fresh function each render must not - // re-announce an unchanged reading. - const onPlanApprovalPendingChangeRef = React.useRef(onPlanApprovalPendingChange); - React.useEffect(() => { - onPlanApprovalPendingChangeRef.current = onPlanApprovalPendingChange; - }, [onPlanApprovalPendingChange]); - React.useEffect(() => { - onPlanApprovalPendingChangeRef.current?.(planApprovalPending, planApprovalPendingCount); - }, [planApprovalPending, planApprovalPendingCount]); + }, [error, unsentText]); - // Read fresh each render from the messages themselves; consulted by value - // (`has`) only, never as a dependency. - const supersededPlans = supersededPlanIds(messages); + const handleCopy = React.useCallback((message: ChatbotEnhancedMessage) => { + void navigator.clipboard?.writeText(message.content); + setCopiedId(message.id); + window.setTimeout(() => setCopiedId((prev) => (prev === message.id ? null : prev)), 1500); + }, []); - /** - * objectstack#34627 — `failureOnChecklist`: the turn's result card shows a - * failed checklist, which states the build's failure; this card then draws - * neither its issue-count chip nor the red summary beside it. - */ - const renderToolDetail = ( - tool: RenderedToolInvocation, - { failureOnChecklist = false }: { failureOnChecklist?: boolean } = {}, - ) => { + const renderToolDetail = (tool: ChatbotEnhancedToolInvocation) => { const state = tool.state ?? (tool.errorText @@ -3929,51 +1536,13 @@ const ChatbotEnhanced = React.forwardRef( friendlyTitle.toLowerCase() !== tool.toolName.toLowerCase(); // Raw PARAMETERS/RESULT JSON is developer detail — only in `debug` mode, // or when a HITL approval needs the operator to see the exact payload. - // A drafting tool (create_object / apply_blueprint) is NOT a reason to dump - // JSON: the human summary + the Publish/Review affordance below already tell - // a Build-with-AI user what happened, so on the consumer surface (`summary`) - // the whole-app blueprint JSON and "status: drafted" envelopes stay hidden. const showPayload = processVisibility === 'debug' || (isAwaitingApproval && !isRecordWriteCard && !tool.sampleDataCleanup && !tool.packageRemoval); - // Lifecycle truth for this card's draft package, in precedence order: - // the server's live pending-draft count (host wired - // `fetchPendingDraftCount`), else this session's in-memory publish - // history. The live count is what keeps reloaded conversations and - // cross-session edits honest. - const draftPackageId = tool.draftReview?.packageId; - const livePendingCount = draftPackageId !== undefined - ? pendingByPackage.get(draftPackageId) - : undefined; - const draftIsPublished = livePendingCount !== undefined - ? livePendingCount === 0 - : publishedToolCalls.has(tool.toolCallId); // A tool with no output yet is RUNNING — show a live elapsed timer next to - // its title so a long blueprint/build call has a visible countdown, not a + // its title so a long tool call has a visible countdown, not a // static "Running" (issue #432). const isRunning = state === 'input-streaming' || state === 'input-available'; - // #772 — the HEADER badge state. A tool that RETURNED a confirm-before- - // change PREVIEW (changes_proposed / blueprint_proposed) reads as - // "Awaiting Approval", not "Completed": nothing was applied, it's waiting - // for the user. Only the header badge is remapped — the local `state` - // (which gates payload display / HITL) is untouched. - // - // objectui#7254 — "waiting for the user" is only true until the user acts. - // The header used to stop reading here, so a card whose BODY had already - // collapsed to 已搭建 / 已生效 / 未生效 kept saying "Awaiting Approval". - // `resolveProposalCardState` is now the one producer both sides read. - const proposalCardState = resolveProposalCardState({ - replayOutcome: replayOutcomeByProposalId.get(tool.toolCallId), - built: planBuildStateOf(tool.toolCallId) === 'built', - building: planBuildStateOf(tool.toolCallId) === 'building', - buildFailed: planBuildStateOf(tool.toolCallId) === 'failed', - confirmed: confirmedChangeIds.has(tool.toolCallId), - approved: planBuildStateOf(tool.toolCallId) === 'confirmed', - }); - const headerState = - state === 'output-available' && isProposalResult(tool.result) && !tool.planSuperseded - ? PROPOSAL_HEADER_STATE[proposalCardState] - : state; const titleNode = ( {friendlyTitle || tool.toolName} @@ -3982,20 +1551,7 @@ const ChatbotEnhanced = React.forwardRef( {tool.toolName} ) : null} - {isRunning ? ( - // The plan-design step gets the friendly rotating-hint indicator - // (long atomic call, no stream); every other running tool keeps the - // compact timer. Mirrors the summary-strip treatment. - isBuildProposalTool(tool) ? ( - - ) : ( - - ) - ) : null} + {isRunning ? : null} ); @@ -4005,22 +1561,14 @@ const ChatbotEnhanced = React.forwardRef( defaultOpen={ state === 'output-error' || state === 'approval-requested' || - Boolean(tool.draftReview && tool.draftReview.items.length > 0) || - Boolean(tool.proposedPlan) || - Boolean(tool.proposedChanges) || - // ADR-0057 P4 — open so the "Open in Builder →" action is visible. - Boolean(tool.builderHandoff) || Boolean(tool.recordHandoff) || Boolean(tool.recordWrite) || - Boolean(tool.packageRemoval) || - // Fallback confirm gate (unstructured proposal) must open so its - // "Build it" button is visible without an extra click. - isUnstructuredBuildProposal(tool) + Boolean(tool.packageRemoval) } > @@ -4096,252 +1644,6 @@ const ChatbotEnhanced = React.forwardRef(
) : 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',