Skip to content
Open
57 changes: 57 additions & 0 deletions packages/provider-acp/src/server/elicitationForm.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -80,6 +80,63 @@ describe("parseElicitationForm", () => {
assert.deepStrictEqual(form.content({ mode: "", tags: [""] }), { mode: "", tags: [""] });
});

it("quotes titled choice values when their labels collide", () => {
const choices = [
{ const: "", title: "" },
{ const: '""', title: '""' },
{ const: "fast", title: "Fast", description: "Quick run" },
];
const form = parseElicitationForm(
decodeElicitationSchema({
type: "object",
required: ["mode", "tags"],
properties: {
mode: { type: "string", oneOf: choices },
tags: { type: "array", items: { anyOf: choices } },
},
}),
"Configure this run",
);
assert(form !== undefined);
const expected = [
['""', '""', ""],
['"\\"\\""', '"\\"\\""', '""'],
["Fast", "Quick run", "fast"],
];
assert.deepStrictEqual(
form.questions.map((question) =>
question.options.map(({ label, description, value }) => [label, description, value]),
),
[expected, expected],
);
assert.deepStrictEqual(form.content({ mode: '""', tags: ["", '""'] }), {
mode: '""',
tags: ["", '""'],
});

// A quoted value can collide with another title; every value is quoted then.
const quoted = parseElicitationForm(
{
type: "object",
properties: {
mode: {
type: "string",
oneOf: [
{ const: "a", title: "Same" },
{ const: "b", title: "Same" },
{ const: "c", title: '"a"' },
],
},
},
},
"Choose",
);
assert.deepStrictEqual(
quoted?.questions[0]?.options.map((option) => option.label),
['"a"', '"b"', '"c"'],
);
});

it("asks each question once when a choice has a free-text companion field", () => {
// OMP's ask dialog follows each choice `q<n>` with a free-text `q<n>__other` field.
const ask = (question: string, header: string) => ({
Expand Down
23 changes: 22 additions & 1 deletion packages/provider-acp/src/server/elicitationForm.ts
Original file line number Diff line number Diff line change
Expand Up @@ -51,7 +51,28 @@ function choiceOptions(
): Option[] | undefined {
if (!Array.isArray(entries) || entries.length === 0) return undefined;
const options = entries.map(toOption);
return options.every((option) => option !== undefined) ? options : undefined;
return options.every((option) => option !== undefined) ? distinctLabels(options) : undefined;
}

function hasDistinctLabels(options: ReadonlyArray<Option>): boolean {
return new Set(options.map((option) => option.label)).size === options.length;
}

function quotedLabel(option: Option): Option {
const label = JSON.stringify(option.value);
const description = option.description === option.label ? label : option.description;
return { ...option, label, description };
}

/** Colliding labels show their quoted values; quote every value if those still collide. */
function distinctLabels(options: Option[]): Option[] {
if (hasDistinctLabels(options)) return options;
const counts = new Map<string, number>();
for (const { label } of options) counts.set(label, (counts.get(label) ?? 0) + 1);
const relabeled = options.map((option) =>
counts.get(option.label) === 1 ? option : quotedLabel(option),
);
return hasDistinctLabels(relabeled) ? relabeled : options.map(quotedLabel);
}

function enumOptions(entries: unknown): Option[] | undefined {
Expand Down
108 changes: 108 additions & 0 deletions scripts/scenarios/acp-titled-empty-choice-label.e2e.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,108 @@
// @effect-diagnostics nodeBuiltinImport:off -- The scenario stages a local Replay recording.
import * as NodeFSP from "node:fs/promises";
import * as NodePath from "node:path";

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

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

const prompt = { kind: "request", method: "session/prompt" };
const fixture = [
{ type: "expect_outbound", frame: prompt },
{
type: "emit_inbound",
frame: {
kind: "request",
method: "elicitation/create",
params: {
sessionId: "demo",
mode: "form",
message: "Which value should the demo save?",
requestedSchema: {
type: "object",
properties: {
value: {
type: "string",
title: "Value",
oneOf: [
{ const: "", title: "" },
{ const: '""', title: '""' },
],
},
},
required: ["value"],
},
},
},
},
{
type: "emit_inbound",
frame: { kind: "response", method: prompt.method, result: { stopReason: "end_turn" } },
},
]
.map((entry) => JSON.stringify(entry))
.join("\n");

test(
"An ACP form distinguishes an empty choice from a pair of quotes",
WEB,
async ({ t3, app, browser }) => {
const agent = await NodeFSP.readFile(
NodePath.join(APP_DIR, "apps/server/scripts/dev-replay-agent.ts"),
"utf8",
);
const project = await t3.project("demo", {
"replay.ts": agent,
"dev-replay/showcase_transcript.ndjson": fixture,
});
const instanceId = ProviderInstanceId.make("devReplay");
const original = await runPromise(
Effect.gen(function* () {
const client = yield* rpcClient(T3_HOME, app.baseUrl ?? "");
const settings = yield* client["server.getSettings"]({});
const instance = settings.providerInstances[instanceId];
if (instance === undefined) throw new Error("Replay provider is missing");
return instance;
}).pipe(Effect.scoped),
);
const setReplay = (instance: typeof original) =>
runPromise(
Effect.gen(function* () {
const client = yield* rpcClient(T3_HOME, app.baseUrl ?? "");
yield* client["server.updateSettings"]({
patch: {},
providerInstanceMutation: { operation: "upsert", instanceId, instance },
});
}).pipe(Effect.scoped),
);

try {
await setReplay({
...original,
config: {
source: "local",
commandPath: process.execPath,
commandArgs: [NodePath.join(project, "replay.ts")],
},
});
const thread = await t3.thread({
project,
title: "Choose a value",
messages: ["Ask which value to save."],
model: "showcase",
});
await t3.open(thread);
const labels = browser.locator(
'[data-chat-composer-form="true"] button[aria-pressed] span.text-sm.font-medium',
);
await labels.nth(1).waitFor();
await app.screenshot("choice-labels");
expect(await labels.nth(0).textContent()).not.toBe(await labels.nth(1).textContent());
} finally {
await setReplay(original);
}
},
);
Loading