From 50338daa20440c67a08d19488d90a4b761278ebb Mon Sep 17 00:00:00 2001 From: "Hyeonjae.Jeong" Date: Thu, 12 Nov 2026 07:48:20 +0900 Subject: [PATCH 1/6] fix(chat): accept a written answer to Codex choice questions --- .../utils/questionPages/questionPages.test.ts | 18 +++++++++- .../utils/questionPages/questionPages.ts | 7 +++- .../src/harness/acp/acpAdapter.test.ts | 35 +++++++++++++++++++ .../src/harness/acp/acpAdapter.ts | 20 +++++++++-- packages/chat-runtime/src/harness/acp/wire.ts | 5 +++ packages/chat/src/protocol/items.ts | 1 + 6 files changed, 82 insertions(+), 4 deletions(-) diff --git a/apps/desktop/src/renderer/routes/_authenticated/_dashboard/v2-workspace/$workspaceId/hooks/usePaneRegistry/components/ChatSession/utils/questionPages/questionPages.test.ts b/apps/desktop/src/renderer/routes/_authenticated/_dashboard/v2-workspace/$workspaceId/hooks/usePaneRegistry/components/ChatSession/utils/questionPages/questionPages.test.ts index 4db001a35a9..e4076541ec0 100644 --- a/apps/desktop/src/renderer/routes/_authenticated/_dashboard/v2-workspace/$workspaceId/hooks/usePaneRegistry/components/ChatSession/utils/questionPages/questionPages.test.ts +++ b/apps/desktop/src/renderer/routes/_authenticated/_dashboard/v2-workspace/$workspaceId/hooks/usePaneRegistry/components/ChatSession/utils/questionPages/questionPages.test.ts @@ -1,6 +1,10 @@ import { describe, expect, it } from "bun:test"; import type { FormField } from "@superset/chat/protocol"; -import { isInvalidNumber, questionPages } from "./questionPages"; +import { + isInvalidNumber, + isPageAnswered, + questionPages, +} from "./questionPages"; const choice = (id: string): FormField => ({ id, @@ -25,6 +29,18 @@ describe("questionPages", () => { ]); }); + it("accepts a Codex note as the only answer to its required choice", () => { + const pages = questionPages([ + { ...choice("delivery"), required: true }, + { ...text("delivery_note1"), answerFor: "delivery" }, + ]); + expect(pages).toHaveLength(1); + const [page] = pages; + if (!page) throw new Error("Missing question"); + expect(isPageAnswered(page, { delivery_note1: "Pickup" })).toBe(true); + expect(isPageAnswered(page, { delivery_note1: " " })).toBe(false); + }); + it("keeps a generic text field on its own page", () => { const pages = questionPages([choice("priority"), text("notes")]); expect(pages.map((page) => [page.field.id, page.other?.id])).toEqual([ diff --git a/apps/desktop/src/renderer/routes/_authenticated/_dashboard/v2-workspace/$workspaceId/hooks/usePaneRegistry/components/ChatSession/utils/questionPages/questionPages.ts b/apps/desktop/src/renderer/routes/_authenticated/_dashboard/v2-workspace/$workspaceId/hooks/usePaneRegistry/components/ChatSession/utils/questionPages/questionPages.ts index 12d8b5e097b..c3edc63724a 100644 --- a/apps/desktop/src/renderer/routes/_authenticated/_dashboard/v2-workspace/$workspaceId/hooks/usePaneRegistry/components/ChatSession/utils/questionPages/questionPages.ts +++ b/apps/desktop/src/renderer/routes/_authenticated/_dashboard/v2-workspace/$workspaceId/hooks/usePaneRegistry/components/ChatSession/utils/questionPages/questionPages.ts @@ -11,7 +11,12 @@ export function questionPages(fields: readonly FormField[]): QuestionPage[] { const pages: QuestionPage[] = []; for (const field of fields) { const previous = pages.at(-1); - if (previous && field.id === `${previous.field.id}_custom`) { + if ( + previous && + (field.id === `${previous.field.id}_custom` || + (previous.field.input === "single" && + field.answerFor === previous.field.id)) + ) { previous.other = field; continue; } diff --git a/packages/chat-runtime/src/harness/acp/acpAdapter.test.ts b/packages/chat-runtime/src/harness/acp/acpAdapter.test.ts index 0e96eeb6e60..10436ce92f4 100644 --- a/packages/chat-runtime/src/harness/acp/acpAdapter.test.ts +++ b/packages/chat-runtime/src/harness/acp/acpAdapter.test.ts @@ -1709,6 +1709,41 @@ describe("AcpAdapter", () => { await adapter.dispose(); }); + it("returns a written Codex answer without requiring an unrelated choice", async () => { + const agent = new FakeAcpAgent(); + const { adapter, events } = startAdapter(agent); + await flush(); + const id = agent.requestElicitation({ + message: "Delivery?", + requestedSchema: { + type: "object", + required: ["delivery"], + properties: { + delivery: { type: "string", oneOf: [{ const: "Mail" }] }, + delivery_note: { + type: "string", + _meta: { codex: { role: "user_note", questionId: "delivery" } }, + }, + }, + }, + }); + await flush(); + const approval = itemsOf(events).find( + (item) => item.kind === "approval_request", + ); + expect(approval?.form?.fields[1]?.answerFor).toBe("delivery"); + adapter.respondToApproval(approval?.id ?? "", { + type: "form", + values: { delivery_note: "Pickup" }, + }); + await flush(); + expect(agent.responseTo(id)?.result).toEqual({ + action: "accept", + content: { delivery_note: "Pickup" }, + }); + await adapter.dispose(); + }); + it("types a generic form's answers by its schema", async () => { const agent = new FakeAcpAgent(); const { adapter, events } = startAdapter(agent); diff --git a/packages/chat-runtime/src/harness/acp/acpAdapter.ts b/packages/chat-runtime/src/harness/acp/acpAdapter.ts index a4336275641..feff42da90e 100644 --- a/packages/chat-runtime/src/harness/acp/acpAdapter.ts +++ b/packages/chat-runtime/src/harness/acp/acpAdapter.ts @@ -360,7 +360,11 @@ function formField( if (!choices) { if (property.type === "integer") return { ...base, input: "integer" }; if (property.type === "number") return { ...base, input: "number" }; - return { ...base, input: "text" }; + return { + ...base, + input: "text", + ...(property._meta ? { answerFor: property._meta.codex.questionId } : {}), + }; } return { ...base, @@ -401,7 +405,19 @@ function formErrors( value === undefined || (Array.isArray(value) ? value.length === 0 : value.trim() === ""); if (empty) { - if (field.required) errors.push(field.id); + if (field.required) { + const hasWrittenAnswer = + field.input === "single" && + fields.some((other) => { + const text = values[other.id]; + return ( + other.answerFor === field.id && + typeof text === "string" && + text.trim() !== "" + ); + }); + if (!hasWrittenAnswer) errors.push(field.id); + } continue; } const type = fieldTypes[field.id]; diff --git a/packages/chat-runtime/src/harness/acp/wire.ts b/packages/chat-runtime/src/harness/acp/wire.ts index 03d9b8ef367..dee025fdc54 100644 --- a/packages/chat-runtime/src/harness/acp/wire.ts +++ b/packages/chat-runtime/src/harness/acp/wire.ts @@ -413,7 +413,12 @@ const acpEnumOptionSchema = z.looseObject({ description: z.string().optional(), }); +const codexUserNoteSchema = z.object({ + codex: z.object({ role: z.literal("user_note"), questionId: z.string() }), +}); + export const acpElicitationPropertySchema = z.looseObject({ + _meta: codexUserNoteSchema.optional().catch(undefined), type: z.string().optional(), title: z.string().optional(), description: z.string().optional(), diff --git a/packages/chat/src/protocol/items.ts b/packages/chat/src/protocol/items.ts index 4737715b18f..8bce752490a 100644 --- a/packages/chat/src/protocol/items.ts +++ b/packages/chat/src/protocol/items.ts @@ -224,6 +224,7 @@ export const planSchema = z.looseObject({ export type Plan = z.infer; export const formFieldSchema = z.looseObject({ + answerFor: z.string().optional(), id: z.string().min(1), title: z.string().optional(), description: z.string().optional(), From 1723f878c22e052ba3d26ae9f1f337ab95e02cba Mon Sep 17 00:00:00 2001 From: "Hyeonjae.Jeong" Date: Thu, 12 Nov 2026 07:50:02 +0900 Subject: [PATCH 2/6] test(chat): assert the question link through the protocol shape --- packages/chat-runtime/src/harness/acp/acpAdapter.test.ts | 9 ++++++++- 1 file changed, 8 insertions(+), 1 deletion(-) diff --git a/packages/chat-runtime/src/harness/acp/acpAdapter.test.ts b/packages/chat-runtime/src/harness/acp/acpAdapter.test.ts index 10436ce92f4..b0e6fa3c0db 100644 --- a/packages/chat-runtime/src/harness/acp/acpAdapter.test.ts +++ b/packages/chat-runtime/src/harness/acp/acpAdapter.test.ts @@ -1731,7 +1731,14 @@ describe("AcpAdapter", () => { const approval = itemsOf(events).find( (item) => item.kind === "approval_request", ); - expect(approval?.form?.fields[1]?.answerFor).toBe("delivery"); + expect(approval).toMatchObject({ + form: { + fields: [ + { id: "delivery" }, + { id: "delivery_note", answerFor: "delivery" }, + ], + }, + }); adapter.respondToApproval(approval?.id ?? "", { type: "form", values: { delivery_note: "Pickup" }, From 9f5cd63971d85777a273a895aeb1ea0874f4a812 Mon Sep 17 00:00:00 2001 From: "Hyeonjae.Jeong" Date: Thu, 12 Nov 2026 09:48:51 +0900 Subject: [PATCH 3/6] fix(chat): associate delayed written answers with their questions --- .../utils/questionPages/questionPages.test.ts | 15 +++++++++++++++ .../utils/questionPages/questionPages.ts | 18 +++++++++++------- 2 files changed, 26 insertions(+), 7 deletions(-) diff --git a/apps/desktop/src/renderer/routes/_authenticated/_dashboard/v2-workspace/$workspaceId/hooks/usePaneRegistry/components/ChatSession/utils/questionPages/questionPages.test.ts b/apps/desktop/src/renderer/routes/_authenticated/_dashboard/v2-workspace/$workspaceId/hooks/usePaneRegistry/components/ChatSession/utils/questionPages/questionPages.test.ts index e4076541ec0..91874369d63 100644 --- a/apps/desktop/src/renderer/routes/_authenticated/_dashboard/v2-workspace/$workspaceId/hooks/usePaneRegistry/components/ChatSession/utils/questionPages/questionPages.test.ts +++ b/apps/desktop/src/renderer/routes/_authenticated/_dashboard/v2-workspace/$workspaceId/hooks/usePaneRegistry/components/ChatSession/utils/questionPages/questionPages.test.ts @@ -41,6 +41,21 @@ describe("questionPages", () => { expect(isPageAnswered(page, { delivery_note1: " " })).toBe(false); }); + it("attaches a delayed note to its own question without replacing an earlier note", () => { + const pages = questionPages([ + choice("1"), + choice("2"), + { ...text("first_note"), answerFor: "1" }, + { ...text("second_note"), answerFor: "2" }, + { ...text("duplicate"), answerFor: "1" }, + ]); + expect(pages.map(({ field, other }) => [field.id, other?.id])).toEqual([ + ["1", "first_note"], + ["2", "second_note"], + ["duplicate", undefined], + ]); + }); + it("keeps a generic text field on its own page", () => { const pages = questionPages([choice("priority"), text("notes")]); expect(pages.map((page) => [page.field.id, page.other?.id])).toEqual([ diff --git a/apps/desktop/src/renderer/routes/_authenticated/_dashboard/v2-workspace/$workspaceId/hooks/usePaneRegistry/components/ChatSession/utils/questionPages/questionPages.ts b/apps/desktop/src/renderer/routes/_authenticated/_dashboard/v2-workspace/$workspaceId/hooks/usePaneRegistry/components/ChatSession/utils/questionPages/questionPages.ts index c3edc63724a..3443724e5e0 100644 --- a/apps/desktop/src/renderer/routes/_authenticated/_dashboard/v2-workspace/$workspaceId/hooks/usePaneRegistry/components/ChatSession/utils/questionPages/questionPages.ts +++ b/apps/desktop/src/renderer/routes/_authenticated/_dashboard/v2-workspace/$workspaceId/hooks/usePaneRegistry/components/ChatSession/utils/questionPages/questionPages.ts @@ -11,13 +11,17 @@ export function questionPages(fields: readonly FormField[]): QuestionPage[] { const pages: QuestionPage[] = []; for (const field of fields) { const previous = pages.at(-1); - if ( - previous && - (field.id === `${previous.field.id}_custom` || - (previous.field.input === "single" && - field.answerFor === previous.field.id)) - ) { - previous.other = field; + const target = + field.answerFor !== undefined + ? pages.find( + ({ field: choice }) => + choice.input === "single" && choice.id === field.answerFor, + ) + : previous && field.id === `${previous.field.id}_custom` + ? previous + : undefined; + if (target && !target.other) { + target.other = field; continue; } pages.push({ field }); From dd414f94a59bfef4b129be167c815b6c0e034b43 Mon Sep 17 00:00:00 2001 From: "Hyeonjae.Jeong" Date: Thu, 12 Nov 2026 09:55:12 +0900 Subject: [PATCH 4/6] fix(chat): distinguish written answers from notes on a choice --- .../components/QuestionForm/QuestionForm.tsx | 24 ++++++-- .../components/QuestionPage/QuestionPage.tsx | 57 ++++++++++++++++--- packages/i18n/locales/cs/messages.po | 6 ++ packages/i18n/locales/de/messages.po | 6 ++ packages/i18n/locales/en/messages.po | 6 ++ packages/i18n/locales/es/messages.po | 6 ++ packages/i18n/locales/fr/messages.po | 6 ++ packages/i18n/locales/id/messages.po | 6 ++ packages/i18n/locales/it/messages.po | 6 ++ packages/i18n/locales/ja/messages.po | 6 ++ packages/i18n/locales/ko/messages.po | 6 ++ packages/i18n/locales/nl/messages.po | 6 ++ packages/i18n/locales/pl/messages.po | 6 ++ packages/i18n/locales/pt-BR/messages.po | 6 ++ packages/i18n/locales/ru/messages.po | 6 ++ packages/i18n/locales/tr/messages.po | 6 ++ packages/i18n/locales/uk/messages.po | 6 ++ packages/i18n/locales/vi/messages.po | 6 ++ packages/i18n/locales/zh-CN/messages.po | 6 ++ packages/i18n/locales/zh-TW/messages.po | 6 ++ 20 files changed, 177 insertions(+), 12 deletions(-) diff --git a/apps/desktop/src/renderer/routes/_authenticated/_dashboard/v2-workspace/$workspaceId/hooks/usePaneRegistry/components/ChatSession/components/Transcript/components/ApprovalRow/components/QuestionForm/QuestionForm.tsx b/apps/desktop/src/renderer/routes/_authenticated/_dashboard/v2-workspace/$workspaceId/hooks/usePaneRegistry/components/ChatSession/components/Transcript/components/ApprovalRow/components/QuestionForm/QuestionForm.tsx index 25d65b5e02a..d3369e134ed 100644 --- a/apps/desktop/src/renderer/routes/_authenticated/_dashboard/v2-workspace/$workspaceId/hooks/usePaneRegistry/components/ChatSession/components/Transcript/components/ApprovalRow/components/QuestionForm/QuestionForm.tsx +++ b/apps/desktop/src/renderer/routes/_authenticated/_dashboard/v2-workspace/$workspaceId/hooks/usePaneRegistry/components/ChatSession/components/Transcript/components/ApprovalRow/components/QuestionForm/QuestionForm.tsx @@ -154,9 +154,20 @@ export function QuestionForm({ }; const next = () => (last ? submit() : goTo(index + 1)); - const pick = (value: string) => { + const pick = (value: string | null) => { if (!page) return; - const { field } = page; + const { field, other } = page; + if (value === null) { + if (!other) return; + setValues((current) => { + if (current[field.id] === undefined && other.id in current) + return current; + const next = { ...current, [other.id]: "" }; + delete next[field.id]; + return next; + }); + return; + } if (field.input === "multi") { setValues((current) => { const picked = Array.isArray(current[field.id]) @@ -172,8 +183,13 @@ export function QuestionForm({ return; } const unpick = values[field.id] === value; - setValues((current) => ({ ...current, [field.id]: unpick ? "" : value })); - if (!unpick && !last) goTo(index + 1); + setValues((current) => { + const next = { ...current, [field.id]: value }; + if (unpick) delete next[field.id]; + if (other) delete next[other.id]; + return next; + }); + if (!other && !unpick && !last) goTo(index + 1); }; const choices = page ? choicesFor(page.field) : []; diff --git a/apps/desktop/src/renderer/routes/_authenticated/_dashboard/v2-workspace/$workspaceId/hooks/usePaneRegistry/components/ChatSession/components/Transcript/components/ApprovalRow/components/QuestionForm/components/QuestionPage/QuestionPage.tsx b/apps/desktop/src/renderer/routes/_authenticated/_dashboard/v2-workspace/$workspaceId/hooks/usePaneRegistry/components/ChatSession/components/Transcript/components/ApprovalRow/components/QuestionForm/components/QuestionPage/QuestionPage.tsx index 8f6286ed64d..ae1e5f72641 100644 --- a/apps/desktop/src/renderer/routes/_authenticated/_dashboard/v2-workspace/$workspaceId/hooks/usePaneRegistry/components/ChatSession/components/Transcript/components/ApprovalRow/components/QuestionForm/components/QuestionPage/QuestionPage.tsx +++ b/apps/desktop/src/renderer/routes/_authenticated/_dashboard/v2-workspace/$workspaceId/hooks/usePaneRegistry/components/ChatSession/components/Transcript/components/ApprovalRow/components/QuestionForm/components/QuestionPage/QuestionPage.tsx @@ -2,6 +2,7 @@ import { Trans, useLingui } from "@lingui/react/macro"; import type { FormField } from "@superset/chat/protocol"; import { cn } from "@superset/ui/utils"; import { Check, PencilLine } from "lucide-react"; +import { useRef } from "react"; import { answerText, type FormValues, @@ -24,7 +25,7 @@ export function QuestionPage({ question: string; choices: Choice[]; values: FormValues; - onPick: (value: string) => void; + onPick: (value: string | null) => void; onType: (fieldId: string, text: string) => void; onEnter: () => void; }) { @@ -39,6 +40,11 @@ export function QuestionPage({ const textField = freeform ? field : other; const textValue = textField ? values[textField.id] : undefined; const typed = answerText(textValue); + const inputRef = useRef(null); + const writtenChoice = field.input === "single" && other !== undefined; + const ownAnswer = + writtenChoice && current === undefined && textValue !== undefined; + const note = writtenChoice && current !== undefined; const invalid = isInvalidNumber(field, values[field.id]); return ( @@ -100,7 +106,28 @@ export function QuestionPage({ ); })} - {textField && ( + {writtenChoice && ( + + )} + {textField && (!writtenChoice || ownAnswer || note) && ( )} + {description && ( +

+ {description} +

+ )} {invalid && (

{field.input === "integer" ? ( diff --git a/apps/mobile/screens/(authenticated)/workspace/[id]/components/ChatRowView/components/ApprovalCard/components/QuestionForm/QuestionForm.tsx b/apps/mobile/screens/(authenticated)/workspace/[id]/components/ChatRowView/components/ApprovalCard/components/QuestionForm/QuestionForm.tsx index 42c9dc632c5..dbaead17fe4 100644 --- a/apps/mobile/screens/(authenticated)/workspace/[id]/components/ChatRowView/components/ApprovalCard/components/QuestionForm/QuestionForm.tsx +++ b/apps/mobile/screens/(authenticated)/workspace/[id]/components/ChatRowView/components/ApprovalCard/components/QuestionForm/QuestionForm.tsx @@ -2,8 +2,8 @@ import { Trans, useLingui } from "@lingui/react/macro"; import { answerText, type FormValues, - isInvalidNumber, isPageAnswered, + isPageComplete, questionPages, } from "@superset/chat/core"; import type { @@ -46,11 +46,7 @@ export function QuestionForm({ void onRespond(approval.id, decision).finally(() => setSending(false)); }; - const blocked = pages.some( - (entry) => - (entry.field.required && !isPageAnswered(entry, values)) || - isInvalidNumber(entry.field, values[entry.field.id]), - ); + const blocked = pages.some((entry) => !isPageComplete(entry, values)); const submit = () => { if (blocked || sending) return; const filled = Object.fromEntries( diff --git a/packages/chat-runtime/src/harness/acp/acpAdapter.test.ts b/packages/chat-runtime/src/harness/acp/acpAdapter.test.ts index fe32c972bd7..d5fa7af7010 100644 --- a/packages/chat-runtime/src/harness/acp/acpAdapter.test.ts +++ b/packages/chat-runtime/src/harness/acp/acpAdapter.test.ts @@ -1730,10 +1730,15 @@ describe("AcpAdapter", () => { required: ["delivery"], properties: { delivery: { type: "string", oneOf: [{ const: "Mail" }] }, + delivery_custom: { type: "string" }, delivery_note: { type: "string", _meta: { codex: { role: "user_note", questionId: "delivery" } }, }, + second_note: { + type: "string", + _meta: { codex: { role: "user_note", questionId: "delivery" } }, + }, }, }, }); @@ -1745,10 +1750,20 @@ describe("AcpAdapter", () => { form: { fields: [ { id: "delivery" }, + { id: "delivery_custom" }, { id: "delivery_note", answerFor: "delivery" }, + { id: "second_note", answerFor: "delivery" }, ], }, }); + for (const field of ["delivery_custom", "second_note"]) { + adapter.respondToApproval(approval?.id ?? "", { + type: "form", + values: { [field]: "Pickup" }, + }); + await flush(); + expect(agent.responseTo(id)).toBeUndefined(); + } adapter.respondToApproval(approval?.id ?? "", { type: "form", values: { delivery_note: "Pickup" }, diff --git a/packages/chat-runtime/src/harness/acp/acpAdapter.ts b/packages/chat-runtime/src/harness/acp/acpAdapter.ts index 8b2aed967db..c64a800c758 100644 --- a/packages/chat-runtime/src/harness/acp/acpAdapter.ts +++ b/packages/chat-runtime/src/harness/acp/acpAdapter.ts @@ -1,6 +1,8 @@ import { randomUUID } from "node:crypto"; import { type ChatSelections, + isPageComplete, + questionPages, type SelectionCategory, selectionCategoryOf, } from "@superset/chat/core"; @@ -394,47 +396,6 @@ function formContent( return content; } -function formErrors( - values: Record, - fields: readonly FormField[], - fieldTypes: Record, -): string[] { - const errors: string[] = []; - for (const field of fields) { - const value = values[field.id]; - const empty = - value === undefined || - (Array.isArray(value) ? value.length === 0 : value.trim() === ""); - if (empty) { - if (field.required) { - const hasWrittenAnswer = - field.input === "single" && - fields.some((other) => { - const text = values[other.id]; - return ( - other.answerFor === field.id && - typeof text === "string" && - text.trim() !== "" - ); - }); - if (!hasWrittenAnswer) errors.push(field.id); - } - continue; - } - const type = fieldTypes[field.id]; - if (type !== "number" && type !== "integer") continue; - const parsed = Number(value); - if ( - typeof value !== "string" || - !Number.isFinite(parsed) || - (type === "integer" && !Number.isInteger(parsed)) - ) { - errors.push(field.id); - } - } - return errors; -} - export class AcpAdapter implements HarnessAdapter { private readonly queue = new EventQueue(); private readonly pendingApprovals = new Map(); @@ -668,11 +629,9 @@ export class AcpAdapter implements HarnessAdapter { if ( decision.type === "form" && pending.item.form && - formErrors( - decision.values, - pending.item.form.fields, - pending.fieldTypes ?? {}, - ).length > 0 + questionPages(pending.item.form.fields).some( + (page) => !isPageComplete(page, decision.values), + ) ) { this.emitNotice( "error", diff --git a/packages/chat/src/core/questionPages/questionPages.test.ts b/packages/chat/src/core/questionPages/questionPages.test.ts index 7b50b209c11..0dfd6e326bc 100644 --- a/packages/chat/src/core/questionPages/questionPages.test.ts +++ b/packages/chat/src/core/questionPages/questionPages.test.ts @@ -3,6 +3,7 @@ import type { FormField } from "../../protocol"; import { isInvalidNumber, isPageAnswered, + isPageComplete, questionPages, } from "./questionPages"; @@ -56,6 +57,66 @@ describe("questionPages", () => { ]); }); + it("attaches a preceding note without moving its choice ahead of other questions", () => { + const pages = questionPages([ + { ...text("note"), answerFor: "delivery" }, + text("address"), + choice("delivery"), + ]); + expect(pages.map(({ field, other }) => [field.id, other?.id])).toEqual([ + ["address", undefined], + ["delivery", "note"], + ]); + }); + + it("prefers an explicit note and keeps the legacy field separately editable", () => { + const pages = questionPages([ + choice("delivery"), + text("delivery_custom"), + { ...text("note"), answerFor: "delivery" }, + ]); + expect(pages.map(({ field, other }) => [field.id, other?.id])).toEqual([ + ["delivery", "note"], + ["delivery_custom", undefined], + ]); + }); + + it("requires a linked field marked required even after picking a choice", () => { + const [page] = questionPages([ + { ...choice("delivery"), required: true }, + { ...text("note"), answerFor: "delivery", required: true }, + ]); + if (!page) throw new Error("Missing question"); + expect(isPageComplete(page, { delivery: "a" })).toBe(false); + expect(isPageComplete(page, { note: "Pickup" })).toBe(true); + expect( + isPageComplete(page, { delivery: "a", note: "Leave at reception" }), + ).toBe(true); + }); + + it("keeps a suffix field independent of an unrelated required scalar", () => { + const pages = questionPages([ + { id: "count", input: "integer", required: true }, + text("count_custom"), + ]); + expect(pages).toHaveLength(2); + const [count] = pages; + if (!count) throw new Error("Missing count"); + expect(isPageComplete(count, { count_custom: "several" })).toBe(false); + }); + + it("still requires an array selection when a required multi-choice has a legacy note", () => { + const [page] = questionPages([ + { ...choice("meals"), input: "multi", required: true }, + text("meals_custom"), + ]); + if (!page) throw new Error("Missing meals"); + expect(isPageComplete(page, { meals_custom: "a note" })).toBe(false); + expect(isPageComplete(page, { meals: ["a"], meals_custom: "a note" })).toBe( + true, + ); + }); + it("keeps a generic text field on its own page", () => { const pages = questionPages([choice("priority"), text("notes")]); expect(pages.map((page) => [page.field.id, page.other?.id])).toEqual([ @@ -71,5 +132,6 @@ describe("questionPages", () => { expect(isInvalidNumber(integer, "4")).toBe(false); expect(isInvalidNumber(integer, "")).toBe(false); expect(isInvalidNumber(number, "3.9")).toBe(false); + expect(isInvalidNumber(number, ["3"])).toBe(true); }); }); diff --git a/packages/chat/src/core/questionPages/questionPages.ts b/packages/chat/src/core/questionPages/questionPages.ts index 61f623578a8..2825909d912 100644 --- a/packages/chat/src/core/questionPages/questionPages.ts +++ b/packages/chat/src/core/questionPages/questionPages.ts @@ -8,25 +8,43 @@ export type QuestionPage = { }; export function questionPages(fields: readonly FormField[]): QuestionPage[] { - const pages: QuestionPage[] = []; - for (const field of fields) { - const previous = pages.at(-1); - const target = - field.answerFor !== undefined - ? pages.find( - ({ field: choice }) => - choice.input === "single" && choice.id === field.answerFor, - ) - : previous && field.id === `${previous.field.id}_custom` - ? previous - : undefined; - if (target && !target.other) { - target.other = field; - continue; + const pages: QuestionPage[] = fields.map((field) => ({ field })); + const choices = new Map( + pages + .filter(({ field }) => field.input === "single") + .map((page) => [page.field.id, page]), + ); + // Reserve the first explicitly linked note before applying the legacy adjacency rule. + const linked = new Set(); + for (const page of pages) { + const { field } = page; + if (field.input !== "text" || field.answerFor === undefined) continue; + const choice = choices.get(field.answerFor); + if (choice && !choice.other) { + choice.other = field; + linked.add(page); + } + } + + const questions: QuestionPage[] = []; + for (const page of pages) { + if (linked.has(page)) continue; + const { field } = page; + const previous = questions.at(-1); + if ( + (previous?.field.input === "single" || + previous?.field.input === "multi") && + !previous.other && + field.input === "text" && + field.answerFor === undefined && + field.id === `${previous.field.id}_custom` + ) { + previous.other = field; + } else { + questions.push(page); } - pages.push({ field }); } - return pages; + return questions; } export function answerText(value: string | string[] | undefined): string { @@ -39,6 +57,7 @@ export function isInvalidNumber( value: string | string[] | undefined, ): boolean { if (field.input !== "number" && field.input !== "integer") return false; + if (Array.isArray(value)) return value.length > 0; const text = answerText(value); if (text === "") return false; const parsed = Number(text); @@ -48,12 +67,32 @@ export function isInvalidNumber( ); } +function hasWrittenAnswer(page: QuestionPage, values: FormValues): boolean { + const written = page.other && values[page.other.id]; + return typeof written === "string" && written.trim() !== ""; +} + export function isPageAnswered( page: QuestionPage, values: FormValues, ): boolean { return ( - answerText(values[page.field.id]) !== "" || - (page.other !== undefined && answerText(values[page.other.id]) !== "") + answerText(values[page.field.id]) !== "" || hasWrittenAnswer(page, values) + ); +} + +export function isPageComplete( + page: QuestionPage, + values: FormValues, +): boolean { + const { field, other } = page; + const answered = + field.input === "single" + ? isPageAnswered(page, values) + : answerText(values[field.id]) !== ""; + return ( + (!field.required || answered) && + (!other?.required || hasWrittenAnswer(page, values)) && + !isInvalidNumber(field, values[field.id]) ); }