Skip to content
Merged
31 changes: 31 additions & 0 deletions packages/client-runtime/src/state/pendingUserInput.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -224,6 +224,37 @@ describe("buildPendingUserInputAnswers", () => {
).toBeNull();
});

it("waits for the provider's minimum number of checked options", () => {
const targets = {
id: "targets",
header: "Targets",
question: "Where should the tests run?",
options: [{ label: "Web" }, { label: "Desktop" }, { label: "Mobile" }],
multiSelect: true,
minSelections: 2,
} as const;
const answers = (selectedOptionValues: ReadonlyArray<string>) =>
buildPendingUserInputAnswers([targets], { targets: { selectedOptionValues } });

expect(answers([])).toEqual({ targets: [] });
expect(answers(["Web"])).toBeNull();
expect(answers(["Web", "Mobile"])).toEqual({ targets: ["Web", "Mobile"] });

const required = { ...targets, required: true };
for (const draft of [
{ customAnswer: "CI" },
{ attachmentCount: 1 },
{ selectedOptionValues: ["Web"], attachmentCount: 1 },
]) {
expect(buildPendingUserInputAnswers([required], { targets: draft })).toBeNull();
}
expect(
buildPendingUserInputAnswers([required], {
targets: { selectedOptionValues: ["Web", "Desktop"], attachmentCount: 1 },
}),
).toEqual({ targets: ["Web", "Desktop"] });
});

