From f1179fecb9d3c5a6cb176360e0eeeb0540637794 Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 27 Nov 2026 14:19:30 +0000 Subject: [PATCH 1/2] wip(plugin-chatbot): wire the question card into the conversation Claude-Session: https://claude.ai/code/session_01L9qibyUpyff7pHe7vkFgA8 Co-authored-by: Claude --- docs/qa/platform-checklist/areas/ai.json | 73 ++++++ packages/spec/src/ai/ask-question.test.ts | 25 +- packages/spec/src/ai/ask-question.zod.ts | 66 +++-- .../app-shell/src/console/ai/ChatPane.tsx | 2 + .../__tests__/useChatConversation.test.tsx | 3 + .../src/hooks/useChatConversation.ts | 12 +- .../plugin-chatbot/src/ChatbotEnhanced.tsx | 77 +++++- .../plugin-chatbot/src/QuestionCard.tsx | 42 ++-- ...hatbotEnhanced.questionCard-37874.test.tsx | 227 ++++++++++++++++++ .../__tests__/pendingQuestion-37874.test.ts | 194 +++++++++++++++ .../plugin-chatbot/src/chat/composerGate.tsx | 74 ++++++ .../src/chat/pendingQuestion.ts | 168 +++++++++++++ .../src/chat/questionMessage.tsx | 79 ++++++ .../plugin-chatbot/src/chat/questionSkip.ts | 79 ++++++ ui/packages/plugin-chatbot/src/chat/types.ts | 7 + ui/packages/plugin-chatbot/src/core.ts | 4 + ui/packages/plugin-chatbot/src/index.tsx | 3 + 17 files changed, 1096 insertions(+), 39 deletions(-) create mode 100644 ui/packages/plugin-chatbot/src/__tests__/ChatbotEnhanced.questionCard-37874.test.tsx create mode 100644 ui/packages/plugin-chatbot/src/__tests__/pendingQuestion-37874.test.ts create mode 100644 ui/packages/plugin-chatbot/src/chat/composerGate.tsx create mode 100644 ui/packages/plugin-chatbot/src/chat/pendingQuestion.ts create mode 100644 ui/packages/plugin-chatbot/src/chat/questionMessage.tsx create mode 100644 ui/packages/plugin-chatbot/src/chat/questionSkip.ts diff --git a/docs/qa/platform-checklist/areas/ai.json b/docs/qa/platform-checklist/areas/ai.json index 0327c6284c5..c02ddbbb18d 100644 --- a/docs/qa/platform-checklist/areas/ai.json +++ b/docs/qa/platform-checklist/areas/ai.json @@ -1808,6 +1808,79 @@ "ref": "#35212" } ] + }, + { + "id": "ai.chat-question-card", + "title": "When the AI ends its turn on a clarifying question, a clickable question card takes the composer's place: one click answers with the next message, Skip gives the composer back with its draft, and the conversation shows the question collapsed", + "since": "v19", + "status": "active", + "revision": 1, + "priority": "P1", + "surface": "browser", + "personas": [ + "seeded admin (admin@objectos.ai / admin123), signed in through the form, in the AI chat" + ], + "fixtures": { + "app": "showcase", + "requires": [ + "an AI service that serves an agent with a model and the ask_which tool, so an ambiguous question ends the turn on a question (service-ai is a Cloud/EE package: ai.open-edition-honest-degradation)", + "an ambiguous question, e.g. 'how much revenue this quarter' where the agent can read more than one revenue figure" + ], + "knownGaps": [ + "BLOCKED(environment): the open tree registers no AI service, so no turn ends on a question. When the card shows, what an answer sends and the skip mark are pinned (automated.ref)" + ] + }, + "steps": [ + "type a few words in the composer without sending them, then ask an ambiguous question; wait for the turn to end", + "read the composer area and the last assistant message; check that the reply's Regenerate button is absent", + "click Skip; read the composer and its draft; reload the conversation and check the card does not come back", + "ask another ambiguous question and click one option; read the next user message" + ], + "acceptance": [ + { + "clause": "the card takes the composer's place once the turn ends on a question, and the conversation shows the question without its options", + "oracle": "dom", + "verify": "the question card is shown where the input was, the input is hidden but still in the DOM, and the last assistant message reads 'AI asks: QUESTION' (ui/packages/plugin-chatbot/src/chat/pendingQuestion.ts#findPendingQuestion)", + "evidence": "a screenshot of the composer area and the message" + }, + { + "clause": "Skip gives the composer back with the draft typed before the question, and the card stays away after a reload on this device", + "oracle": "dom", + "verify": "the input holds the typed words, the question shows collapsed with its options inside, and localStorage holds objectstack:ai-chat-question-skip:CONVERSATION_ID (ui/packages/plugin-chatbot/src/chat/questionSkip.ts#QUESTION_SKIP_STORAGE_PREFIX)", + "evidence": "the input value, the message DOM and the storage entry" + }, + { + "clause": "one click on an option sends its label as the next user message", + "oracle": "network", + "verify": "the chat request after the click carries the option label as the user message", + "evidence": "the request body" + } + ], + "negative": [ + "a card that shows while the turn still streams, a draft lost after Skip, or an answer sent twice is a FAIL" + ], + "blocked": { + "by": "environment", + "ref": "service-ai is Cloud/EE: no open-tree AI service answers the chat (FOLLOW-UPS §18c, ai.console-ai-surface-gating)" + }, + "automated": { + "kind": "unit", + "ref": "ui/packages/plugin-chatbot/src/__tests__/pendingQuestion-37874.test.ts, ui/packages/plugin-chatbot/src/__tests__/ChatbotEnhanced.questionCard-37874.test.tsx" + }, + "source": [ + "ui/packages/plugin-chatbot/src/chat/pendingQuestion.ts#findPendingQuestion", + "ui/packages/plugin-chatbot/src/chat/composerGate.tsx#ComposerGate", + "ui/packages/plugin-chatbot/src/chat/questionSkip.ts#QUESTION_SKIP_STORAGE_PREFIX", + "packages/spec/src/ai/ask-question.zod.ts#parseAskQuestionEnvelope" + ], + "history": [ + { + "revision": 1, + "date": "2026-11-27", + "change": "initial — the question card wired into the AI chat (question-card topic #37871, Q2b). Blocked(environment): no open-tree AI service; no live run made", + "ref": "#37874" + } + ] } ] } diff --git a/packages/spec/src/ai/ask-question.test.ts b/packages/spec/src/ai/ask-question.test.ts index e676be486ab..ce0023c5a5f 100644 --- a/packages/spec/src/ai/ask-question.test.ts +++ b/packages/spec/src/ai/ask-question.test.ts @@ -203,8 +203,31 @@ describe('parseAskQuestionEnvelope', () => { expect(parseAskQuestionEnvelope({ ...LEGACY, readings: ['Only one'] })).toBeNull(); expect(parseAskQuestionEnvelope({ ...LEGACY, readings: ['A', 'B', 'C', 'D', 'E'] })).toBeNull(); expect(parseAskQuestionEnvelope({ ...LEGACY, readings: ['A', 'A'] })).toBeNull(); - expect(parseAskQuestionEnvelope({ ...LEGACY, readings: ['x'.repeat(ASK_QUESTION_LIMITS.labelMaxLength + 1), 'B'] })) + expect(parseAskQuestionEnvelope({ ...LEGACY, readings: ['A', ' A '] })).toBeNull(); + expect(parseAskQuestionEnvelope({ ...LEGACY, readings: ['A', ' '] })).toBeNull(); + expect(parseAskQuestionEnvelope({ + ...LEGACY, + readings: ['x'.repeat(ASK_QUESTION_LIMITS.legacyReadingMaxLength + 1), 'B'], + })).toBeNull(); + expect(parseAskQuestionEnvelope({ ...LEGACY, question: 'q'.repeat(ASK_QUESTION_LIMITS.questionMaxLength + 1) })) .toBeNull(); + expect(parseAskQuestionEnvelope({ ...LEGACY, reply: '' })).toBeNull(); + }); + + it('holds a reading to its own limit, longer than the label limit', () => { + // Real ask_which readings run past the envelope's 24-character label + // (most of them do), so a reading gets the description's length. + expect(ASK_QUESTION_LIMITS.legacyReadingMaxLength).toBeGreaterThan(ASK_QUESTION_LIMITS.labelMaxLength); + const atEdge = 'r'.repeat(ASK_QUESTION_LIMITS.legacyReadingMaxLength); + const overLabel = 'Revenue booked when the deal closed'; + expect(overLabel.length).toBeGreaterThan(ASK_QUESTION_LIMITS.labelMaxLength); + const parsed = parseAskQuestionEnvelope({ ...LEGACY, readings: [atEdge, overLabel] }); + expect(parsed?.questions[0]?.options).toEqual([{ label: atEdge }, { label: overLabel }]); + }); + + it('keeps the new envelope at the label limit', () => { + const long = 'x'.repeat(ASK_QUESTION_LIMITS.labelMaxLength + 1); + expect(parseAskQuestionEnvelope(withQuestion({ options: [{ label: long }, { label: 'B' }] }))).toBeNull(); }); it('answers null for a malformed legacy result', () => { diff --git a/packages/spec/src/ai/ask-question.zod.ts b/packages/spec/src/ai/ask-question.zod.ts index b3470a16d78..f377ad0db4c 100644 --- a/packages/spec/src/ai/ask-question.zod.ts +++ b/packages/spec/src/ai/ask-question.zod.ts @@ -37,10 +37,12 @@ import { strictObject } from '../shared/strict-object'; * is `ask_which`'s existing result, * `{ success: true, status: 'asked_which', question, readings, reply }`. * {@link parseAskQuestionEnvelope} reads it as one question whose options are - * the readings, with no description, and holds the result to the same - * {@link AskQuestionEnvelopeSchema} — one contract and one set of limits, so a - * legacy result the card cannot draw (a reading over the label limit, more - * than four readings) answers `null` and stays text, as it renders today. + * the readings, with no description, under the envelope's limits with one + * exception: a reading is a whole sentence-sized phrase, not a short label, so + * it is held to its own limit, `ASK_QUESTION_LIMITS.legacyReadingMaxLength`, + * and the card wraps it. Every other limit is the envelope's, so a legacy + * result the card cannot draw (a reading over its limit, one reading or more + * than four, a duplicate) answers `null` and stays text, as it renders today. * Stored conversations keep their old results, so this reading stays as long * as those rows can be shown. */ @@ -70,6 +72,13 @@ export const ASK_QUESTION_LIMITS = { questionMaxLength: 120, labelMaxLength: 24, descriptionMaxLength: 60, + /** + * A legacy `ask_which` reading, which becomes an option label with no + * description. Readings were never held to the label limit, so they get + * the description's length instead; the new envelope's labels stay at + * `labelMaxLength`. + */ + legacyReadingMaxLength: 60, } as const; /** A non-empty string with at least one non-space character, at most `max` long. */ @@ -126,7 +135,18 @@ export const AskQuestionSchema = lazySchema(() => strictObject( .max(ASK_QUESTION_LIMITS.maxOptions) .describe('Two to four mutually exclusive options; labels unique, at most one recommended'), }, -).superRefine((question, ctx) => { +).superRefine(refineOptions)); + +/** + * The rules over a question's options that one option alone cannot hold: + * labels unique (compared trimmed, since a label is the answer text) and at + * most one option recommended. Shared by the envelope's question and the + * legacy reading's, so both refuse the same way. + */ +function refineOptions( + question: { options: ReadonlyArray<{ label: string; recommended?: boolean }> }, + ctx: z.RefinementCtx, +) { const seen = new Set(); question.options.forEach((option, index) => { const label = option.label.trim(); @@ -147,7 +167,7 @@ export const AskQuestionSchema = lazySchema(() => strictObject( message: `${recommended} options are marked recommended: at most one per question`, }); } -})); +} /** The ask-question envelope a question tool's result carries. */ export const AskQuestionEnvelopeSchema = lazySchema(() => strictObject( @@ -193,14 +213,27 @@ const AskWhichLegacyResultSchema = z.looseObject({ reply: z.string(), }); +/** + * The one question a legacy `ask_which` result converts to: the envelope's + * question rules, with each reading held to `legacyReadingMaxLength` instead + * of the label limit. Not exported, for the same reason as the result above. + */ +const AskWhichLegacyQuestionSchema = z.object({ + question: text(ASK_QUESTION_LIMITS.questionMaxLength), + options: z.array(z.object({ label: text(ASK_QUESTION_LIMITS.legacyReadingMaxLength) })) + .min(ASK_QUESTION_LIMITS.minOptions) + .max(ASK_QUESTION_LIMITS.maxOptions), +}).superRefine(refineOptions); + /** * Read a tool result as an ask-question envelope. * * Takes the already-unwrapped result object (peeling the stream's * `{ type: 'text', value }` wrapper stays with the caller). Answers the parsed * envelope for a valid {@link AskQuestionEnvelopeSchema} value or a legacy - * `ask_which` result that converts to one, and `null` for anything else — - * the caller then shows the result as the text it already is. + * `ask_which` result that converts to one (its option labels then run to + * `ASK_QUESTION_LIMITS.legacyReadingMaxLength`), and `null` for anything + * else — the caller then shows the result as the text it already is. */ export function parseAskQuestionEnvelope(value: unknown): AskQuestionEnvelopeParsed | null { if (value === null || typeof value !== 'object') return null; @@ -211,17 +244,18 @@ export function parseAskQuestionEnvelope(value: unknown): AskQuestionEnvelopePar } if (status === ASK_WHICH_LEGACY_STATUS) { const legacy = AskWhichLegacyResultSchema.safeParse(value); - if (!legacy.success) return null; - const parsed = AskQuestionEnvelopeSchema.safeParse({ + if (!legacy.success || legacy.data.reply.length === 0) return null; + const question = AskWhichLegacyQuestionSchema.safeParse({ + question: legacy.data.question, + options: legacy.data.readings.map((label) => ({ label })), + }); + if (!question.success) return null; + return { success: true, status: ASK_QUESTION_STATUS, reply: legacy.data.reply, - questions: [{ - question: legacy.data.question, - options: legacy.data.readings.map((label) => ({ label })), - }], - }); - return parsed.success ? parsed.data : null; + questions: [question.data], + }; } return null; } diff --git a/ui/packages/app-shell/src/console/ai/ChatPane.tsx b/ui/packages/app-shell/src/console/ai/ChatPane.tsx index 932c2cafc65..53580ecc755 100644 --- a/ui/packages/app-shell/src/console/ai/ChatPane.tsx +++ b/ui/packages/app-shell/src/console/ai/ChatPane.tsx @@ -772,6 +772,8 @@ export function ChatPane({ // area, in flow above the input. promptHeaderSlot={focusRow ?? undefined} messages={shownMessages} + // Keys the question card's skip marks to this conversation. + conversationId={conversationId} placeholder={ activeAgent ? agentRouteName(activeAgent) === 'ask' 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 9ac87c521af..79418aaec16 100644 --- a/ui/packages/app-shell/src/hooks/__tests__/useChatConversation.test.tsx +++ b/ui/packages/app-shell/src/hooks/__tests__/useChatConversation.test.tsx @@ -1022,7 +1022,10 @@ describe('useChatConversation — clears chat cache on logout / user switch', () it('purgeChatCaches removes only the ai-chat keys', () => { seedChatCache(); + // The question card's skip marks, one key per conversation. + localStorage.setItem('objectstack:ai-chat-question-skip:conv-1', JSON.stringify(['call_1'])); purgeChatCaches(); + expect(localStorage.getItem('objectstack:ai-chat-question-skip:conv-1')).toBeNull(); expect(localStorage.getItem(`${CACHE_PREFIX}:u1`)).toBeNull(); expect(localStorage.getItem(`${CACHE_PREFIX}:u1:app:crm:build`)).toBeNull(); expect(localStorage.getItem(`${MESSAGE_PREFIX}:conv-1`)).toBeNull(); diff --git a/ui/packages/app-shell/src/hooks/useChatConversation.ts b/ui/packages/app-shell/src/hooks/useChatConversation.ts index 293c688fc5e..038863c4971 100644 --- a/ui/packages/app-shell/src/hooks/useChatConversation.ts +++ b/ui/packages/app-shell/src/hooks/useChatConversation.ts @@ -22,7 +22,7 @@ import { useCallback, useEffect, useLayoutEffect, useRef, useState } from 'react // `@object-ui/plugin-chatbot` is already a static member of this package's // barrel closure (`index.ts` re-exports `AiChatPage`, which imports it), so // this adds no package edge and no eager bundle weight. -import { detectPendingApproval, storedAnswerParts } from '@object-ui/plugin-chatbot/core'; +import { detectPendingApproval, QUESTION_SKIP_STORAGE_PREFIX, storedAnswerParts } from '@object-ui/plugin-chatbot/core'; import type { StoredAnswerData } from '@object-ui/plugin-chatbot/core'; // Type-only, so it is erased and pulls no barrel closure into the hook. import type { AnswerSource } from '@object-ui/plugin-chatbot'; @@ -282,7 +282,8 @@ function messageCacheKey(conversationId: string): string { /** * Security — clear ALL cached AI-chat state from localStorage (per-user - * conversation-id pointers AND per-conversation message bodies). Conversation + * conversation-id pointers, per-conversation message bodies, and the question + * card's per-conversation skip marks). Conversation * content + tool payloads are cached in plaintext (keyed by `objectstack: * ai-chat-*`); without this, on a shared machine the next profile user could * read the previous user's AI threads (which may contain data surfaced by the @@ -294,7 +295,12 @@ export function purgeChatCaches(): void { const doomed: string[] = []; for (let i = 0; i < localStorage.length; i += 1) { const key = localStorage.key(i); - if (key && (key.startsWith(CACHE_PREFIX) || key.startsWith(MESSAGE_CACHE_PREFIX))) { + if ( + key && + (key.startsWith(CACHE_PREFIX) || + key.startsWith(MESSAGE_CACHE_PREFIX) || + key.startsWith(QUESTION_SKIP_STORAGE_PREFIX)) + ) { doomed.push(key); } } diff --git a/ui/packages/plugin-chatbot/src/ChatbotEnhanced.tsx b/ui/packages/plugin-chatbot/src/ChatbotEnhanced.tsx index 52288cc8001..35ec4c1c0ea 100644 --- a/ui/packages/plugin-chatbot/src/ChatbotEnhanced.tsx +++ b/ui/packages/plugin-chatbot/src/ChatbotEnhanced.tsx @@ -93,6 +93,11 @@ import { formatSizeLimit, SendErrorNotice, } from './chat/composerNotices'; +import { QuestionCard } from './QuestionCard'; +import { ComposerGate } from './chat/composerGate'; +import { QuestionMessage } from './chat/questionMessage'; +import { findPendingQuestion, findQuestions, type ChatQuestion } from './chat/pendingQuestion'; +import { useQuestionSkips } from './chat/questionSkip'; export type { ChatbotEnhancedMessage, @@ -145,6 +150,7 @@ const ChatbotEnhanced = React.forwardRef( onUpgrade, disabled = false, readOnly = false, + conversationId, isLoading = false, error, unsentText, @@ -474,6 +480,50 @@ const ChatbotEnhanced = React.forwardRef( [queuedSends], ); + // The question card (question-card topic, Q2b). A question the turn ended + // on takes the composer's place until it is answered or skipped; the + // conversation draws every question from its envelope. See + // `chat/pendingQuestion.ts` for when a question is pending. + const { skipped: skippedQuestions, skip: skipQuestion } = useQuestionSkips(conversationId); + const questionsByMessage = React.useMemo( + () => new Map(findQuestions(messages).map((question) => [question.messageId, question])), + [messages], + ); + const pendingQuestion = React.useMemo( + () => + findPendingQuestion(messages, promptStatus, { + queued: queuedSends.length > 0, + skipped: skippedQuestions, + readOnly, + toolDecisions, + }), + [messages, promptStatus, queuedSends.length, skippedQuestions, readOnly, toolDecisions], + ); + // The question last answered from the card. Its card stays mounted (hidden) + // while the answer is on its way: a send that fails rolls the answer back, + // the question is pending again, and the card returns with its choices. + const [answeredQuestion, setAnsweredQuestion] = React.useState(null); + const cardQuestion = pendingQuestion ?? answeredQuestion; + const answerQuestion = React.useCallback( + (question: ChatQuestion, text: string) => { + setAnsweredQuestion(question); + // A card answer is not typed text: a rejected send has nothing to put + // back in the composer (the card returns instead). + lastSubmittedRef.current = ''; + restoredErrorRef.current = null; + onSendMessage?.(text); + followThreadToBottom(); + }, + [onSendMessage, followThreadToBottom], + ); + const skipPendingQuestion = React.useCallback( + (question: ChatQuestion) => { + setAnsweredQuestion(null); + skipQuestion(question.toolCallId); + }, + [skipQuestion], + ); + const handleSuggestionClick = React.useCallback( (text: string) => { // Not typed by the user — nothing to restore if this send is rejected @@ -704,6 +754,11 @@ const ChatbotEnhanced = React.forwardRef( // streaming cursor rides the last text run, where it sat when // the charts always trailed the text. const answerBlocks = isUser ? undefined : layoutAnswer(message.content, message.charts); + // The question this turn ended on, drawn from its envelope in + // place of its plain-text reply. + const threadQuestion = isUser ? undefined : questionsByMessage.get(message.id); + const questionPending = + threadQuestion !== undefined && pendingQuestion?.toolCallId === threadQuestion.toolCallId; let lastTextBlock = -1; answerBlocks?.forEach((block, i) => { if (block.kind === 'text') lastTextBlock = i; @@ -787,7 +842,9 @@ const ChatbotEnhanced = React.forwardRef( {L.agentActivity} ) : null} - {answerBlocks ? ( + {threadQuestion ? ( + + ) : answerBlocks ? ( // objectui#13492 — the answer's text and charts in // stream order (see `layoutAnswer`). A turn with no // showable prose still draws its charts here, so a @@ -873,7 +930,8 @@ const ChatbotEnhanced = React.forwardRef( )} - {onReload ? ( + {/* A pending question is answered, not regenerated. */} + {onReload && !questionPending ? ( ( ))} ) : null} + answerQuestion(cardQuestion, text)} + onSkip={() => skipPendingQuestion(cardQuestion)} + /> + ) : null + } + > ( /> + )} diff --git a/ui/packages/plugin-chatbot/src/QuestionCard.tsx b/ui/packages/plugin-chatbot/src/QuestionCard.tsx index 281c4e00756..018eb91cd7a 100644 --- a/ui/packages/plugin-chatbot/src/QuestionCard.tsx +++ b/ui/packages/plugin-chatbot/src/QuestionCard.tsx @@ -30,26 +30,30 @@ * Ctrl/⌘+Enter anywhere go to the next question or send. */ import * as React from 'react'; +import { + ASK_QUESTION_LIMITS, + type AskQuestionOptionParsed, + type AskQuestionParsed, +} from '@objectstack/spec/ai'; import { Badge, Button, cn } from '@object-ui/components'; import { useObjectTranslation } from '@object-ui/i18n'; import { useQuestionCardTranslation } from './useQuestionCardTranslation'; -/** One option of a question, as the question envelope carries it. */ -export interface QuestionCardOption { - label: string; - /** Shown as a grey second line under the label. */ - description?: string; - /** Shows a "recommended" tag on the option. */ - recommended?: boolean; -} +/** + * One option of a question: the envelope's option + * (`AskQuestionOptionParsed`, `@objectstack/spec/ai`) — a label, an optional + * grey second line, an optional "recommended" tag. + */ +export type QuestionCardOption = AskQuestionOptionParsed; -/** One question, as the question envelope carries it. */ -export interface QuestionCardQuestion { - /** Short name of the question, used to label its line in a multi-question answer. */ - header?: string; - question: string; +/** + * One question: the envelope's question (`AskQuestionParsed`) — an optional + * short header that labels its line in a multi-question answer, the question, + * and its options, taken read-only. + */ +export type QuestionCardQuestion = Omit & { options: readonly QuestionCardOption[]; -} +}; export interface QuestionCardProps { /** The questions to ask, in order. */ @@ -70,7 +74,11 @@ export interface QuestionCardProps { /** An option index, the typed text row, or nothing chosen yet. */ type Choice = number | 'text' | null; -const DIGIT_KEYS = ['1', '2', '3', '4'] as const; +/** One digit key per option the envelope allows: `1` picks the first option. */ +const DIGIT_KEYS: readonly string[] = Array.from( + { length: ASK_QUESTION_LIMITS.maxOptions }, + (_, i) => String(i + 1), +); export function QuestionCard({ questions, onAnswer, onSkip, announce = false, className }: QuestionCardProps) { const { t } = useQuestionCardTranslation(); @@ -186,7 +194,7 @@ export function QuestionCard({ questions, onAnswer, onSkip, announce = false, cl return; } if (!inText && !e.ctrlKey && !e.metaKey && !e.altKey) { - const digit = (DIGIT_KEYS as readonly string[]).indexOf(e.key); + const digit = DIGIT_KEYS.indexOf(e.key); if (digit !== -1 && current && digit < current.options.length) { e.preventDefault(); pick(digit); @@ -259,7 +267,7 @@ export function QuestionCard({ questions, onAnswer, onSkip, announce = false, cl - {option.label} + {option.label} {option.recommended && ( {t('chatbot.questionCard.recommended')} diff --git a/ui/packages/plugin-chatbot/src/__tests__/ChatbotEnhanced.questionCard-37874.test.tsx b/ui/packages/plugin-chatbot/src/__tests__/ChatbotEnhanced.questionCard-37874.test.tsx new file mode 100644 index 00000000000..2eb8f00df17 --- /dev/null +++ b/ui/packages/plugin-chatbot/src/__tests__/ChatbotEnhanced.questionCard-37874.test.tsx @@ -0,0 +1,227 @@ +/** + * 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. + * + * Question-card topic, Q2b — the question card wired into the conversation: + * it takes the composer's place without unmounting it, an answer is the next + * message, a skip is remembered per conversation on this device, the thread + * draws the question from its envelope, and a pending question is not + * regenerated. Every interaction goes through the rendered component. + */ +import '@testing-library/jest-dom/vitest'; +import { afterEach, describe, expect, it, vi } from 'vitest'; +import { fireEvent, render, screen, waitFor, within } from '@testing-library/react'; +import { ChatbotEnhanced } from '../ChatbotEnhanced'; +import { QUESTION_SKIP_STORAGE_PREFIX } from '../chat/questionSkip'; +import type { ChatbotEnhancedMessage } from '../chat/types'; + +const REPLY = 'Which revenue did you mean?\n- Booked revenue\n- Invoiced revenue'; + +const ASKED: ChatbotEnhancedMessage[] = [ + { id: 'u1', role: 'user', content: 'Show me revenue' }, + { + id: 'a1', + role: 'assistant', + content: REPLY, + toolInvocations: [{ + toolCallId: 'call_q', + toolName: 'ask_which', + state: 'output-available', + result: { + type: 'text', + value: JSON.stringify({ + success: true, + status: 'asked_which', + question: 'Which revenue did you mean?', + readings: ['Booked revenue', 'Invoiced revenue'], + reply: REPLY, + }), + }, + }], + }, +]; + +const ANSWERED: ChatbotEnhancedMessage[] = [ + ...ASKED, + { id: 'u2', role: 'user', content: 'Booked revenue' }, + { id: 'a2', role: 'assistant', content: 'Booked revenue this quarter is 1.2M.' }, +]; + +afterEach(() => { + localStorage.clear(); +}); + +describe('Q2b — the card takes the composer place', () => { + it('shows the card once the turn ended on a question; the composer stays mounted, hidden and inert', () => { + render(); + const holder = screen.getByTestId('composer-gate-holder'); + expect(holder).toBeVisible(); + expect(within(holder).getByTestId('question-card')).toHaveTextContent('Which revenue did you mean?'); + const composer = screen.getByTestId('composer-gate-composer'); + expect(composer).not.toBeVisible(); + expect(composer).toHaveAttribute('inert'); + // Mounted, not removed: the textarea is still in the document. + expect(screen.getByPlaceholderText('Ask…')).toBeInTheDocument(); + }); + + it('control: no card while the turn is still running', () => { + render(); + expect(screen.queryByTestId('question-card')).not.toBeInTheDocument(); + expect(screen.getByTestId('composer-gate-composer')).toBeVisible(); + }); + + it('keeps the draft typed before the card opened, and gives it back after a skip', () => { + const { rerender } = render( + , + ); + const textarea = screen.getByPlaceholderText('Ask…') as HTMLTextAreaElement; + fireEvent.change(textarea, { target: { value: 'half a thought' } }); + rerender(); + expect(screen.getByTestId('question-card')).toBeVisible(); + + fireEvent.click(screen.getByRole('button', { name: 'Skip' })); + expect(screen.queryByTestId('question-card')).not.toBeInTheDocument(); + expect(screen.getByTestId('composer-gate-composer')).toBeVisible(); + expect(screen.getByPlaceholderText('Ask…')).toBe(textarea); + expect(textarea.value).toBe('half a thought'); + }); + + it('answers with one click: the label is sent as the next message', () => { + const onSendMessage = vi.fn(); + render(); + fireEvent.click(screen.getByRole('radio', { name: /Invoiced revenue/ })); + expect(onSendMessage).toHaveBeenCalledTimes(1); + expect(onSendMessage).toHaveBeenCalledWith('Invoiced revenue'); + }); + + it('a failed send brings the card back with the choice still made', () => { + const onSendMessage = vi.fn(); + const { rerender } = render( + , + ); + fireEvent.click(screen.getByRole('radio', { name: /Invoiced revenue/ })); + // The optimistic bubble: the question has moved on. + rerender( + , + ); + expect(screen.getByTestId('composer-gate-composer')).toBeVisible(); + // The send is refused and the bubble rolls back: the question is pending again. + rerender( + , + ); + expect(screen.getByTestId('question-card')).toBeVisible(); + expect(screen.getByRole('radio', { name: /Invoiced revenue/ })).toHaveAttribute('aria-checked', 'true'); + // The answer is not typed text, so nothing is put back in the composer. + expect((screen.getByPlaceholderText('Ask…') as HTMLTextAreaElement).value).toBe(''); + }); + + it('a queued message holds the card back', () => { + const { rerender } = render( + , + ); + const textarea = screen.getByPlaceholderText('Ask…') as HTMLTextAreaElement; + fireEvent.change(textarea, { target: { value: 'actually, show costs' } }); + fireEvent.keyDown(textarea, { key: 'Enter' }); + rerender(); + expect(screen.getByTestId('composer-queued-item')).toBeInTheDocument(); + expect(screen.queryByTestId('question-card')).not.toBeInTheDocument(); + }); + + it('no card on a read-only transcript, which draws the question as past', () => { + render(); + expect(screen.queryByTestId('question-card')).not.toBeInTheDocument(); + expect(screen.getByTestId('question-message')).toHaveAttribute('data-state', 'past'); + }); +}); + +describe('Q2b — a skip is remembered per conversation on this device', () => { + it('writes the question id under the conversation key, and the card stays away on the next mount', () => { + const { unmount } = render( + , + ); + fireEvent.click(screen.getByRole('button', { name: 'Skip' })); + expect(JSON.parse(localStorage.getItem(`${QUESTION_SKIP_STORAGE_PREFIX}:conv-1`) ?? 'null')).toEqual(['call_q']); + expect(QUESTION_SKIP_STORAGE_PREFIX).toBe('objectstack:ai-chat-question-skip'); + unmount(); + + render(); + expect(screen.queryByTestId('question-card')).not.toBeInTheDocument(); + expect(screen.getByTestId('question-message')).toHaveAttribute('data-state', 'past'); + }); + + it('control: another conversation is not skipped', () => { + localStorage.setItem(`${QUESTION_SKIP_STORAGE_PREFIX}:conv-1`, JSON.stringify(['call_q'])); + render(); + expect(screen.getByTestId('question-card')).toBeVisible(); + }); + + it('a stored mark that is not a list is ignored', () => { + localStorage.setItem(`${QUESTION_SKIP_STORAGE_PREFIX}:conv-1`, '{not json'); + render(); + expect(screen.getByTestId('question-card')).toBeVisible(); + }); +}); + +describe('Q2b — the thread draws the question from its envelope', () => { + it('pending: the question alone, no options, no bullets parsed out of the reply', () => { + render(); + const message = screen.getByTestId('question-message'); + expect(message).toHaveAttribute('data-state', 'pending'); + expect(message).toHaveTextContent('AI asks: Which revenue did you mean?'); + expect(within(message).queryByText('Booked revenue')).not.toBeInTheDocument(); + expect(within(message).queryByText(/- Booked revenue/)).not.toBeInTheDocument(); + }); + + it('past: a collapsed question that expands to its options', () => { + render(); + const message = screen.getByTestId('question-message'); + expect(message).toHaveAttribute('data-state', 'past'); + const details = message.querySelector('details'); + expect(details).not.toBeNull(); + expect(details).not.toHaveAttribute('open'); + expect(within(message).getByText('Booked revenue')).toBeInTheDocument(); + expect(within(message).getByText('Invoiced revenue')).toBeInTheDocument(); + expect(screen.queryByTestId('question-card')).not.toBeInTheDocument(); + }); + + it('control: a turn whose text is not the reply renders as text', () => { + const other: ChatbotEnhancedMessage[] = [ASKED[0], { ...ASKED[1], content: 'Here is your revenue.' }]; + render(); + expect(screen.queryByTestId('question-message')).not.toBeInTheDocument(); + expect(screen.queryByTestId('question-card')).not.toBeInTheDocument(); + expect(screen.getByText('Here is your revenue.')).toBeInTheDocument(); + }); +}); + +describe('Q2b — a pending question is answered, not regenerated', () => { + it('hides Regenerate on the pending question and keeps Copy', () => { + render(); + expect(screen.queryByRole('button', { name: 'Regenerate' })).not.toBeInTheDocument(); + expect(screen.getByRole('button', { name: 'Copy' })).toBeInTheDocument(); + }); + + it('Copy copies the full reply, bullets included', async () => { + const writeText = vi.fn().mockResolvedValue(undefined); + Object.defineProperty(navigator, 'clipboard', { value: { writeText }, configurable: true }); + render(); + fireEvent.click(screen.getByRole('button', { name: 'Copy' })); + await waitFor(() => expect(writeText).toHaveBeenCalledWith(REPLY)); + }); + + it('control: once answered, the question turn regenerates as before', () => { + render(); + expect(screen.getAllByRole('button', { name: 'Regenerate' }).length).toBe(2); + }); +}); diff --git a/ui/packages/plugin-chatbot/src/__tests__/pendingQuestion-37874.test.ts b/ui/packages/plugin-chatbot/src/__tests__/pendingQuestion-37874.test.ts new file mode 100644 index 00000000000..dd4092b716c --- /dev/null +++ b/ui/packages/plugin-chatbot/src/__tests__/pendingQuestion-37874.test.ts @@ -0,0 +1,194 @@ +/** + * 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. + * + * Question-card topic, Q2b — where the conversation holds a question + * (`findQuestions`) and when the card shows (`findPendingQuestion`), over the + * two shapes a tool-ended turn arrives in and every condition that holds the + * card back. + */ +import { describe, expect, it } from 'vitest'; +import { findPendingQuestion, findQuestions } from '../chat/pendingQuestion'; +import type { ChatbotEnhancedMessage } from '../chat/types'; + +const REPLY = 'Which revenue did you mean?\n- Booked revenue\n- Invoiced revenue'; + +const LEGACY_RESULT = { + success: true, + status: 'asked_which', + question: 'Which revenue did you mean?', + readings: ['Booked revenue', 'Invoiced revenue'], + reply: REPLY, +}; + +const ENVELOPE_RESULT = { + success: true, + status: 'asked', + reply: REPLY, + preface: 'Revenue can be counted two ways.', + questions: [{ + question: 'Which revenue did you mean?', + options: [{ label: 'Booked revenue', recommended: true }, { label: 'Invoiced revenue' }], + }], +}; + +const USER: ChatbotEnhancedMessage = { id: 'u1', role: 'user', content: 'Show me revenue' }; + +/** Streamed: ONE assistant message carries the tool part (stream-wrapped) and the text. */ +function streamed(result: unknown = LEGACY_RESULT, text = REPLY, toolCallId = 'call_q'): ChatbotEnhancedMessage[] { + return [ + USER, + { + id: 'a1', + role: 'assistant', + content: text, + toolInvocations: [{ + toolCallId, + toolName: 'ask_which', + state: 'output-available', + result: { type: 'text', value: JSON.stringify(result) }, + }], + }, + ]; +} + +/** Reloaded: TWO assistant messages, one with the tool part (placeholder text), one with the text. */ +function reloaded(result: unknown = LEGACY_RESULT): ChatbotEnhancedMessage[] { + return [ + USER, + { + id: 'a1', + role: 'assistant', + content: '(called ask_which)', + toolInvocations: [{ toolCallId: 'call_q', toolName: 'ask_which', result }], + }, + { id: 'a2', role: 'assistant', content: REPLY }, + ]; +} + +describe('findPendingQuestion — the card shows', () => { + it('on the streamed shape, drawn on the message that carries the reply', () => { + const question = findPendingQuestion(streamed(), 'ready'); + expect(question?.toolCallId).toBe('call_q'); + expect(question?.messageId).toBe('a1'); + expect(question?.envelope.questions[0]?.options.map((o) => o.label)).toEqual([ + 'Booked revenue', + 'Invoiced revenue', + ]); + }); + + it('on the reloaded shape, drawn on the text message, not the tool message', () => { + const question = findPendingQuestion(reloaded(), 'ready'); + expect(question?.toolCallId).toBe('call_q'); + expect(question?.messageId).toBe('a2'); + }); + + it('for the new envelope as well as the legacy ask_which result', () => { + const question = findPendingQuestion(streamed(ENVELOPE_RESULT), 'ready'); + expect(question?.envelope.preface).toBe('Revenue can be counted two ways.'); + expect(question?.envelope.questions[0]?.options[0]?.recommended).toBe(true); + }); + + it('when the reply matches the text up to surrounding whitespace', () => { + expect(findPendingQuestion(streamed(LEGACY_RESULT, `${REPLY}\n`), 'ready')).not.toBeNull(); + }); + + it('after an error status: the stream has ended', () => { + expect(findPendingQuestion(streamed(), 'error')).not.toBeNull(); + }); +}); + +describe('findPendingQuestion — the card stays away', () => { + it('while the stream runs, or while a message still streams', () => { + expect(findPendingQuestion(streamed(), 'streaming')).toBeNull(); + expect(findPendingQuestion(streamed(), 'submitted')).toBeNull(); + const messages = streamed(); + messages[1] = { ...messages[1], streaming: true }; + expect(findPendingQuestion(messages, 'ready')).toBeNull(); + }); + + it('when the turn ended on other text than the question', () => { + expect(findPendingQuestion(streamed(LEGACY_RESULT, 'Here is your revenue.'), 'ready')).toBeNull(); + }); + + it('when another message ended the turn after the question', () => { + const messages = [...reloaded(), { id: 'a3', role: 'assistant' as const, content: 'Something else.' }]; + expect(findPendingQuestion(messages, 'ready')).toBeNull(); + }); + + it('when two questions came in one batch', () => { + const messages = streamed(); + messages[1] = { + ...messages[1], + toolInvocations: [ + ...(messages[1].toolInvocations ?? []), + { toolCallId: 'call_q2', toolName: 'ask_which', state: 'output-available', result: LEGACY_RESULT }, + ], + }; + expect(findPendingQuestion(messages, 'ready')).toBeNull(); + }); + + it('when a user message follows it — a HITL continuation counts as moving on', () => { + expect(findPendingQuestion([...streamed(), { id: 'u2', role: 'user', content: 'Booked revenue' }], 'ready')) + .toBeNull(); + expect(findPendingQuestion([...streamed(), { id: 'u2', role: 'user', content: '[HITL pa_1] approved' }], 'ready')) + .toBeNull(); + }); + + it('when a typed message is queued: it is sent, and sending something else is a skip', () => { + expect(findPendingQuestion(streamed(), 'ready', { queued: true })).toBeNull(); + }); + + it('while a write approval waits in the same segment; it comes back once decided', () => { + const messages = streamed(); + messages[1] = { + ...messages[1], + toolInvocations: [ + { toolCallId: 'call_w', toolName: 'update_record', state: 'approval-requested', pendingActionId: 'pa_1' }, + ...(messages[1].toolInvocations ?? []), + ], + }; + expect(findPendingQuestion(messages, 'ready')).toBeNull(); + expect(findPendingQuestion(messages, 'ready', { toolDecisions: { call_w: { state: 'pending' } } })).toBeNull(); + expect(findPendingQuestion(messages, 'ready', { toolDecisions: { call_w: { state: 'success' } } })) + .not.toBeNull(); + }); + + it('when the user skipped it on this device', () => { + expect(findPendingQuestion(streamed(), 'ready', { skipped: new Set(['call_q']) })).toBeNull(); + expect(findPendingQuestion(streamed(), 'ready', { skipped: new Set(['call_other']) })).not.toBeNull(); + }); + + it('on a read-only transcript', () => { + expect(findPendingQuestion(streamed(), 'ready', { readOnly: true })).toBeNull(); + }); + + it('when the result is not a question envelope, or the tool failed', () => { + expect(findPendingQuestion(streamed({ ...LEGACY_RESULT, readings: ['Only one'] }), 'ready')).toBeNull(); + const failed = streamed(); + failed[1] = { + ...failed[1], + toolInvocations: [{ toolCallId: 'call_q', toolName: 'ask_which', state: 'output-error', errorText: 'boom' }], + }; + expect(findPendingQuestion(failed, 'ready')).toBeNull(); + }); +}); + +describe('findQuestions — every question the conversation holds', () => { + it('finds answered questions in history too, one per segment, by the message that draws them', () => { + const messages: ChatbotEnhancedMessage[] = [ + ...reloaded(), + { id: 'u2', role: 'user', content: 'Booked revenue' }, + { id: 'a3', role: 'assistant', content: 'Booked revenue this quarter is 1.2M.' }, + ]; + expect(findQuestions(messages).map((q) => [q.toolCallId, q.messageId])).toEqual([['call_q', 'a2']]); + expect(findPendingQuestion(messages, 'ready')).toBeNull(); + }); + + it('finds nothing where the reply does not match', () => { + expect(findQuestions(streamed(LEGACY_RESULT, 'Something else.'))).toEqual([]); + }); +}); diff --git a/ui/packages/plugin-chatbot/src/chat/composerGate.tsx b/ui/packages/plugin-chatbot/src/chat/composerGate.tsx new file mode 100644 index 00000000000..927d100e9ca --- /dev/null +++ b/ui/packages/plugin-chatbot/src/chat/composerGate.tsx @@ -0,0 +1,74 @@ +/** + * 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 * as React from 'react'; + +export interface ComposerGateProps { + /** + * What takes the composer's place while `open` (the question card today). + * Rendered whenever given, hidden while closed, so a holder keeps its own + * state across a close and a reopen (a send that fails reopens the card + * with the choice still made). + */ + holder?: React.ReactNode; + /** The holder has the composer's place. */ + open: boolean; + /** The composer. */ + children: React.ReactNode; +} + +/** + * The composer's place, held by one thing at a time: the composer, or a + * holder that replaces it (a question card; later an approval card). + * + * The composer is never unmounted: while the holder is open it is hidden and + * `inert`, so its draft, its attachments and its uncontrolled textarea all + * survive, and keyboard focus that was in it goes back to it once the holder + * closes. The holder never takes focus itself. + */ +export function ComposerGate({ holder, open, children }: ComposerGateProps) { + const composerRef = React.useRef(null); + const holderRef = React.useRef(null); + const focusedBeforeOpen = React.useRef(null); + const held = open && holder != null; + + // A layout effect runs after the commit and before the browser's focus + // fix-up, so the element that had focus is still `activeElement` here. + React.useLayoutEffect(() => { + if (held) { + const active = document.activeElement; + focusedBeforeOpen.current = + active instanceof HTMLElement && composerRef.current?.contains(active) ? active : null; + return; + } + const target = focusedBeforeOpen.current; + focusedBeforeOpen.current = null; + if (!target || !target.isConnected) return; + const active = document.activeElement; + const lost = !active || active === document.body || Boolean(holderRef.current?.contains(active)); + if (lost) target.focus(); + }, [held]); + + return ( + <> + {holder != null ? ( + + ) : null} + + + ); +} diff --git a/ui/packages/plugin-chatbot/src/chat/pendingQuestion.ts b/ui/packages/plugin-chatbot/src/chat/pendingQuestion.ts new file mode 100644 index 00000000000..fe3d5c34cd4 --- /dev/null +++ b/ui/packages/plugin-chatbot/src/chat/pendingQuestion.ts @@ -0,0 +1,168 @@ +/** + * 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. + */ + +/** + * Where the conversation holds an AI question, and when that question is + * still waiting for its answer (question-card topic, Q2b). + * + * A question is a question tool's result whose envelope + * (`parseAskQuestionEnvelope`, `@objectstack/spec/ai`) ended the turn: its + * `reply` is the plain text the turn ended with. The answer is the next user + * message; nothing here is turn state. + * + * A "segment" is the run of assistant messages between two user messages. A + * tool-ended turn arrives in two shapes: streamed it is ONE assistant message + * (tool parts plus text), reloaded it is TWO (one carrying the tool parts, one + * carrying the text). Both are one segment, so both read the same. + * + * Pure functions over the rendered message list, so the card, the in-thread + * summary and the regenerate button all read one answer. + */ +import { parseAskQuestionEnvelope, type AskQuestionEnvelopeParsed } from '@objectstack/spec/ai'; +import { parseResultEnvelope } from '../toolResultParsers'; +import { isToolCallPlaceholder } from './answerLayout'; +import type { ChatbotEnhancedMessage, ChatbotEnhancedToolInvocation, ToolDecisionState } from './types'; + +/** A question the conversation holds. */ +export interface ChatQuestion { + /** The question tool call's id: the question's identity (skip marks key on it). */ + toolCallId: string; + envelope: AskQuestionEnvelopeParsed; + /** The message whose text is the envelope's `reply`: where the question is drawn. */ + messageId: string; +} + +/** What the composer knows beside the message list. */ +export interface PendingQuestionContext { + /** A message the user typed during the turn waits to be sent. */ + queued?: boolean; + /** Question tool-call ids the user skipped on this device. */ + skipped?: ReadonlySet; + /** A read-only transcript (a share page): it has no composer to replace. */ + readOnly?: boolean; + /** The host's approval decisions, by tool-call id (`ChatbotEnhancedProps.toolDecisions`). */ + toolDecisions?: Record; +} + +/** + * The stream statuses a chat reports (the AI SDK's `ChatStatus`). A question + * is pending only once the stream has ended. + */ +export type ChatStreamStatus = 'submitted' | 'streaming' | 'ready' | 'error'; + +function questionOf(tool: ChatbotEnhancedToolInvocation): AskQuestionEnvelopeParsed | null { + if (tool.errorText || tool.result === undefined) return null; + if (tool.state && tool.state !== 'output-available') return null; + const envelope = parseResultEnvelope(tool.result); + return envelope ? parseAskQuestionEnvelope(envelope) : null; +} + +function isShownText(message: ChatbotEnhancedMessage): boolean { + const text = message.content.trim(); + return text.length > 0 && !isToolCallPlaceholder(text); +} + +/** The segments of a message list: the assistant runs, each with its start index. */ +function segmentsOf(messages: readonly ChatbotEnhancedMessage[]): Array<{ start: number; end: number }> { + const segments: Array<{ start: number; end: number }> = []; + let start = 0; + messages.forEach((message, index) => { + if (message.role !== 'user') return; + if (index > start) segments.push({ start, end: index }); + start = index + 1; + }); + if (messages.length > start) segments.push({ start, end: messages.length }); + return segments; +} + +/** + * The question one segment ended on, or `null`. The segment holds exactly one + * question result, and that result's `reply` equals the segment's last shown + * assistant text, at or after the result. That excludes two questions in one + * batch, another tool or text ending the turn after the question, and a turn + * whose text is not the question's. + */ +function questionInSegment( + messages: readonly ChatbotEnhancedMessage[], + start: number, + end: number, +): ChatQuestion | null { + let found: { toolCallId: string; envelope: AskQuestionEnvelopeParsed; index: number } | null = null; + let count = 0; + let lastText: { message: ChatbotEnhancedMessage; index: number } | null = null; + for (let i = start; i < end; i += 1) { + const message = messages[i]; + if (message.role !== 'assistant') continue; + for (const tool of message.toolInvocations ?? []) { + const envelope = questionOf(tool); + if (!envelope) continue; + count += 1; + found = { toolCallId: tool.toolCallId, envelope, index: i }; + } + if (isShownText(message)) lastText = { message, index: i }; + } + if (count !== 1 || !found || !lastText || lastText.index < found.index) return null; + if (lastText.message.content.trim() !== found.envelope.reply.trim()) return null; + return { toolCallId: found.toolCallId, envelope: found.envelope, messageId: lastText.message.id }; +} + +/** Every question the conversation holds, oldest first (at most one per segment). */ +export function findQuestions(messages: readonly ChatbotEnhancedMessage[]): ChatQuestion[] { + const questions: ChatQuestion[] = []; + for (const { start, end } of segmentsOf(messages)) { + const question = questionInSegment(messages, start, end); + if (question) questions.push(question); + } + return questions; +} + +function hasPendingApproval( + messages: readonly ChatbotEnhancedMessage[], + start: number, + decisions: Record | undefined, +): boolean { + for (let i = start; i < messages.length; i += 1) { + for (const tool of messages[i].toolInvocations ?? []) { + if (tool.state !== 'approval-requested') continue; + const decision = decisions?.[tool.toolCallId]; + if (!decision || decision.state === 'pending') return true; + } + } + return false; +} + +/** + * The question waiting for an answer, or `null`. A question is pending only + * while ALL hold: + * 1. the stream has ended; + * 2. the last segment (no user message after it, a HITL continuation + * included) ended on a question (`findQuestions`' rule); + * 3. no message typed during the turn is queued — it is sent, and sending + * something else is a skip; + * 4. no write approval waits in the same segment — the approval card comes + * first; + * 5. the user has not skipped it on this device; + * 6. the transcript is not read-only. + */ +export function findPendingQuestion( + messages: readonly ChatbotEnhancedMessage[], + status: ChatStreamStatus, + context: PendingQuestionContext = {}, +): ChatQuestion | null { + if (status === 'submitted' || status === 'streaming') return null; + if (context.readOnly || context.queued) return null; + if (messages.some((message) => message.streaming)) return null; + const segments = segmentsOf(messages); + const last = segments[segments.length - 1]; + if (!last || last.end !== messages.length) return null; + const question = questionInSegment(messages, last.start, last.end); + if (!question) return null; + if (context.skipped?.has(question.toolCallId)) return null; + if (hasPendingApproval(messages, last.start, context.toolDecisions)) return null; + return question; +} diff --git a/ui/packages/plugin-chatbot/src/chat/questionMessage.tsx b/ui/packages/plugin-chatbot/src/chat/questionMessage.tsx new file mode 100644 index 00000000000..91ae36aa447 --- /dev/null +++ b/ui/packages/plugin-chatbot/src/chat/questionMessage.tsx @@ -0,0 +1,79 @@ +/** + * 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 * as React from 'react'; +import { ChevronRight } from 'lucide-react'; +import type { AskQuestionEnvelopeParsed } from '@objectstack/spec/ai'; +import { cn } from '@object-ui/components'; +import { useQuestionCardTranslation } from '../useQuestionCardTranslation'; + +export interface QuestionMessageProps { + envelope: AskQuestionEnvelopeParsed; + /** The question waits for its answer: the card holds the options, so the message does not repeat them. */ + pending: boolean; +} + +/** + * An AI question as the conversation shows it, drawn from the question's + * envelope rather than from its plain-text `reply` (whose bullets are model + * history, never parsed back). + * + * Pending: the lead-in and the question only; the options are on the card in + * the composer's place. Past (answered or skipped, which read the same): the + * lead-in and a collapsed 「AI asks: QUESTION」 per question that expands to + * its options. + */ +export function QuestionMessage({ envelope, pending }: QuestionMessageProps) { + const { t } = useQuestionCardTranslation(); + const aiAsks = t('chatbot.questionCard.aiAsks'); + return ( +
+ {envelope.preface ?

{envelope.preface}

: null} + {envelope.questions.map((question, index) => + pending ? ( +

+ {aiAsks}{' '} + {question.question} +

+ ) : ( +
+ + +
    + {question.options.map((option, optionIndex) => ( +
  • + {option.label} + {option.description ? ( + {option.description} + ) : null} +
  • + ))} +
+
+ ), + )} +
+ ); +} diff --git a/ui/packages/plugin-chatbot/src/chat/questionSkip.ts b/ui/packages/plugin-chatbot/src/chat/questionSkip.ts new file mode 100644 index 00000000000..99577206d78 --- /dev/null +++ b/ui/packages/plugin-chatbot/src/chat/questionSkip.ts @@ -0,0 +1,79 @@ +/** + * 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 * as React from 'react'; + +/** + * The localStorage key prefix of the question-card skip marks. One key per + * conversation, `PREFIX:CONVERSATION_ID`, whose value is the JSON list of the + * question tool-call ids the user skipped there. + * + * A skip is device-local on purpose: the server keeps no question state, and + * an answered or skipped question reads the same in the transcript. Sign-out + * clears every key under this prefix with the rest of the chat cache. + */ +export const QUESTION_SKIP_STORAGE_PREFIX = 'objectstack:ai-chat-question-skip'; + +function storageKey(conversationId: string): string { + return `${QUESTION_SKIP_STORAGE_PREFIX}:${conversationId}`; +} + +/** The skipped question ids stored for a conversation; empty when storage is unreadable. */ +export function readQuestionSkips(conversationId: string): string[] { + try { + const raw = localStorage.getItem(storageKey(conversationId)); + if (!raw) return []; + const parsed: unknown = JSON.parse(raw); + return Array.isArray(parsed) ? parsed.filter((id): id is string => typeof id === 'string') : []; + } catch { + return []; + } +} + +/** Store one more skipped question id for a conversation. Storage failures are ignored. */ +export function writeQuestionSkip(conversationId: string, toolCallId: string): void { + try { + const ids = readQuestionSkips(conversationId); + if (ids.includes(toolCallId)) return; + localStorage.setItem(storageKey(conversationId), JSON.stringify([...ids, toolCallId])); + } catch { + /* private mode, quota, disabled storage: the skip holds for this view only */ + } +} + +/** + * The skipped question ids of a conversation and a `skip` that records one. + * Without a conversation id (a host that names none) a skip holds for the + * mounted view only. + */ +export function useQuestionSkips(conversationId: string | undefined): { + skipped: ReadonlySet; + skip: (toolCallId: string) => void; +} { + const [local, setLocal] = React.useState<{ conversationId: string | undefined; ids: readonly string[] }>( + () => ({ conversationId, ids: [] }), + ); + const ids = local.conversationId === conversationId ? local.ids : []; + // What earlier views stored; a skip made in this view is in `ids` as well. + const stored = React.useMemo( + () => (conversationId ? readQuestionSkips(conversationId) : []), + [conversationId], + ); + const skipped = React.useMemo(() => new Set([...stored, ...ids]), [stored, ids]); + const skip = React.useCallback( + (toolCallId: string) => { + if (conversationId) writeQuestionSkip(conversationId, toolCallId); + setLocal((prev) => { + const prevIds = prev.conversationId === conversationId ? prev.ids : []; + return { conversationId, ids: prevIds.includes(toolCallId) ? prevIds : [...prevIds, toolCallId] }; + }); + }, + [conversationId], + ); + return { skipped, skip }; +} diff --git a/ui/packages/plugin-chatbot/src/chat/types.ts b/ui/packages/plugin-chatbot/src/chat/types.ts index 56b88e4bc38..b6656d70583 100644 --- a/ui/packages/plugin-chatbot/src/chat/types.ts +++ b/ui/packages/plugin-chatbot/src/chat/types.ts @@ -312,6 +312,13 @@ export interface ChatbotEnhancedProps extends React.HTMLAttributes Date: Fri, 27 Nov 2026 14:31:31 +0000 Subject: [PATCH 2/2] wip: docs, changesets, regenerated spec references Claude-Session: https://claude.ai/code/session_01L9qibyUpyff7pHe7vkFgA8 Co-authored-by: Claude --- .changeset/37874-ask-which-reading-length.md | 10 +++++++++ .changeset/37874-question-card-wiring.md | 17 +++++++++++++++ .../docs/frontend/plugins/plugin-chatbot.mdx | 21 +++++++++++++++++++ content/docs/references/ai/ask-question.mdx | 10 +++++---- .../ai.md | 2 +- ui/packages/plugin-chatbot/README.md | 21 +++++++++++++++++++ ...hatbotEnhanced.questionCard-37874.test.tsx | 11 ++++++---- 7 files changed, 83 insertions(+), 9 deletions(-) create mode 100644 .changeset/37874-ask-which-reading-length.md create mode 100644 .changeset/37874-question-card-wiring.md diff --git a/.changeset/37874-ask-which-reading-length.md b/.changeset/37874-ask-which-reading-length.md new file mode 100644 index 00000000000..5babf85564b --- /dev/null +++ b/.changeset/37874-ask-which-reading-length.md @@ -0,0 +1,10 @@ +--- +'@objectstack/spec': patch +--- + +fix(spec): a legacy `ask_which` reading up to 60 characters reads as a question-card option + +Clause-②: yes (widening) — widened: `parseAskQuestionEnvelope` now accepts a legacy `ask_which` result whose readings run up to 60 characters (it refused any reading over the envelope's 24-character label), and `ASK_QUESTION_LIMITS` gains `legacyReadingMaxLength: 60`. +Metadata-protocol: none + +Real `ask_which` readings are short phrases, most of them longer than the new envelope's 24-character label, so holding them to that label left most of today's questions as plain text. A legacy reading now has its own limit, 60 characters (the envelope's description length), and becomes an option label with no description. Every other rule still applies to the legacy result: one question of at most 120 characters, two to four readings, no duplicate or blank reading, a non-empty reply. The new `asked` envelope keeps its 24-character label. diff --git a/.changeset/37874-question-card-wiring.md b/.changeset/37874-question-card-wiring.md new file mode 100644 index 00000000000..f674616a45e --- /dev/null +++ b/.changeset/37874-question-card-wiring.md @@ -0,0 +1,17 @@ +--- +'@object-ui/plugin-chatbot': patch +'@object-ui/app-shell': patch +--- + +feat(plugin-chatbot): the question card takes the composer's place when the AI ends its turn on a question + +Clause-②: yes (widening) — widened: `ChatbotEnhancedProps` gains the optional `conversationId`; `@object-ui/plugin-chatbot` (and its `/core` entry) exports `QUESTION_SKIP_STORAGE_PREFIX`; `QuestionCardQuestion` and `QuestionCardOption` keep their names and shape and are now the envelope types of `@objectstack/spec/ai` (`AskQuestionParsed`, `AskQuestionOptionParsed`), with `options` still read-only. +Metadata-protocol: none + +`ChatbotEnhanced` now draws the question card itself. When a turn ends on a question tool's result that `parseAskQuestionEnvelope` reads, and the envelope's `reply` is the turn's last text, the card replaces the composer: + +- It shows only once the stream has ended, and never while a typed message is queued (that message is sent, and sending something else skips the question), while a write approval waits in the same turn, after a skip, or on a `readOnly` transcript. Both shapes of a tool-ended turn count: one streamed message, or the two messages a reloaded conversation holds. +- The composer stays mounted, hidden and `inert`, so a draft and its attachments come back after Skip or an answer, and focus that was in it returns to it. +- One click answers: the option label goes out through `onSendMessage` as the next user message. If the send fails and the message is rolled back, the card returns with its choice still made. +- Skip is remembered on this device, per conversation, under `objectstack:ai-chat-question-skip:` plus the conversation id. The console passes its conversation id, and signing out clears these keys with the rest of the chat cache. +- The conversation draws the question from its envelope instead of its plain-text reply: while pending, the question alone; once answered or skipped, a collapsed "AI asks: …" that expands to its options. Copy still copies the full reply, and a pending question shows no Regenerate. diff --git a/content/docs/frontend/plugins/plugin-chatbot.mdx b/content/docs/frontend/plugins/plugin-chatbot.mdx index d80ef99f4a2..6d5bd6daefd 100644 --- a/content/docs/frontend/plugins/plugin-chatbot.mdx +++ b/content/docs/frontend/plugins/plugin-chatbot.mdx @@ -595,6 +595,27 @@ export function PendingQuestion({ messageId, onSend, onDismiss }: { - Strings come from the `chatbot.questionCard.*` keys of `@object-ui/i18n`; the card is right-to-left in Arabic. +`ChatbotEnhanced` draws the card itself. When a turn ends on a question tool's +result that `parseAskQuestionEnvelope` (`@objectstack/spec/ai`) reads — the +question envelope, or a legacy `ask_which` result — and the envelope's `reply` +is the turn's last text, the card takes the composer's place: + +- It shows only once the stream has ended, and never while a typed message is + queued, while a write approval waits in the same turn, after a skip, or on a + `readOnly` transcript. +- The composer is not unmounted: it is hidden and `inert`, so a draft and its + attachments come back after Skip or an answer. +- An answer is sent through `onSendMessage` as the next user message. If the + send fails and the message is rolled back, the card returns with its choice. +- Skip is remembered on this device, per conversation, when the host passes + `conversationId`: the key is `QUESTION_SKIP_STORAGE_PREFIX` followed by + `:` and the conversation id. A host's sign-out cleanup should clear that + prefix. +- The conversation draws the question from its envelope: pending, the question + alone; answered or skipped, a collapsed "AI asks: …" that expands to its + options. Copy still copies the full reply, and a pending question has no + Regenerate. + ## Examples ### Simple AI Chat diff --git a/content/docs/references/ai/ask-question.mdx b/content/docs/references/ai/ask-question.mdx index fddb768377a..13ed23c30c3 100644 --- a/content/docs/references/ai/ask-question.mdx +++ b/content/docs/references/ai/ask-question.mdx @@ -38,10 +38,12 @@ Until the question tool emits this envelope, the one producer in the field is `ask_which`'s existing result, `{ success: true, status: 'asked_which', question, readings, reply }`. `parseAskQuestionEnvelope` reads it as one question whose options are -the readings, with no description, and holds the result to the same -`AskQuestionEnvelopeSchema` — one contract and one set of limits, so a -legacy result the card cannot draw (a reading over the label limit, more -than four readings) answers `null` and stays text, as it renders today. +the readings, with no description, under the envelope's limits with one +exception: a reading is a whole sentence-sized phrase, not a short label, so +it is held to its own limit, `ASK_QUESTION_LIMITS.legacyReadingMaxLength`, +and the card wraps it. Every other limit is the envelope's, so a legacy +result the card cannot draw (a reading over its limit, one reading or more +than four, a duplicate) answers `null` and stays text, as it renders today. Stored conversations keep their old results, so this reading stays as long as those rows can be shown. diff --git a/docs/audits/2026-07-unknown-key-strictness-ledger.counts/ai.md b/docs/audits/2026-07-unknown-key-strictness-ledger.counts/ai.md index 37985ae75bb..95160a223a2 100644 --- a/docs/audits/2026-07-unknown-key-strictness-ledger.counts/ai.md +++ b/docs/audits/2026-07-unknown-key-strictness-ledger.counts/ai.md @@ -19,4 +19,4 @@ hand-patch a number here** — fix the code or the verdict and regenerate. | Dir | Sites | |---|---| -| `ai/` | 114 | +| `ai/` | 116 | diff --git a/ui/packages/plugin-chatbot/README.md b/ui/packages/plugin-chatbot/README.md index 0da8067f8a7..5eca9c878ac 100644 --- a/ui/packages/plugin-chatbot/README.md +++ b/ui/packages/plugin-chatbot/README.md @@ -522,6 +522,27 @@ export function PendingQuestion({ messageId, onSend, onDismiss }: { - Strings come from the `chatbot.questionCard.*` keys of `@object-ui/i18n`; the card is right-to-left in Arabic. +`ChatbotEnhanced` draws the card itself. When a turn ends on a question tool's +result that `parseAskQuestionEnvelope` (`@objectstack/spec/ai`) reads — the +question envelope, or a legacy `ask_which` result — and the envelope's `reply` +is the turn's last text, the card takes the composer's place: + +- It shows only once the stream has ended, and never while a typed message is + queued, while a write approval waits in the same turn, after a skip, or on a + `readOnly` transcript. +- The composer is not unmounted: it is hidden and `inert`, so a draft and its + attachments come back after Skip or an answer. +- An answer is sent through `onSendMessage` as the next user message. If the + send fails and the message is rolled back, the card returns with its choice. +- Skip is remembered on this device, per conversation, when the host passes + `conversationId`: the key is `QUESTION_SKIP_STORAGE_PREFIX` followed by + `:` and the conversation id. A host's sign-out cleanup should clear that + prefix. +- The conversation draws the question from its envelope: pending, the question + alone; answered or skipped, a collapsed "AI asks: …" that expands to its + options. Copy still copies the full reply, and a pending question has no + Regenerate. + ## Bundle considerations This package depends on `streamdown`, `shiki`, `mermaid`, and `katex` diff --git a/ui/packages/plugin-chatbot/src/__tests__/ChatbotEnhanced.questionCard-37874.test.tsx b/ui/packages/plugin-chatbot/src/__tests__/ChatbotEnhanced.questionCard-37874.test.tsx index 2eb8f00df17..d2b14b36dc4 100644 --- a/ui/packages/plugin-chatbot/src/__tests__/ChatbotEnhanced.questionCard-37874.test.tsx +++ b/ui/packages/plugin-chatbot/src/__tests__/ChatbotEnhanced.questionCard-37874.test.tsx @@ -127,16 +127,19 @@ describe('Q2b — the card takes the composer place', () => { expect((screen.getByPlaceholderText('Ask…') as HTMLTextAreaElement).value).toBe(''); }); - it('a queued message holds the card back', () => { + it('a message queued during the turn holds the card back and is sent instead', async () => { + const onSendMessage = vi.fn(); const { rerender } = render( - , + , ); const textarea = screen.getByPlaceholderText('Ask…') as HTMLTextAreaElement; fireEvent.change(textarea, { target: { value: 'actually, show costs' } }); fireEvent.keyDown(textarea, { key: 'Enter' }); - rerender(); - expect(screen.getByTestId('composer-queued-item')).toBeInTheDocument(); + await screen.findByTestId('composer-queued-item'); + // The turn ends on the question while a message waits: no card, the message goes out. + rerender(); expect(screen.queryByTestId('question-card')).not.toBeInTheDocument(); + await waitFor(() => expect(onSendMessage).toHaveBeenCalledWith('actually, show costs', undefined)); }); it('no card on a read-only transcript, which draws the question as past', () => {