The best way to control Claude Code, Codex and more from any computer or phone
chore: make agent mistakes fail early (#26167)
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
Theo Browne committed
Oct 29, 2026 at 01:51 UTC
da1eab01f712a6c1595ff0f51e7f4fea9b7ebacb
19 files changed
+490
-570
.github/workflows/agent-context-budget.yml
+1
-1
@@ -51,5 +51,5 @@ jobs:
51
echo "Accepted by the agent-context-increase label."
52
exit 0
53
fi
54
- echo "::error file=$BUDGET::Agent context grew compared to main. Cut the added text, or ask a maintainer to add the agent-context-increase label."
54
+ echo "::error file=$BUDGET::Agent context grew compared to main. Cut the added text and rerun the evals that cover it (evals/README.md), or ask a maintainer to add the agent-context-increase label."
55
exit 1
AGENTS.md
+1
-1
@@ -98,7 +98,7 @@ An empty database is a bad test. Seed your worktree's `.t3` with a copy of real
98
99
## Verifying
100
101
-- Before you push, run `vp run check:changed`. It runs CI's fast checks for changed files: format, lint, knip, typecheck of affected packages and dependents, and tests beside changes. CI still runs the full test suites.
101
+- Before you push, run `vp run check:changed`. It runs CI's fast checks for changed files: format, lint, knip, typecheck of affected packages and dependents, tests beside changes, and the cross-file checks those miss. CI still runs the full test suites.
102
- While you iterate, run `vp test run <files>`. For big files, add `-t "<name>"`.
103
- Use `vp run typecheck`, not `npx tsc`; it caches per package. Both run tsc-rs (`typescript` is the `@tsc-rs/typescript` drop-in).
104
- Run `node -e` snippets from `apps/server` or the owning package. `effect` does not resolve from the repo root.
apps/mobile/src/features/threads/PendingUserInputCard.tsx
+2
-2
@@ -26,9 +26,9 @@ import { useMarkdownPreviewStyles } from "../files/FileMarkdownPreview";
26
import { useLiveThreadLinkLabels } from "../../state/entities";
27
import {
28
isPendingUserInputOptionSelected,
29
- type PendingUserInput,
29
type PendingUserInputDraftAnswer,
31
-} from "../../lib/threadActivity";
30
+} from "@t3tools/client-runtime/state/pending-user-input";
31
+import type { PendingUserInput } from "../../lib/threadActivity";
32
33
export interface PendingUserInputCardProps {
34
readonly environmentId: EnvironmentId;
apps/mobile/src/features/threads/ThreadDetailScreen.tsx
+1
-1
@@ -157,10 +157,10 @@ import { appAtomRegistry } from "../../state/atom-registry";
157
import { threadStreamHaptics } from "./threadStreamHaptics";
158
import { useAtomCommand } from "../../state/use-atom-command";
159
import { useDelayedStatus } from "../../lib/useDelayedStatus";
160
+import type { PendingUserInputDraftAnswer } from "@t3tools/client-runtime/state/pending-user-input";
161
import type {
162
PendingApproval,
163
PendingUserInput,
163
- PendingUserInputDraftAnswer,
164
ThreadFeedEntry,
165
ThreadFeedLatestRun,
166
} from "../../lib/threadActivity";
apps/mobile/src/lib/threadActivity.test.ts
-104
@@ -31,10 +31,6 @@ import {
31
type ThreadFeedCache,
32
type ThreadFeedEntry,
33
type ThreadFeedLatestRun,
34
- togglePendingUserInputOptionSelection,
35
- setPendingUserInputCustomAnswer,
36
- isPendingUserInputOptionSelected,
37
- buildPendingUserInputAnswers,
34
} from "./threadActivity";
35
36
const threadId = ThreadId.make("thread-1");
@@ -1368,17 +1364,6 @@ describe("retained v2 feed presentation", () => {
1364
});
1365
});
1366
1371
-const singleSelectQuestion = {
1372
- id: "runtime",
1373
- header: "Runtime",
1374
- question: "Which runtime should be used?",
1375
- options: [
1376
- { label: "Go", description: "One binary" },
1377
- { label: "Node.js", description: "Reuse TypeScript" },
1378
- ],
1379
- multiSelect: false,
1380
-} as const;
1381
-
1367
describe("subagent continued by a later turn", () => {
1368
const run2 = RunId.make("run-2");
1369
const at = (second: number) => `2026-10-09T10:00:${String(second).padStart(2, "0")}.000Z`;
@@ -1454,95 +1439,6 @@ describe("subagent continued by a later turn", () => {
1439
});
1440
});
1441
1457
-describe("pending user input answers", () => {
1458
- it("preserves exact editor text, including a deliberately cleared answer", () => {
1459
- const question = { ...singleSelectQuestion, initialAnswer: " Proposed message\n" };
1460
- expect(
1461
- buildPendingUserInputAnswers([question], {
1462
- runtime: { customAnswer: question.initialAnswer },
1463
- }),
1464
- ).toEqual({ runtime: question.initialAnswer });
1465
- expect(
1466
- buildPendingUserInputAnswers([question], {
1467
- runtime: { customAnswer: " Edited message\n\n" },
1468
- }),
1469
- ).toEqual({ runtime: " Edited message\n\n" });
1470
- expect(buildPendingUserInputAnswers([question], { runtime: { customAnswer: "" } })).toEqual({
1471
- runtime: "",
1472
- });
1473
- expect(buildPendingUserInputAnswers([question], { runtime: { customAnswer: " \n" } })).toEqual({
1474
- runtime: " \n",
1475
- });
1476
- expect(setPendingUserInputCustomAnswer(question, { selectedOptionValues: ["Go"] }, "")).toEqual(
1477
- { customAnswer: "" },
1478
- );
1479
- });
1480
-});
1481
-
1482
-describe("provider question values", () => {
1483
- const question = {
1484
- ...singleSelectQuestion,
1485
- allowCustomAnswer: false,
1486
- options: [
1487
- { label: "Same label", value: " exact first ", description: "First" },
1488
- { label: "Same label", value: "second", description: "Second" },
1489
- ],
1490
- } as const;
1491
-
1492
- it("submits raw option values and distinguishes duplicate labels", () => {
1493
- const first = togglePendingUserInputOptionSelection(question, undefined, " exact first ");
1494
- expect(isPendingUserInputOptionSelected(question, first, " exact first ")).toBe(true);
1495
- expect(isPendingUserInputOptionSelected(question, first, "second")).toBe(false);
1496
- expect(buildPendingUserInputAnswers([question], { runtime: first })).toEqual({
1497
- runtime: " exact first ",
1498
- });
1499
- expect(togglePendingUserInputOptionSelection(question, first, "Same label")).toBe(first);
1500
- });
1501
-
1502
- it("rejects arbitrary text when the provider only accepts offered options", () => {
1503
- expect(setPendingUserInputCustomAnswer(question, undefined, "Other")).toEqual({});
1504
- expect(
1505
- buildPendingUserInputAnswers([question], { runtime: { customAnswer: "Other" } }),
1506
- ).toBeNull();
1507
- expect(
1508
- buildPendingUserInputAnswers([question], { runtime: { selectedOptionValues: ["unknown"] } }),
1509
- ).toBeNull();
1510
- expect(
1511
- buildPendingUserInputAnswers([question], {
1512
- runtime: { selectedOptionValues: ["second"], customAnswer: "stale draft" },
1513
- }),
1514
- ).toEqual({ runtime: "second" });
1515
- });
1516
-});
1517
-
1518
-it("accepts ready attachment-only answers while preserving selected options", () => {
1519
- const question = {
1520
- id: "q",
1521
- header: "Spec",
1522
- question: "Provide a specification",
1523
- options: [{ label: "Yes", description: "Approve" }],
1524
- multiSelect: false,
1525
- };
1526
- expect(buildPendingUserInputAnswers([question], { q: { attachmentCount: 1 } })).toEqual({
1527
- q: "",
1528
- });
1529
- expect(
1530
- buildPendingUserInputAnswers([question], {
1531
- q: { attachmentCount: 1, selectedOptionValues: ["Yes"] },
1532
- }),
1533
- ).toEqual({ q: "Yes" });
1534
- expect(
1535
- buildPendingUserInputAnswers([question], {
1536
- q: { attachmentCount: 1, attachmentsBlocked: true },
1537
- }),
1538
- ).toBeNull();
1539
- expect(
1540
- buildPendingUserInputAnswers([{ ...question, allowCustomAnswer: false }], {
1541
- q: { attachmentCount: 1 },
1542
- }),
1543
- ).toBeNull();
1544
-});
1545
-
1442
it("stops stranded thinking after a steer and follows the next thought or tool", () => {
1443
const at = "2026-06-20T00:00:02.000Z";
1444
const thought = (id: string): OrchestrationV2TurnItem => ({
apps/mobile/src/lib/threadActivity.ts
-162
@@ -1,7 +1,6 @@
1
import type {
2
ThreadPendingApproval,
3
ThreadPendingUserInput,
4
- ThreadUserInputQuestion,
4
} from "@t3tools/client-runtime/state/thread-requests";
5
import { turnItemIsWorkspacePreparation } from "@t3tools/client-runtime/state/turn-item-presentation";
6
import type { ThreadCheckpointSummary } from "@t3tools/client-runtime/state/thread-checkpoints";
@@ -81,13 +80,6 @@ import {
80
export type PendingApproval = ThreadPendingApproval;
81
export type PendingUserInput = ThreadPendingUserInput;
82
84
-export interface PendingUserInputDraftAnswer {
85
- readonly selectedOptionValues?: ReadonlyArray<string>;
86
- readonly customAnswer?: string;
87
- readonly attachmentCount?: number;
88
- readonly attachmentsBlocked?: boolean;
89
-}
90
-
83
export interface ThreadFeedActivity {
84
readonly id: string;
85
readonly createdAt: string;
@@ -406,73 +398,6 @@ function isUserInputActivityGroup(entry: ThreadFeedActivityGroup): boolean {
398
return entry.activities.some((activity) => activity.workEntry.questionAnswer !== undefined);
399
}
400
409
-function normalizeDraftAnswer(value: string | undefined): string | null {
410
- if (typeof value !== "string") return null;
411
- const trimmed = value.trim();
412
- return trimmed.length > 0 ? trimmed : null;
413
-}
414
-
415
-function resolvePendingUserInputOptionValue(
416
- question: ThreadUserInputQuestion,
417
- value: string,
418
-): string | null {
419
- if (question.options.some((option) => option.value === value)) {
420
- return value;
421
- }
422
-
423
- const label = value.trim();
424
- return label.length > 0 &&
425
- question.options.some((option) => option.value === undefined && option.label.trim() === label)
426
- ? label
427
- : null;
428
-}
429
-
430
-function normalizeSelectedOptionValues(
431
- question: ThreadUserInputQuestion,
432
- value: ReadonlyArray<string> | undefined,
433
-): ReadonlyArray<string> {
434
- if (!Array.isArray(value)) {
435
- return [];
436
- }
437
-
438
- return Array.from(
439
- new Set(
440
- value
441
- .map((entry) => resolvePendingUserInputOptionValue(question, entry))
442
- .filter((entry): entry is string => entry !== null),
443
- ),
444
- );
445
-}
446
-
447
-function resolvePendingUserInputAnswer(
448
- question: ThreadUserInputQuestion,
449
- draft: PendingUserInputDraftAnswer | undefined,
450
-): string | ReadonlyArray<string> | null {
451
- if (draft?.attachmentsBlocked) return null;
452
- const customAnswer =
453
- question.allowCustomAnswer === false
454
- ? null
455
- : question.initialAnswer !== undefined
456
- ? (draft?.customAnswer ?? null)
457
- : normalizeDraftAnswer(draft?.customAnswer);
458
- if (customAnswer !== null && customAnswer.length > 0) {
459
- return customAnswer;
460
- }
461
-
462
- const selectedOptionValues = normalizeSelectedOptionValues(question, draft?.selectedOptionValues);
463
- if (question.multiSelect) {
464
- return selectedOptionValues.length > 0
465
- ? selectedOptionValues
466
- : (customAnswer ??
467
- (question.allowCustomAnswer !== false && (draft?.attachmentCount ?? 0) > 0 ? "" : null));
468
- }
469
- return (
470
- selectedOptionValues[0] ??
471
- customAnswer ??
472
- (question.allowCustomAnswer !== false && (draft?.attachmentCount ?? 0) > 0 ? "" : null)
473
- );
474
-}
475
-
401
function capitalizePhrase(value: string): string {
402
const trimmed = value.trim();
403
return trimmed.length === 0 ? value : `${trimmed.charAt(0).toUpperCase()}${trimmed.slice(1)}`;
@@ -1974,93 +1899,6 @@ function liveToolActivitySummary(activity: ThreadFeedActivity, presentTense: boo
1899
return activity.detail ?? activity.summary;
1900
}
1901
1977
-export function setPendingUserInputCustomAnswer(
1978
- question: ThreadUserInputQuestion,
1979
- draft: PendingUserInputDraftAnswer | undefined,
1980
- customAnswer: string,
1981
-): PendingUserInputDraftAnswer {
1982
- if (question.allowCustomAnswer === false) {
1983
- return draft ?? {};
1984
- }
1985
-
1986
- const selectedOptionValues =
1987
- question.initialAnswer !== undefined || customAnswer.trim().length > 0
1988
- ? undefined
1989
- : normalizeSelectedOptionValues(question, draft?.selectedOptionValues);
1990
- return {
1991
- customAnswer,
1992
- ...(selectedOptionValues && selectedOptionValues.length > 0 ? { selectedOptionValues } : {}),
1993
- };
1994
-}
1995
-
1996
-export function isPendingUserInputOptionSelected(
1997
- question: ThreadUserInputQuestion,
1998
- draft: PendingUserInputDraftAnswer | undefined,
1999
- optionValue: string,
2000
-): boolean {
2001
- if (question.allowCustomAnswer !== false && normalizeDraftAnswer(draft?.customAnswer)) {
2002
- return false;
2003
- }
2004
-
2005
- const resolvedOptionValue = resolvePendingUserInputOptionValue(question, optionValue);
2006
- return (
2007
- resolvedOptionValue !== null &&
2008
- normalizeSelectedOptionValues(question, draft?.selectedOptionValues).includes(
2009
- resolvedOptionValue,
2010
- )
2011
- );
2012
-}
2013
-
2014
-export function togglePendingUserInputOptionSelection(
2015
- question: ThreadUserInputQuestion,
2016
- draft: PendingUserInputDraftAnswer | undefined,
2017
- optionValue: string,
2018
-): PendingUserInputDraftAnswer {
2019
- const resolvedOptionValue = resolvePendingUserInputOptionValue(question, optionValue);
2020
- if (resolvedOptionValue === null) {
2021
- return draft ?? {};
2022
- }
2023
-
2024
- if (question.multiSelect) {
2025
- const selectedOptionValues = normalizeSelectedOptionValues(
2026
- question,
2027
- draft?.selectedOptionValues,
2028
- );
2029
- const nextSelectedOptionValues = selectedOptionValues.includes(resolvedOptionValue)
2030
- ? selectedOptionValues.filter((value) => value !== resolvedOptionValue)
2031
- : [...selectedOptionValues, resolvedOptionValue];
2032
-
2033
- return {
2034
- customAnswer: "",
2035
- ...(nextSelectedOptionValues.length > 0
2036
- ? { selectedOptionValues: nextSelectedOptionValues }
2037
- : {}),
2038
- };
2039
- }
2040
-
2041
- return {
2042
- customAnswer: "",
2043
- selectedOptionValues: [resolvedOptionValue],
2044
- };
2045
-}
2046
-
2047
-export function buildPendingUserInputAnswers(
2048
- questions: ReadonlyArray<ThreadUserInputQuestion>,
2049
- draftAnswers: Record<string, PendingUserInputDraftAnswer>,
2050
-): Record<string, string | ReadonlyArray<string>> | null {
2051
- const answers: Record<string, string | ReadonlyArray<string>> = {};
2052
-
2053
- for (const question of questions) {
2054
- const answer = resolvePendingUserInputAnswer(question, draftAnswers[question.id]);
2055
- if (answer === null) {
2056
- return null;
2057
- }
2058
- answers[question.id] = answer;
2059
- }
2060
-
2061
- return answers;
2062
-}
2063
-
1902
interface ThreadFeedBuild {
1903
readonly rows: ReadonlyArray<OrchestrationV2ProjectedTurnItem>;
1904
readonly attempts: ReadonlyArray<OrchestrationV2RunAttempt> | undefined;
apps/mobile/src/state/use-selected-thread-requests.ts
+1
-1
@@ -42,7 +42,7 @@ import {
42
setPendingUserInputCustomAnswer,
43
togglePendingUserInputOptionSelection,
44
type PendingUserInputDraftAnswer,
45
-} from "../lib/threadActivity";
45
+} from "@t3tools/client-runtime/state/pending-user-input";
46
import { appAtomRegistry } from "./atom-registry";
47
import { useSelectedThreadPendingRequests } from "./use-thread-detail";
48
import { useThreadSelection } from "./use-thread-selection";
apps/server/src/provider/AgentContextBudget.test.ts
+4
-1
@@ -123,7 +123,10 @@ it.effect("agent context matches the committed budget", () =>
123
),
124
};
125
126
- expect(measured).toEqual(budget);
126
+ expect(
127
+ measured,
128
+ "Set agentContextBudget.json to the measured values. Before you cut text to fit, run the evals that cover it (evals/README.md).",
129
+ ).toEqual(budget);
130
}).pipe(
131
Effect.provide(
132
McpHttpServer.layerTools.pipe(
apps/web/src/components/chat/ChatComposer.tsx
+1
-1
@@ -241,7 +241,7 @@ import {
241
type ThreadShell,
242
} from "../../types";
243
import { type ComposerPromptHistoryPosition } from "./composerPromptHistory";
244
-import type { PendingUserInputDraftAnswer } from "../../pendingUserInput";
244
+import type { PendingUserInputDraftAnswer } from "@t3tools/client-runtime/state/pending-user-input";
245
import type {
246
LatestProposedPlanState,
247
PendingApproval,
apps/web/src/components/chat/ComposerPendingUserInputPanel.tsx
+2
-4
@@ -3,10 +3,8 @@ import { memo, use, useEffect, useEffectEvent, useRef, useState } from "react";
3
import { BackgroundThreadContext } from "./backgroundThread";
4
import { useStableCallback } from "~/hooks/useStableCallback";
5
import { type PendingUserInput } from "../../session-logic";
6
-import {
7
- derivePendingUserInputProgress,
8
- type PendingUserInputDraftAnswer,
9
-} from "../../pendingUserInput";
6
+import type { PendingUserInputDraftAnswer } from "@t3tools/client-runtime/state/pending-user-input";
7
+import { derivePendingUserInputProgress } from "../../pendingUserInput";
8
import { CheckboxMark } from "../ui/checkbox";
9
import { Collapsible, CollapsiblePanel, CollapsibleTrigger } from "../ui/collapsible";
10
import { Kbd } from "../ui/kbd";
apps/web/src/components/chat/usePendingThreadRequests.ts
+6
-4
@@ -27,13 +27,15 @@ import { useStableCallback } from "../../hooks/useStableCallback";
27
import { getUploadedAttachments, useAttachmentUploadStore } from "../../lib/attachmentUploadQueue";
28
import {
29
buildPendingUserInputAnswers,
30
+ setPendingUserInputCustomAnswer,
31
+ togglePendingUserInputOptionSelection,
32
+ type PendingUserInputDraftAnswer,
33
+} from "@t3tools/client-runtime/state/pending-user-input";
34
+import {
35
carryDisplacedCustomAnswerIntoPrompt,
36
derivePendingUserInputProgress,
37
projectPendingUserInputAnswer,
33
- setPendingUserInputCustomAnswer,
38
threadContextsReferencedByAnswer,
35
- togglePendingUserInputOptionSelection,
36
- type PendingUserInputDraftAnswer,
39
} from "../../pendingUserInput";
40
import {
41
questionAttachmentDraftId,
@@ -98,9 +100,9 @@ function makePendingCustomAnswerSetter(input: {
100
[activePendingRequestKey]: {
101
...existing[activePendingRequestKey],
102
[questionId]: setPendingUserInputCustomAnswer(
103
+ question,
104
existing[activePendingRequestKey]?.[questionId],
105
value,
103
- question,
106
),
107
},
108
}));
apps/web/src/pendingUserInput.test.ts
+11
-145
@@ -5,14 +5,10 @@ import { threadContextReference } from "./lib/composerContextRecords";
5
import { threadContextRecord } from "@t3tools/shared/composerContextReferences";
6
7
import {
8
- buildPendingUserInputAnswers,
8
carryDisplacedCustomAnswerIntoPrompt,
9
derivePendingUserInputProgress,
10
projectPendingUserInputAnswer,
12
- resolvePendingUserInputAnswer,
13
- setPendingUserInputCustomAnswer,
11
threadContextsReferencedByAnswer,
15
- togglePendingUserInputOptionSelection,
12
} from "./pendingUserInput";
13
14
describe("projectPendingUserInputAnswer", () => {
@@ -68,128 +64,6 @@ const singleSelectQuestion = {
64
multiSelect: false,
65
} as const;
66
71
-const nativeChoiceQuestion = {
72
- id: "result",
73
- header: "Result",
74
- question: "Which result should be used?",
75
- options: [
76
- { value: " first\t", label: "Result", description: "First result" },
77
- { value: "second", label: "Result", description: "Second result" },
78
- ],
79
- allowCustomAnswer: false,
80
- multiSelect: false,
81
-} as const;
82
-
83
-describe("resolvePendingUserInputAnswer", () => {
84
- it("preserves exact editor text, including a deliberately cleared answer", () => {
85
- const question = { ...singleSelectQuestion, initialAnswer: " Proposed message\n" };
86
- expect(resolvePendingUserInputAnswer(question, { customAnswer: question.initialAnswer })).toBe(
87
- question.initialAnswer,
88
- );
89
- expect(resolvePendingUserInputAnswer(question, { customAnswer: " Edited message\n\n" })).toBe(
90
- " Edited message\n\n",
91
- );
92
- expect(resolvePendingUserInputAnswer(question, { customAnswer: "" })).toBe("");
93
- expect(resolvePendingUserInputAnswer(question, { customAnswer: " \n" })).toBe(" \n");
94
- expect(
95
- setPendingUserInputCustomAnswer(
96
- { selectedOptionValues: ["Orchestration-first"] },
97
- "",
98
- question,
99
- ),
100
- ).toEqual({ customAnswer: "" });
101
- const drafts = { scope: { customAnswer: "" } };
102
- expect(derivePendingUserInputProgress([question], drafts, 0)).toMatchObject({
103
- customAnswer: "",
104
- resolvedAnswer: "",
105
- canAdvance: true,
106
- isComplete: true,
107
- });
108
- });
109
-
110
- it("prefers a custom answer over selected options", () => {
111
- expect(
112
- resolvePendingUserInputAnswer(singleSelectQuestion, {
113
- selectedOptionValues: ["Orchestration-first"],
114
- customAnswer: "Keep the existing envelope for one release",
115
- }),
116
- ).toBe("Keep the existing envelope for one release");
117
- });
118
-
119
- it("does not replace a required choice with a custom answer", () => {
120
- expect(
121
- resolvePendingUserInputAnswer(nativeChoiceQuestion, {
122
- selectedOptionValues: ["second"],
123
- customAnswer: "Use another result",
124
- }),
125
- ).toBe("second");
126
- });
127
-
128
- it("does not submit labels or unknown values when an option has a value", () => {
129
- expect(
130
- resolvePendingUserInputAnswer(nativeChoiceQuestion, {
131
- selectedOptionValues: ["Result", "unknown"],
132
- }),
133
- ).toBeNull();
134
- });
135
-});
136
-
137
-describe("togglePendingUserInputOptionSelection", () => {
138
- it("selects and removes options with the same label independently", () => {
139
- const question = { ...nativeChoiceQuestion, multiSelect: true };
140
- const firstSelected = togglePendingUserInputOptionSelection(question, undefined, " first\t");
141
- const bothSelected = togglePendingUserInputOptionSelection(question, firstSelected, "second");
142
-
143
- expect(buildPendingUserInputAnswers([question], { result: bothSelected })).toEqual({
144
- result: [" first\t", "second"],
145
- });
146
-
147
- const secondSelected = togglePendingUserInputOptionSelection(
148
- question,
149
- bothSelected,
150
- " first\t",
151
- );
152
- expect(buildPendingUserInputAnswers([question], { result: secondSelected })).toEqual({
153
- result: ["second"],
154
- });
155
- });
156
-});
157
-
158
-describe("buildPendingUserInputAnswers", () => {
159
- it("returns a canonical answer map for complete prompts", () => {
160
- expect(
161
- buildPendingUserInputAnswers(
162
- [
163
- singleSelectQuestion,
164
- {
165
- id: "compat",
166
- header: "Compat",
167
- question: "How strict should compatibility be?",
168
- options: [
169
- {
170
- label: "Keep current envelope",
171
- description: "Preserve current wire format",
172
- },
173
- ],
174
- multiSelect: false,
175
- },
176
- ],
177
- {
178
- scope: {
179
- selectedOptionValues: ["Orchestration-first"],
180
- },
181
- compat: {
182
- customAnswer: "Keep the current envelope for one release window",
183
- },
184
- },
185
- ),
186
- ).toEqual({
187
- scope: "Orchestration-first",
188
- compat: "Keep the current envelope for one release window",
189
- });
190
- });
191
-});
192
-
67
describe("pending user input question progress", () => {
68
const questions = [
69
singleSelectQuestion,
@@ -207,6 +81,17 @@ describe("pending user input question progress", () => {
81
},
82
] as const;
83
84
+ it("counts a deliberately cleared answer as answered", () => {
85
+ const question = { ...singleSelectQuestion, initialAnswer: " Proposed message\n" };
86
+ const drafts = { scope: { customAnswer: "" } };
87
+ expect(derivePendingUserInputProgress([question], drafts, 0)).toMatchObject({
88
+ customAnswer: "",
89
+ resolvedAnswer: "",
90
+ canAdvance: true,
91
+ isComplete: true,
92
+ });
93
+ });
94
+
95
it("derives the active question and advancement state", () => {
96
expect(
97
derivePendingUserInputProgress(
@@ -232,25 +117,6 @@ describe("pending user input question progress", () => {
117
});
118
});
119
235
-it("accepts attachment-only answers after every upload finishes", () => {
236
- const questions = [
237
- { id: "spec", header: "Spec", question: "Provide a spec", options: [], multiSelect: false },
238
- ];
239
- expect(buildPendingUserInputAnswers(questions, { spec: { attachmentCount: 1 } })).toEqual({
240
- spec: "",
241
- });
242
- expect(
243
- buildPendingUserInputAnswers(questions, {
244
- spec: { attachmentCount: 1, attachmentsBlocked: true },
245
- }),
246
- ).toBeNull();
247
- expect(
248
- buildPendingUserInputAnswers([{ ...questions[0]!, allowCustomAnswer: false }], {
249
- spec: { attachmentCount: 1 },
250
- }),
251
- ).toBeNull();
252
-});
253
-
120
describe("carryDisplacedCustomAnswerIntoPrompt", () => {
121
// regression: #12577 clicking a question option discarded typed text
122
it("keeps the thread draft when nothing was typed into the answer", () => {
apps/web/src/pendingUserInput.ts
+12
-118
@@ -1,6 +1,13 @@
1
import type { ThreadContextRecord, UserInputQuestion } from "@t3tools/contracts";
2
import { replaceComposerContextReferences } from "@t3tools/shared/composerContextReferences";
3
import { formatThreadLink } from "@t3tools/shared/threadLinks";
4
+import {
5
+ buildPendingUserInputAnswers,
6
+ normalizeSelectedOptionValues,
7
+ resolvePendingUserInputAnswer,
8
+ type PendingUserInputAnswer,
9
+ type PendingUserInputDraftAnswer,
10
+} from "@t3tools/client-runtime/state/pending-user-input";
11
12
import { collectInlineContextIds } from "./lib/composerContextReferences";
13
@@ -25,20 +32,13 @@ export function threadContextsReferencedByAnswer(
32
return threadContexts.filter((record) => referencedIds.has(record.contextId));
33
}
34
28
-export interface PendingUserInputDraftAnswer {
29
- selectedOptionValues?: string[];
30
- customAnswer?: string;
31
- attachmentCount?: number;
32
- attachmentsBlocked?: boolean;
33
-}
34
-
35
export interface PendingUserInputProgress {
36
questionIndex: number;
37
activeQuestion: UserInputQuestion | null;
38
activeDraft: PendingUserInputDraftAnswer | undefined;
39
- selectedOptionValues: string[];
39
+ selectedOptionValues: ReadonlyArray<string>;
40
customAnswer: string;
41
- resolvedAnswer: string | string[] | null;
41
+ resolvedAnswer: PendingUserInputAnswer | null;
42
usingCustomAnswer: boolean;
43
answeredQuestionCount: number;
44
isLastQuestion: boolean;
@@ -46,72 +46,6 @@ export interface PendingUserInputProgress {
46
canAdvance: boolean;
47
}
48
49
-function normalizeDraftAnswer(value: string | undefined): string | null {
50
- if (typeof value !== "string") {
51
- return null;
52
- }
53
-
54
- const trimmed = value.trim();
55
- return trimmed.length > 0 ? trimmed : null;
56
-}
57
-
58
-function normalizeSelectedOptionValues(value: string[] | undefined): string[] {
59
- if (!Array.isArray(value)) {
60
- return [];
61
- }
62
-
63
- // Provider option IDs must stay unchanged, including whitespace.
64
- return Array.from(new Set(value.filter((entry) => typeof entry === "string")));
65
-}
66
-
67
-export function resolvePendingUserInputAnswer(
68
- question: UserInputQuestion,
69
- draft: PendingUserInputDraftAnswer | undefined,
70
-): string | string[] | null {
71
- if (draft?.attachmentsBlocked) return null;
72
- const customAnswer =
73
- question.allowCustomAnswer === false
74
- ? null
75
- : question.initialAnswer !== undefined
76
- ? (draft?.customAnswer ?? null)
77
- : normalizeDraftAnswer(draft?.customAnswer);
78
- if (customAnswer !== null && customAnswer.length > 0) {
79
- return customAnswer;
80
- }
81
-
82
- const selectedOptionValues = normalizeSelectedOptionValues(draft?.selectedOptionValues).filter(
83
- (value) => question.options.some((option) => (option.value ?? option.label) === value),
84
- );
85
- if (question.multiSelect) {
86
- return selectedOptionValues.length > 0
87
- ? selectedOptionValues
88
- : (customAnswer ??
89
- (question.allowCustomAnswer !== false && (draft?.attachmentCount ?? 0) > 0 ? "" : null));
90
- }
91
-
92
- return (
93
- selectedOptionValues[0] ??
94
- customAnswer ??
95
- (question.allowCustomAnswer !== false && (draft?.attachmentCount ?? 0) > 0 ? "" : null)
96
- );
97
-}
98
-
99
-export function setPendingUserInputCustomAnswer(
100
- draft: PendingUserInputDraftAnswer | undefined,
101
- customAnswer: string,
102
- question?: Pick<UserInputQuestion, "initialAnswer">,
103
-): PendingUserInputDraftAnswer {
104
- const selectedOptionValues =
105
- question?.initialAnswer !== undefined || customAnswer.trim().length > 0
106
- ? undefined
107
- : normalizeSelectedOptionValues(draft?.selectedOptionValues);
108
-
109
- return {
110
- customAnswer,
111
- ...(selectedOptionValues && selectedOptionValues.length > 0 ? { selectedOptionValues } : {}),
112
- };
113
-}
114
-
49
const DISPLACED_ANSWER_SEPARATOR = "\n\n";
50
51
export function carryDisplacedCustomAnswerIntoPrompt(
@@ -128,48 +62,6 @@ export function carryDisplacedCustomAnswerIntoPrompt(
62
return `${prompt.trimEnd()}${DISPLACED_ANSWER_SEPARATOR}${displaced}`;
63
}
64
131
-export function togglePendingUserInputOptionSelection(
132
- question: UserInputQuestion,
133
- draft: PendingUserInputDraftAnswer | undefined,
134
- optionValue: string,
135
-): PendingUserInputDraftAnswer {
136
- if (question.multiSelect) {
137
- const selectedOptionValues = normalizeSelectedOptionValues(draft?.selectedOptionValues);
138
- const nextSelectedOptionValues = selectedOptionValues.includes(optionValue)
139
- ? selectedOptionValues.filter((value) => value !== optionValue)
140
- : [...selectedOptionValues, optionValue];
141
-
142
- return {
143
- customAnswer: "",
144
- ...(nextSelectedOptionValues.length > 0
145
- ? { selectedOptionValues: nextSelectedOptionValues }
146
- : {}),
147
- };
148
- }
149
-
150
- return {
151
- customAnswer: "",
152
- selectedOptionValues: [optionValue],
153
- };
154
-}
155
-
156
-export function buildPendingUserInputAnswers(
157
- questions: ReadonlyArray<UserInputQuestion>,
158
- draftAnswers: Record<string, PendingUserInputDraftAnswer>,
159
-): Record<string, string | string[]> | null {
160
- const answers: Record<string, string | string[]> = {};
161
-
162
- for (const question of questions) {
163
- const answer = resolvePendingUserInputAnswer(question, draftAnswers[question.id]);
164
- if (answer === null) {
165
- return null;
166
- }
167
- answers[question.id] = answer;
168
- }
169
-
170
- return answers;
171
-}
172
-
65
function countAnsweredPendingUserInputQuestions(
66
questions: ReadonlyArray<UserInputQuestion>,
67
draftAnswers: Record<string, PendingUserInputDraftAnswer>,
@@ -203,7 +95,9 @@ export function derivePendingUserInputProgress(
95
questionIndex: normalizedQuestionIndex,
96
activeQuestion,
97
activeDraft,
206
- selectedOptionValues: normalizeSelectedOptionValues(activeDraft?.selectedOptionValues),
98
+ selectedOptionValues: activeQuestion
99
+ ? normalizeSelectedOptionValues(activeQuestion, activeDraft?.selectedOptionValues)
100
+ : [],
101
customAnswer,
102
resolvedAnswer,
103
usingCustomAnswer:
docs/operations/development.md
+3
-1
@@ -163,7 +163,9 @@ for the security model.
163
164
`vp run check:changed` runs CI's fast checks for your branch's changes: format and lint of the
165
changed files, `knip:check` when code or a manifest changes, the generated GraphQL checks, typecheck
166
-of the affected packages and their dependents, and the test files beside the changed files. It maps
166
+of the affected packages and their dependents, and the test files beside the changed files. It also
167
+runs the checks that read other files: the agent context budget when the server is affected, and
168
+React Compiler coverage for only the changed web and mobile files. It maps
169
files to packages with [ci-changes.cjs](../../.github/scripts/ci-changes.cjs), as CI does. It
170
compares against the merge base with `origin/main`, or with a ref you pass. CI still runs the full
171
test suites and the jobs the summary lists, so a local pass does not promise a green CI run.
packages/client-runtime/package.json
+4
@@ -331,6 +331,10 @@
331
"types": "./src/state/threadExecution.ts",
332
"default": "./src/state/threadExecution.ts"
333
},
334
+ "./state/pending-user-input": {
335
+ "types": "./src/state/pendingUserInput.ts",
336
+ "default": "./src/state/pendingUserInput.ts"
337
+ },
338
"./state/thread-requests": {
339
"types": "./src/state/threadRequests.ts",
340
"default": "./src/state/threadRequests.ts"
packages/client-runtime/src/state/pendingUserInput.test.ts
new
+180
@@ -0,0 +1,180 @@
1
+import { describe, expect, it } from "vite-plus/test";
2
+
3
+import {
4
+ buildPendingUserInputAnswers,
5
+ isPendingUserInputOptionSelected,
6
+ resolvePendingUserInputAnswer,
7
+ setPendingUserInputCustomAnswer,
8
+ togglePendingUserInputOptionSelection,
9
+} from "./pendingUserInput.ts";
10
+
11
+const singleSelectQuestion = {
12
+ id: "scope",
13
+ header: "Scope",
14
+ question: "What should the plan target first?",
15
+ options: [
16
+ { label: "Orchestration-first", description: "Focus on orchestration first" },
17
+ { label: "Node.js", description: "Reuse TypeScript" },
18
+ ],
19
+ multiSelect: false,
20
+} as const;
21
+
22
+const nativeChoiceQuestion = {
23
+ id: "result",
24
+ header: "Result",
25
+ question: "Which result should be used?",
26
+ options: [
27
+ { value: " first\t", label: "Result", description: "First result" },
28
+ { value: "second", label: "Result", description: "Second result" },
29
+ ],
30
+ allowCustomAnswer: false,
31
+ multiSelect: false,
32
+} as const;
33
+
34
+describe("resolvePendingUserInputAnswer", () => {
35
+ it("preserves exact editor text, including a deliberately cleared answer", () => {
36
+ const question = { ...singleSelectQuestion, initialAnswer: " Proposed message\n" };
37
+ expect(resolvePendingUserInputAnswer(question, { customAnswer: question.initialAnswer })).toBe(
38
+ question.initialAnswer,
39
+ );
40
+ expect(resolvePendingUserInputAnswer(question, { customAnswer: " Edited message\n\n" })).toBe(
41
+ " Edited message\n\n",
42
+ );
43
+ expect(resolvePendingUserInputAnswer(question, { customAnswer: "" })).toBe("");
44
+ expect(resolvePendingUserInputAnswer(question, { customAnswer: " \n" })).toBe(" \n");
45
+ expect(
46
+ setPendingUserInputCustomAnswer(
47
+ question,
48
+ { selectedOptionValues: ["Orchestration-first"] },
49
+ "",
50
+ ),
51
+ ).toEqual({ customAnswer: "" });
52
+ });
53
+
54
+ it("prefers a custom answer over selected options", () => {
55
+ expect(
56
+ resolvePendingUserInputAnswer(singleSelectQuestion, {
57
+ selectedOptionValues: ["Orchestration-first"],
58
+ customAnswer: "Keep the existing envelope for one release",
59
+ }),
60
+ ).toBe("Keep the existing envelope for one release");
61
+ });
62
+
63
+ it("does not replace a required choice with a custom answer", () => {
64
+ expect(
65
+ resolvePendingUserInputAnswer(nativeChoiceQuestion, {
66
+ selectedOptionValues: ["second"],
67
+ customAnswer: "Use another result",
68
+ }),
69
+ ).toBe("second");
70
+ });
71
+
72
+ it("does not submit labels or unknown values when an option has a value", () => {
73
+ expect(
74
+ resolvePendingUserInputAnswer(nativeChoiceQuestion, {
75
+ selectedOptionValues: ["Result", "unknown"],
76
+ }),
77
+ ).toBeNull();
78
+ });
79
+
80
+ it("matches a label only for an option without a value", () => {
81
+ expect(
82
+ resolvePendingUserInputAnswer(singleSelectQuestion, { selectedOptionValues: [" Node.js "] }),
83
+ ).toBe("Node.js");
84
+ });
85
+
86
+ it("accepts ready attachment-only answers while preserving selected options", () => {
87
+ expect(resolvePendingUserInputAnswer(singleSelectQuestion, { attachmentCount: 1 })).toBe("");
88
+ expect(
89
+ resolvePendingUserInputAnswer(singleSelectQuestion, {
90
+ attachmentCount: 1,
91
+ selectedOptionValues: ["Node.js"],
92
+ }),
93
+ ).toBe("Node.js");
94
+ expect(
95
+ resolvePendingUserInputAnswer(singleSelectQuestion, {
96
+ attachmentCount: 1,
97
+ attachmentsBlocked: true,
98
+ }),
99
+ ).toBeNull();
100
+ expect(
101
+ resolvePendingUserInputAnswer(
102
+ { ...singleSelectQuestion, allowCustomAnswer: false },
103
+ { attachmentCount: 1 },
104
+ ),
105
+ ).toBeNull();
106
+ });
107
+});
108
+
109
+describe("togglePendingUserInputOptionSelection", () => {
110
+ it("selects and removes options with the same label independently", () => {
111
+ const question = { ...nativeChoiceQuestion, multiSelect: true };
112
+ const firstSelected = togglePendingUserInputOptionSelection(question, undefined, " first\t");
113
+ const bothSelected = togglePendingUserInputOptionSelection(question, firstSelected, "second");
114
+
115
+ expect(buildPendingUserInputAnswers([question], { result: bothSelected })).toEqual({
116
+ result: [" first\t", "second"],
117
+ });
118
+
119
+ const secondSelected = togglePendingUserInputOptionSelection(
120
+ question,
121
+ bothSelected,
122
+ " first\t",
123
+ );
124
+ expect(buildPendingUserInputAnswers([question], { result: secondSelected })).toEqual({
125
+ result: ["second"],
126
+ });
127
+ });
128
+
129
+ it("submits raw option values and leaves the draft alone for an unknown option", () => {
130
+ const first = togglePendingUserInputOptionSelection(
131
+ nativeChoiceQuestion,
132
+ undefined,
133
+ " first\t",
134
+ );
135
+ expect(isPendingUserInputOptionSelected(nativeChoiceQuestion, first, " first\t")).toBe(true);
136
+ expect(isPendingUserInputOptionSelected(nativeChoiceQuestion, first, "second")).toBe(false);
137
+ expect(buildPendingUserInputAnswers([nativeChoiceQuestion], { result: first })).toEqual({
138
+ result: " first\t",
139
+ });
140
+ expect(togglePendingUserInputOptionSelection(nativeChoiceQuestion, first, "Result")).toBe(
141
+ first,
142
+ );
143
+ });
144
+});
145
+
146
+describe("setPendingUserInputCustomAnswer", () => {
147
+ it("rejects arbitrary text when the provider only accepts offered options", () => {
148
+ expect(setPendingUserInputCustomAnswer(nativeChoiceQuestion, undefined, "Other")).toEqual({});
149
+ expect(
150
+ buildPendingUserInputAnswers([nativeChoiceQuestion], { result: { customAnswer: "Other" } }),
151
+ ).toBeNull();
152
+ expect(
153
+ buildPendingUserInputAnswers([nativeChoiceQuestion], {
154
+ result: { selectedOptionValues: ["second"], customAnswer: "stale draft" },
155
+ }),
156
+ ).toEqual({ result: "second" });
157
+ });
158
+});
159
+
160
+const compatQuestion = {
161
+ id: "compat",
162
+ header: "Compat",
163
+ question: "How strict should compatibility be?",
164
+ options: [{ label: "Keep current envelope", description: "Preserve current wire format" }],
165
+ multiSelect: false,
166
+} as const;
167
+
168
+describe("buildPendingUserInputAnswers", () => {
169
+ it("returns a canonical answer map for complete prompts", () => {
170
+ expect(
171
+ buildPendingUserInputAnswers([singleSelectQuestion, compatQuestion], {
172
+ scope: { selectedOptionValues: ["Orchestration-first"] },
173
+ compat: { customAnswer: "Keep the current envelope for one release window" },
174
+ }),
175
+ ).toEqual({
176
+ scope: "Orchestration-first",
177
+ compat: "Keep the current envelope for one release window",
178
+ });
179
+ });
180
+});
packages/client-runtime/src/state/pendingUserInput.ts
new
+176
@@ -0,0 +1,176 @@
1
+/** The question fields answer handling reads. Web and mobile question types both fit it. */
2
+export interface PendingUserInputQuestion {
3
+ readonly id: string;
4
+ readonly options: ReadonlyArray<{ readonly label: string; readonly value?: string | undefined }>;
5
+ readonly multiSelect?: boolean | undefined;
6
+ readonly allowCustomAnswer?: boolean | undefined;
7
+ readonly initialAnswer?: string | undefined;
8
+}
9
+
10
+export interface PendingUserInputDraftAnswer {
11
+ readonly selectedOptionValues?: ReadonlyArray<string>;
12
+ readonly customAnswer?: string;
13
+ readonly attachmentCount?: number;
14
+ readonly attachmentsBlocked?: boolean;
15
+}
16
+
17
+export type PendingUserInputAnswer = string | ReadonlyArray<string>;
18
+
19
+function normalizeDraftAnswer(value: string | undefined): string | null {
20
+ if (typeof value !== "string") return null;
21
+ const trimmed = value.trim();
22
+ return trimmed.length > 0 ? trimmed : null;
23
+}
24
+
25
+// Provider option values stay exact, including whitespace. Only options without a value match by label.
26
+function resolvePendingUserInputOptionValue(
27
+ question: PendingUserInputQuestion,
28
+ value: string,
29
+): string | null {
30
+ if (question.options.some((option) => option.value === value)) {
31
+ return value;
32
+ }
33
+
34
+ const label = value.trim();
35
+ return label.length > 0 &&
36
+ question.options.some((option) => option.value === undefined && option.label.trim() === label)
37
+ ? label
38
+ : null;
39
+}
40
+
41
+/** The draft's selections that name an offered option, deduplicated, in selection order. */
42
+export function normalizeSelectedOptionValues(
43
+ question: PendingUserInputQuestion,
44
+ value: ReadonlyArray<string> | undefined,
45
+): ReadonlyArray<string> {
46
+ if (!Array.isArray(value)) {
47
+ return [];
48
+ }
49
+
50
+ return Array.from(
51
+ new Set(
52
+ value
53
+ .map((entry) => resolvePendingUserInputOptionValue(question, entry))
54
+ .filter((entry): entry is string => entry !== null),
55
+ ),
56
+ );
57
+}
58
+
59
+/** The answer to submit for one question, or null while it is unanswered. */
60
+export function resolvePendingUserInputAnswer(
61
+ question: PendingUserInputQuestion,
62
+ draft: PendingUserInputDraftAnswer | undefined,
63
+): PendingUserInputAnswer | null {
64
+ if (draft?.attachmentsBlocked) return null;
65
+ const customAnswer =
66
+ question.allowCustomAnswer === false
67
+ ? null
68
+ : question.initialAnswer !== undefined
69
+ ? (draft?.customAnswer ?? null)
70
+ : normalizeDraftAnswer(draft?.customAnswer);
71
+ if (customAnswer !== null && customAnswer.length > 0) {
72
+ return customAnswer;
73
+ }
74
+
75
+ const selectedOptionValues = normalizeSelectedOptionValues(question, draft?.selectedOptionValues);
76
+ if (question.multiSelect) {
77
+ return selectedOptionValues.length > 0
78
+ ? selectedOptionValues
79
+ : (customAnswer ??
80
+ (question.allowCustomAnswer !== false && (draft?.attachmentCount ?? 0) > 0 ? "" : null));
81
+ }
82
+ return (
83
+ selectedOptionValues[0] ??
84
+ customAnswer ??
85
+ (question.allowCustomAnswer !== false && (draft?.attachmentCount ?? 0) > 0 ? "" : null)
86
+ );
87
+}
88
+
89
+export function setPendingUserInputCustomAnswer(
90
+ question: PendingUserInputQuestion,
91
+ draft: PendingUserInputDraftAnswer | undefined,
92
+ customAnswer: string,
93
+): PendingUserInputDraftAnswer {
94
+ if (question.allowCustomAnswer === false) {
95
+ return draft ?? {};
96
+ }
97
+
98
+ const selectedOptionValues =
99
+ question.initialAnswer !== undefined || customAnswer.trim().length > 0
100
+ ? undefined
101
+ : normalizeSelectedOptionValues(question, draft?.selectedOptionValues);
102
+ return {
103
+ customAnswer,
104
+ ...(selectedOptionValues && selectedOptionValues.length > 0 ? { selectedOptionValues } : {}),
105
+ };
106
+}
107
+
108
+export function isPendingUserInputOptionSelected(
109
+ question: PendingUserInputQuestion,
110
+ draft: PendingUserInputDraftAnswer | undefined,
111
+ optionValue: string,
112
+): boolean {
113
+ if (question.allowCustomAnswer !== false && normalizeDraftAnswer(draft?.customAnswer)) {
114
+ return false;
115
+ }
116
+
117
+ const resolvedOptionValue = resolvePendingUserInputOptionValue(question, optionValue);
118
+ return (
119
+ resolvedOptionValue !== null &&
120
+ normalizeSelectedOptionValues(question, draft?.selectedOptionValues).includes(
121
+ resolvedOptionValue,
122
+ )
123
+ );
124
+}
125
+
126
+/** Toggles an offered option. An unknown option returns the same draft. */
127
+export function togglePendingUserInputOptionSelection(
128
+ question: PendingUserInputQuestion,
129
+ draft: PendingUserInputDraftAnswer | undefined,
130
+ optionValue: string,
131
+): PendingUserInputDraftAnswer {
132
+ const resolvedOptionValue = resolvePendingUserInputOptionValue(question, optionValue);
133
+ if (resolvedOptionValue === null) {
134
+ return draft ?? {};
135
+ }
136
+
137
+ if (question.multiSelect) {
138
+ const selectedOptionValues = normalizeSelectedOptionValues(
139
+ question,
140
+ draft?.selectedOptionValues,
141
+ );
142
+ const nextSelectedOptionValues = selectedOptionValues.includes(resolvedOptionValue)
143
+ ? selectedOptionValues.filter((value) => value !== resolvedOptionValue)
144
+ : [...selectedOptionValues, resolvedOptionValue];
145
+
146
+ return {
147
+ customAnswer: "",
148
+ ...(nextSelectedOptionValues.length > 0
149
+ ? { selectedOptionValues: nextSelectedOptionValues }
150
+ : {}),
151
+ };
152
+ }
153
+
154
+ return {
155
+ customAnswer: "",
156
+ selectedOptionValues: [resolvedOptionValue],
157
+ };
158
+}
159
+
160
+/** Every question's answer keyed by question id, or null while any is unanswered. */
161
+export function buildPendingUserInputAnswers(
162
+ questions: ReadonlyArray<PendingUserInputQuestion>,
163
+ draftAnswers: Record<string, PendingUserInputDraftAnswer>,
164
+): Record<string, PendingUserInputAnswer> | null {
165
+ const answers: Record<string, PendingUserInputAnswer> = {};
166
+
167
+ for (const question of questions) {
168
+ const answer = resolvePendingUserInputAnswer(question, draftAnswers[question.id]);
169
+ if (answer === null) {
170
+ return null;
171
+ }
172
+ answers[question.id] = answer;
173
+ }
174
+
175
+ return answers;
176
+}
scripts/check-changed.ts
+80
-23
@@ -1,7 +1,9 @@
1
// @effect-diagnostics nodeBuiltinImport:off globalConsole:off
2
// Runs CI's fast checks for this branch's changes: format and lint of the
3
// changed files, knip, generated GraphQL operations, typecheck of the affected
4
-// packages and their dependents, and the test files beside the changed files.
4
+// packages and their dependents, the test files beside the changed files, and
5
+// the cross-file checks those miss (agent context budget, React Compiler
6
+// coverage of the changed client files).
7
// A dependency change also gets the unused-patch install check below. CI still
8
// runs the full test suites and the jobs listed in the summary.
9
//
@@ -138,6 +140,52 @@ for (const file of code) {
140
if (entry.startsWith(prefix) && TEST.test(entry)) tests.add(NodePath.join(dir, entry));
141
}
142
}
143
+// It reads files other than the ones beside it, so no changed file selects it.
144
+if (affected.includes("t3")) tests.add("apps/server/src/provider/AgentContextBudget.test.ts");
145
+
146
+// React Compiler coverage compiles every client source file, so run only the
147
+// changed files' cases, in one extra step: a -t filter in the main test step
148
+// would drop every other test. An app is skipped when the main step already
149
+// runs its coverage file unfiltered. File filters mirror each coverage test.
150
+const escapeRegExp = (text: string) => text.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
151
+const compilerApps = [
152
+ {
153
+ test: "apps/web/src/reactCompilerCoverage.test.ts",
154
+ root: "apps/web/src/",
155
+ // Test names keep the repo-relative path.
156
+ name: (file: string) => file,
157
+ compiled: (file: string) =>
158
+ /\.tsx?$/.test(file) && !/\.(test|browser)\.tsx?$/.test(file) && !file.endsWith(".gen.ts"),
159
+ // Web has only per-file cases.
160
+ always: [],
161
+ },
162
+ {
163
+ test: "apps/mobile/src/reactCompilerCoverage.test.ts",
164
+ root: "apps/mobile/src/",
165
+ name: (file: string) => file.slice("apps/mobile/".length),
166
+ compiled: (file: string) => /\.tsx?$/.test(file) && !/\.(test\.tsx?|d\.ts)$/.test(file),
167
+ // The Metro, cache, and stale-allowlist cases check more than one file, deletions included.
168
+ always: ["^(?!.*compiles )"],
169
+ },
170
+].flatMap(({ test, root: appRoot, name, compiled, always }) => {
171
+ const changed = files.filter((file) => file.startsWith(appRoot) && compiled(file));
172
+ if (changed.length === 0 || tests.has(test)) return [];
173
+ const names = changed
174
+ .filter((file) => present.includes(file))
175
+ .map((file) => `compiles ${escapeRegExp(name(file))}$`);
176
+ const pattern = [...names, ...always];
177
+ return pattern.length > 0 ? [{ test, names, pattern }] : [];
178
+});
179
+const compilerCoverage = compilerApps.length > 0 && {
180
+ name: `react compiler (${compilerApps.reduce((count, app) => count + app.names.length, 0)} files)`,
181
+ args: [
182
+ "test",
183
+ "run",
184
+ ...compilerApps.map((app) => app.test),
185
+ "-t",
186
+ compilerApps.flatMap((app) => app.pattern).join("|"),
187
+ ],
188
+};
189
190
// knip:check cannot be scoped to a package. Any code change can leave a file,
191
// export, or dependency unused (removing the last import of a helper does), so
@@ -255,33 +303,42 @@ const steps = [
303
name: `test (${tests.size} files)`,
304
args: ["test", "run", "--passWithNoTests", ...tests],
305
},
306
+ compilerCoverage,
307
].filter((step) => step !== false);
308
309
// Output is piped, so keep the colors a terminal would get.
310
const env = process.stdout.isTTY ? { ...process.env, FORCE_COLOR: "1" } : process.env;
311
+const runStep = (step: (typeof steps)[number]) =>
312
+ new Promise<{ name: string; ok: boolean; seconds: string }>((resolve) => {
313
+ const started = performance.now();
314
+ const finish = (ok: boolean, output?: Buffer) => {
315
+ const seconds = ((performance.now() - started) / 1000).toFixed(1);
316
+ console.log(`\n> vp ${step.name} ${ok ? "pass" : "FAIL"} ${seconds}s`);
317
+ if (output) process.stdout.write(output);
318
+ resolve({ name: step.name, ok, seconds });
319
+ };
320
+ // In-process steps print their own output. The patch check is first and
321
+ // takes about a second, so the commands start right after it.
322
+ if ("run" in step) return finish(step.run());
323
+ const output: Array<Buffer> = [];
324
+ const child = NodeChildProcess.spawn("vp", step.args, { cwd: root, env });
325
+ child.stdout.on("data", (chunk: Buffer) => output.push(chunk));
326
+ child.stderr.on("data", (chunk: Buffer) => output.push(chunk));
327
+ // A failed spawn emits "error", then "close" with a nonzero code.
328
+ child.on("error", (error) => output.push(Buffer.from(`${error.message}\n`)));
329
+ child.on("close", (status) => finish(status === 0, Buffer.concat(output)));
330
+ });
331
+
332
+// Vitest runs started together race to rebuild node_modules/.vitest-cache after
333
+// an install (ENOTEMPTY), so they run one after another.
334
+let previousVitest: Promise<unknown> = Promise.resolve();
335
const results = await Promise.all(
263
- steps.map(
264
- (step) =>
265
- new Promise<{ name: string; ok: boolean; seconds: string }>((resolve) => {
266
- const started = performance.now();
267
- const finish = (ok: boolean, output?: Buffer) => {
268
- const seconds = ((performance.now() - started) / 1000).toFixed(1);
269
- console.log(`\n> vp ${step.name} ${ok ? "pass" : "FAIL"} ${seconds}s`);
270
- if (output) process.stdout.write(output);
271
- resolve({ name: step.name, ok, seconds });
272
- };
273
- // In-process steps print their own output. The patch check is first and
274
- // takes about a second, so the commands start right after it.
275
- if ("run" in step) return finish(step.run());
276
- const output: Array<Buffer> = [];
277
- const child = NodeChildProcess.spawn("vp", step.args, { cwd: root, env });
278
- child.stdout.on("data", (chunk: Buffer) => output.push(chunk));
279
- child.stderr.on("data", (chunk: Buffer) => output.push(chunk));
280
- // A failed spawn emits "error", then "close" with a nonzero code.
281
- child.on("error", (error) => output.push(Buffer.from(`${error.message}\n`)));
282
- child.on("close", (status) => finish(status === 0, Buffer.concat(output)));
283
- }),
284
- ),
336
+ steps.map((step) => {
337
+ if (!("args" in step) || step.args[0] !== "test") return runStep(step);
338
+ const result = previousVitest.then(() => runStep(step));
339
+ previousVitest = result;
340
+ return result;
341
+ }),
342
);
343
344
const summary = ["check:changed summary"];
vite.config.ts
+5
-1
@@ -149,7 +149,11 @@ export default defineConfig({
149
: {}),
150
},
151
staged: {
152
- "*": "vp fmt --no-error-on-unmatched-pattern",
152
+ // In order, so lint reads the formatted file. CI lint failures cost a full round trip.
153
+ "*": ["vp fmt --no-error-on-unmatched-pattern", "vp lint --no-error-on-unmatched-pattern"],
154
+ // knip checks the whole repo, so it takes no file list. Any code or manifest change can leave
155
+ // a file, export, or dependency unused.
156
+ "{*.{js,jsx,ts,tsx,mjs,cjs,mts,cts},package.json,knip.jsonc}": () => "vp run knip:check",
157
},
158
fmt: {
159
ignorePatterns: [