it("omits an unselected optional single choice and keeps explicit false and empty choices", () => {
const extras = {
id: "extras",
Expand Down
15 changes: 12 additions & 3 deletions packages/client-runtime/src/state/pendingUserInput.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ export interface PendingUserInputQuestion {
readonly id: string;
readonly options: ReadonlyArray<{ readonly label: string; readonly value?: string | undefined }>;
readonly multiSelect?: boolean | undefined;
readonly minSelections?: number | undefined;
readonly allowCustomAnswer?: boolean | undefined;
readonly initialAnswer?: string | undefined;
readonly required?: boolean | undefined;
Expand Down Expand Up @@ -63,13 +64,18 @@ export function resolvePendingUserInputAnswer(
draft: PendingUserInputDraftAnswer | undefined,
): PendingUserInputAnswer | null {
if (draft?.attachmentsBlocked) return null;
// Text or attachments cannot stand in for a required minimum of checked options.
const selectionsRequired =
question.multiSelect === true &&
question.required === true &&
question.minSelections !== undefined;
const customAnswer =
question.allowCustomAnswer === false
? null
: question.initialAnswer !== undefined
? (draft?.customAnswer ?? null)
: normalizeDraftAnswer(draft?.customAnswer);
if (customAnswer !== null && customAnswer.length > 0) {
if (customAnswer !== null && customAnswer.length > 0 && !selectionsRequired) {
return customAnswer;
}
if (question.required === false && question.options.length === 0) {
Expand All @@ -82,9 +88,12 @@ export function resolvePendingUserInputAnswer(
(question.allowCustomAnswer !== false && (draft?.attachmentCount ?? 0) > 0 ? "" : null);
if (question.multiSelect) {
// Checking nothing answers "none of these" unless the provider requires a choice.
return selectedOptionValues.length > 0
if (selectedOptionValues.length === 0) {
return selectionsRequired ? null : (fallback ?? (question.required ? null : []));
}
return selectedOptionValues.length >= (question.minSelections ?? 1)
? selectedOptionValues
: (fallback ?? (question.required ? null : []));
: null;
}
return selectedOptionValues[0] ?? fallback;
}
Expand Down
2 changes: 2 additions & 0 deletions packages/contracts/src/orchestrationV2.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1660,6 +1660,8 @@ export const OrchestrationV2UserInputQuestion = Schema.Struct({
}),
),
multiSelect: Schema.optional(Schema.Boolean),
/** The fewest options a non-empty multi-select answer may check. */
minSelections: Schema.optional(PositiveInt),
allowCustomAnswer: Schema.optional(Schema.Boolean),
initialAnswer: Schema.optional(Schema.String),
required: Schema.optional(Schema.Boolean),
Expand Down
21 changes: 12 additions & 9 deletions packages/provider-acp/src/server/elicitationForm.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -169,24 +169,27 @@ describe("parseElicitationForm", () => {
targets: { type: "array", minItems: 1, items },
extras: { type: "array", items },
platforms: { type: "array", minItems: 1, items },
pair: { type: "array", minItems: 2, items },
},
required: ["targets"],
required: ["targets", "pair"],
},
"Choose",
);
assert(form !== undefined);
assert.deepStrictEqual(
form.questions.map((question) => [question.id, question.required]),
form.questions.map((question) => [question.id, question.required, question.minSelections]),
[
["targets", true],
["extras", undefined],
["platforms", undefined],
["targets", true, undefined],
["extras", undefined, undefined],
["platforms", undefined, undefined],
["pair", true, 2],
],
);
assert.deepStrictEqual(form.content({ targets: ["web"], extras: [], platforms: [] }), {
targets: ["web"],
extras: [],
});
assert.isUndefined(form.content({ targets: ["web"], pair: ["web"] }));
assert.deepStrictEqual(
form.content({ targets: ["web"], extras: [], platforms: [], pair: ["web", "mobile"] }),
{ targets: ["web"], extras: [], pair: ["web", "mobile"] },
);
});

it("marks optional number and integer fields as not required and omits blank answers", () => {
Expand Down
3 changes: 3 additions & 0 deletions packages/provider-acp/src/server/elicitationForm.ts
Original file line number Diff line number Diff line change
Expand Up @@ -279,6 +279,9 @@ export function parseElicitationForm(
? {}
: { allowCustomAnswer: false }),
...(kind === "multiChoice" ? { multiSelect: true } : {}),
...(field?.kind === "multiChoice" && field.minItems > 1
? { minSelections: field.minItems }
: {}),
// An empty selection answers "none" unless the schema demands a choice.
...(field?.kind === "multiChoice" && field.minItems > 0 && required.has(id)
? { required: true }
Expand Down
114 changes: 114 additions & 0 deletions scripts/scenarios/acp-question-requires-enough-choices.e2e.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,114 @@
// @effect-diagnostics nodeBuiltinImport:off -- Seed a local recording for the dev Replay agent.
import * as NodeFSP from "node:fs/promises";
import * as NodePath from "node:path";

import { ProviderDriverKind, ProviderInstanceId } from "@t3tools/contracts";
import { expect } from "e2e";
import * as Effect from "effect/Effect";

import { T3_HOME } from "../e2e.config.ts";
import { makeState, rpcClient, runPromise, test, WEB } from "./t3.ts";

const recording = [
{ type: "expect_outbound", frame: { kind: "request", method: "session/prompt" } },
{
type: "emit_inbound",
frame: {
kind: "request",
method: "elicitation/create",
params: {
sessionId: "demo-session",
mode: "form",
message: "Choose where to run the tests.",
requestedSchema: {
type: "object",
properties: {
targets: {
type: "array",
title: "Test targets",
description: "Choose at least two targets.",
items: { type: "string", enum: ["Web", "Desktop", "Mobile"] },
minItems: 2,
},
},
required: ["targets"],
},
},
},
},
{
type: "emit_inbound",
frame: { kind: "response", method: "session/prompt", result: { stopReason: "end_turn" } },
},
]
.map((entry) => JSON.stringify(entry))
.join("\n");

test(
"An ACP question requires the requested number of choices",
WEB,
async ({ t3, app, screen }) => {
const replayAgent = await NodeFSP.readFile(
new URL("../../apps/server/scripts/dev-replay-agent.ts", import.meta.url),
"utf8",
);
const project = await t3.project("Test targets demo", {
"replay/dev-replay-agent.ts": replayAgent,
"replay/dev-replay/showcase_transcript.ndjson": recording,
});
const instanceId = ProviderInstanceId.make("scenario-choice-agent");
await runPromise(
Effect.gen(function* () {
const client = yield* rpcClient(T3_HOME, app.baseUrl ?? "");
yield* client["server.updateSettings"]({
patch: {},
providerInstanceMutation: {
operation: "upsert",
instanceId,
instance: {
driver: ProviderDriverKind.make("acpRegistry"),
displayName: "Choice fixture",
enabled: true,
config: {
source: "local",
commandPath: process.execPath,
commandArgs: [NodePath.join(project, "replay/dev-replay-agent.ts")],
},
},
},
});
}).pipe(Effect.scoped),
);
const { cli } = makeState(T3_HOME);
const started = await runPromise(
cli(
[
"thread",
"start",
project,
"Ask me where to run the tests.",
"--title",
"Choose test targets",
"--provider",
instanceId,
"--model",
"default",
"--wait",
"--json",
],
[2],
),
);
const { threadId } = JSON.parse(started.stdout) as { threadId: string };
await t3.open({ threadId });

const web = screen.getByRole("button", { name: /^Web\b/ });
const submit = screen.getByRole("button", { name: "Submit", exact: true });
await web.tap();
await expect(web).toHaveAttribute("aria-pressed", "true");
await app.screenshot("one-of-two-required-targets");
await expect(submit).toBeDisabled();
await screen.getByRole("button", { name: /^Mobile\b/ }).tap();
await expect(submit).toBeEnabled();
},
);
Loading