TypeScript
fix(chat): fold question answers into tool activity (#11014)
maria27eb79dc719d
diff --git a/apps/mobile/src/features/threads/QuestionAnswerHistory.tsx b/apps/mobile/src/features/threads/QuestionAnswerHistory.tsxindex 2ff0a3b370f..2a08ee65bb0 100644--- a/apps/mobile/src/features/threads/QuestionAnswerHistory.tsx+++ b/apps/mobile/src/features/threads/QuestionAnswerHistory.tsx@@ -4,6 +4,7 @@ import type {UserInputAttachments,} from "@t3tools/contracts";import { Image, Linking, Pressable, View } from "react-native";+import { getQuestionAnswerText } from "@t3tools/client-runtime/work-log/user-input";import { AppText as Text } from "../../components/AppText";import { useAssetUrl } from "../../state/assets";@@ -41,6 +42,7 @@ export function QuestionAnswerHistory(props: {<View className="gap-2">{[...new Set([+ ...Object.keys(props.answer.questionTextById ?? {}),...Object.keys(props.answer.answers),...Object.keys(props.answer.attachmentsByQuestionId),]),@@ -51,12 +53,11 @@ export function QuestionAnswerHistory(props: {{props.answer.questionTextById[questionId]}</Text>) : null}- <Text className="text-sm text-foreground">- {[props.answer.answers[questionId]]- .flat()- .filter((value): value is string => typeof value === "string")- .join(", ")}- </Text>+ {getQuestionAnswerText(props.answer.answers[questionId]) ? (+ <Text className="ml-3 text-sm text-foreground-muted">+ {getQuestionAnswerText(props.answer.answers[questionId])}+ </Text>+ ) : null}{(props.answer.attachmentsByQuestionId[questionId] ?? []).map((attachment) => (<AnswerFilekey={attachment.id}diff --git a/apps/mobile/src/features/threads/thread-work-log.tsx b/apps/mobile/src/features/threads/thread-work-log.tsxindex 593a4975537..21147bc739b 100644--- a/apps/mobile/src/features/threads/thread-work-log.tsx+++ b/apps/mobile/src/features/threads/thread-work-log.tsx@@ -1,4 +1,8 @@import { QuestionAnswerHistory } from "./QuestionAnswerHistory";+import {+ getQuestionAnswerPreview,+ hasQuestionAnswer,+} from "@t3tools/client-runtime/work-log/user-input";import * as Haptics from "expo-haptics";import { Image } from "expo-image";import { type AppSymbolName, SymbolView } from "../../components/AppSymbol";@@ -745,6 +749,10 @@ const ThreadWorkLogRow = memo(function ThreadWorkLogRow(const viewedImagePath = workEntryViewedImagePath(row.workEntry);const toolPresentation = resolveWorkEntryToolPresentation(row.workEntry);const previewText = workEntryRowLabel(row.workEntry);+ const answerPreview = row.workEntry.questionAnswer+ ? getQuestionAnswerPreview(row.workEntry.questionAnswer)+ : null;+ const accessiblePreview = [previewText, answerPreview].filter(Boolean).join(": ");const displayText = workEntryRowLabel(row.workEntry, expanded);const iconIsDestructive = row.icon === "alert" || row.icon === "warning";const failed = row.status === "failure";@@ -759,7 +767,7 @@ const ThreadWorkLogRow = memo(function ThreadWorkLogRow(><PressableaccessibilityRole={canExpand ? "button" : undefined}- accessibilityLabel={failed ? `${previewText}, tool call failed` : previewText}+ accessibilityLabel={failed ? `${accessiblePreview}, tool call failed` : accessiblePreview}accessibilityHint={canExpand? `Double tap to ${expanded ? "hide" : "show"} full details. Long press to copy.`@@ -820,6 +828,17 @@ const ThreadWorkLogRow = memo(function ThreadWorkLogRow(numberOfLines={expanded ? undefined : 1}>{displayText}+ {answerPreview ? (+ <Text+ className={+ !expanded &&+ row.workEntry.questionAnswer &&+ hasQuestionAnswer(row.workEntry.questionAnswer)+ ? "text-foreground"+ : "text-foreground-subtle"+ }+ >{` ${answerPreview}`}</Text>+ ) : null}</Text></>)}diff --git a/apps/mobile/src/lib/threadActivity.ts b/apps/mobile/src/lib/threadActivity.tsindex c7d27af11d5..b7d5018edd9 100644--- a/apps/mobile/src/lib/threadActivity.ts+++ b/apps/mobile/src/lib/threadActivity.ts@@ -1,4 +1,5 @@import * as Option from "effect/Option";+import { foldUserInputActivities } from "@t3tools/client-runtime/work-log/user-input";import * as Schema from "effect/Schema";import {requestKindFromRequestType,@@ -405,7 +406,7 @@ function deriveWorkLogEntries(): DerivedWorkLogEntry[] {const ordered = Arr.sort(activities, activityOrder);const entries: DerivedWorkLogEntry[] = [];- for (const activity of ordered) {+ for (const activity of foldUserInputActivities(ordered)) {if (activity.tone !== "error" && isWorktreeSetupActivity(activity.kind)) continue;if (activity.kind === "tool.started") continue;// Like web: an agent's task.started row anchors its batch. It has a fixed@@ -936,6 +937,7 @@ function workEntryStatus(entry: WorkLogEntry): ThreadFeedActivity["status"] {function workEntryIcon(entry: DerivedWorkLogEntry): ThreadFeedActivity["icon"] {if (entry.agentSpawn) return "agent";if (+ entry.questionAnswer ||entry.sourceActivityKind === "user-input.requested" ||entry.sourceActivityKind === "user-input.resolved") {@@ -2184,21 +2186,30 @@ export function buildThreadFeed(: loadedMessages;const oldestLoadedMessageCreatedAt =options?.loadedMessages !== undefined ? (loadedMessages[0]?.createdAt ?? null) : null;- const activityEntries = getThreadFeedActivityEntries(thread.activities);+ const activityEntries = getThreadFeedActivityEntries(thread.activities).filter(+ (entry) =>+ oldestLoadedMessageCreatedAt === null || entry.createdAt >= oldestLoadedMessageCreatedAt,+ );+ const foldedAnswerMessageIds = new Set(+ activityEntries.flatMap((entry) =>+ entry.activity.workEntry.questionAnswer+ ? [`async-answer:${entry.activity.workEntry.questionAnswer.requestId}`]+ : [],+ ),+ );const entries = Arr.sortWith([- ...messages.map((message) => {- let entry = messageEntriesCache.get(message);- if (!entry) {- entry = { type: "message", id: message.id, createdAt: message.createdAt, message };- messageEntriesCache.set(message, entry);- }- return entry;- }),- ...activityEntries.filter(- (entry) =>- oldestLoadedMessageCreatedAt === null || entry.createdAt >= oldestLoadedMessageCreatedAt,- ),+ ...messages+ .filter((message) => message.role !== "user" || !foldedAnswerMessageIds.has(message.id))+ .map((message) => {+ let entry = messageEntriesCache.get(message);+ if (!entry) {+ entry = { type: "message", id: message.id, createdAt: message.createdAt, message };+ messageEntriesCache.set(message, entry);+ }+ return entry;+ }),+ ...activityEntries,],(s) => new Date(s.createdAt),Order.Date,diff --git a/apps/server/src/orchestration/ActivityPayloadProjection.ts b/apps/server/src/orchestration/ActivityPayloadProjection.tsindex 98294e63b35..43db2cfcc4c 100644--- a/apps/server/src/orchestration/ActivityPayloadProjection.ts+++ b/apps/server/src/orchestration/ActivityPayloadProjection.ts@@ -1,3 +1,4 @@+import { projectQuestionToolInput } from "@t3tools/shared/toolActivity";import type {OrchestrationEvent,OrchestrationThreadActivity,@@ -370,18 +371,19 @@ export function projectActivityPayload(payload.status === "completed" && (itemStatus === "failed" || itemStatus === "declined")? { ...payload, status: itemStatus }: payload;+ const questionInput = projectQuestionToolInput(data, payload.title);if (payload.itemType === "mcp_tool_call") {return {...activity,payload: {...projectedPayload,- data: projectMcpToolCallData(data),+ data: { ...projectMcpToolCallData(data), ...questionInput },},};}- const projectedData: Record<string, unknown> = {};+ const projectedData: Record<string, unknown> = { ...questionInput };const item = projectCommandData(data);if (item) {projectedData.item = item;diff --git a/apps/web/src/components/chat/MessagesTimeline.test.tsx b/apps/web/src/components/chat/MessagesTimeline.test.tsxindex c47402f4204..07252d6ab7f 100644--- a/apps/web/src/components/chat/MessagesTimeline.test.tsx+++ b/apps/web/src/components/chat/MessagesTimeline.test.tsx@@ -348,12 +348,24 @@ describe("MessagesTimeline", () => {});const toggle = renderer!.root.findByProps({ "aria-expanded": false });await act(() => toggle.props.onClick());+ const questionToggle = renderer!.root.find(+ (node) =>+ node.props["aria-label"]?.startsWith("Question answer submitted:") &&+ node.props["aria-expanded"] === false,+ );+ expect(questionToggle.props["aria-label"]).toContain(+ Object.values(answers)[0] ?? "spec.txt",+ );+ expect(JSON.stringify(renderer!.toJSON())).not.toContain("Provide a spec");+ await act(() => questionToggle.props.onClick());const markup = JSON.stringify(renderer!.toJSON());expect(markup.match(/Provide a spec/g)).toHaveLength(1);- expect(markup.match(/spec\.txt/g)).toHaveLength(1);+ expect(markup).toContain("spec.txt");expect(markup).toContain("Provide a screenshot");expect(markup).toContain("shot.png");for (const answer of Object.values(answers)) expect(markup).toContain(answer);+ await act(() => questionToggle.props.onClick());+ expect(JSON.stringify(renderer!.toJSON())).not.toContain("Provide a spec");} finally {await act(() => renderer?.unmount());}diff --git a/apps/web/src/components/chat/MessagesTimeline.tsx b/apps/web/src/components/chat/MessagesTimeline.tsxindex 3544e87817b..13c1e1dc61b 100644--- a/apps/web/src/components/chat/MessagesTimeline.tsx+++ b/apps/web/src/components/chat/MessagesTimeline.tsx@@ -1,4 +1,9 @@import { GitPullRequestIcon } from "lucide-react";+import {+ getQuestionAnswerPreview,+ getQuestionAnswerText,+ hasQuestionAnswer,+} from "@t3tools/client-runtime/work-log/user-input";import {type AssistantCitation,type EnvironmentId,@@ -2115,7 +2120,7 @@ function LiveActivityRow({active = false,shimmer = false,}: {- label: string;+ label: ReactNode;iconName?: WorkEntryIconName;toolIcon?: ToolActivityIcon | undefined;failed?: boolean;@@ -2155,7 +2160,7 @@ function LiveActivityContent({active = false,highlighted = false,}: {- label: string;+ label: ReactNode;iconName: WorkEntryIconName | undefined;toolIcon?: ToolActivityIcon | undefined;failed?: boolean;@@ -2213,7 +2218,25 @@ function LiveWorkEntryTimelineRow({ row }: { row: Extract<TimelineRow, { kind: "onClick={() => ctx.onToggleWorkGroup(row.groupId, row.id)}><LiveActivityRow- label={label}+ label={+ row.entry.questionAnswer ? (+ <span className="flex min-w-0 gap-1.5">+ <span className="shrink-0">{label}</span>+ <span+ className={cn(+ "truncate",+ !row.expanded && hasQuestionAnswer(row.entry.questionAnswer)+ ? "text-foreground"+ : "text-muted-foreground",+ )}+ >+ {getQuestionAnswerPreview(row.entry.questionAnswer)}+ </span>+ </span>+ ) : (+ label+ )+ }iconName={workEntryIconName(row.entry)}toolIcon={row.entry.toolIcon ?? row.entry.toolSource?.icon}failed={failed}@@ -3148,6 +3171,7 @@ const toolCallExpandedBodyClassName =function workEntryIconName(workEntry: TimelineWorkEntry): WorkEntryIconName {if (+ workEntry.questionAnswer ||workEntry.sourceActivityKind === "user-input.requested" ||workEntry.sourceActivityKind === "user-input.resolved") {@@ -3325,9 +3349,10 @@ const PlainWorkEntryRow = memo(function PlainWorkEntryRow(props: {showWarningIndicator || showDestructiveRowStyle? undefined: (workEntry.toolIcon ?? workEntry.toolSource?.icon);- const previewText = workEntry.questionAnswer- ? "Question answer submitted"- : (displayLabel ?? workEntryDisplayLabel(workEntry, workspaceRoot));+ const previewText = displayLabel ?? workEntryDisplayLabel(workEntry, workspaceRoot);+ const answerPreview = workEntry.questionAnswer+ ? getQuestionAnswerPreview(workEntry.questionAnswer)+ : null;const viewedImagePath = workEntryViewedImagePath(workEntry);const viewedImage =viewedImagePath && threadRef@@ -3337,6 +3362,7 @@ const PlainWorkEntryRow = memo(function PlainWorkEntryRow(props: {}): null;const canExpand =+ Boolean(workEntry.questionAnswer) ||(showFailedIndicator && previewText.trim().length > 0) ||(workEntry.itemType === "mcp_tool_call" && workEntry.toolData !== undefined) ||Boolean(@@ -3374,9 +3400,10 @@ const PlainWorkEntryRow = memo(function PlainWorkEntryRow(props: {: workLogEntryIsToolLike(workEntry)? "text-secondary-label": "text-foreground/80";+ const accessiblePreview = [previewText, answerPreview].filter(Boolean).join(": ");const accessibleDisplayText = showFailedIndicator- ? `${previewText}, tool call failed`- : previewText;+ ? `${accessiblePreview}, tool call failed`+ : accessiblePreview;const rowToggleProps = canExpand? {role: "button" as const,@@ -3421,7 +3448,7 @@ const PlainWorkEntryRow = memo(function PlainWorkEntryRow(props: {<p className="flex min-w-0 w-full items-baseline gap-1.5 text-sm leading-relaxed"><spanclassName={cn(- "min-w-0 flex-1",+ answerPreview ? "shrink-0" : "min-w-0 flex-1",expanded ? "whitespace-pre-wrap break-words select-text" : "truncate",headingClass,)}@@ -3430,6 +3457,20 @@ const PlainWorkEntryRow = memo(function PlainWorkEntryRow(props: {>{previewText}</span>+ {answerPreview ? (+ <span+ className={cn(+ "min-w-0 truncate",+ !expanded &&+ workEntry.questionAnswer &&+ hasQuestionAnswer(workEntry.questionAnswer)+ ? "text-foreground"+ : "text-muted-foreground",+ )}+ >+ {answerPreview}+ </span>+ ) : null}</p></div>{showFailedIndicator &&@@ -3470,10 +3511,10 @@ const PlainWorkEntryRow = memo(function PlainWorkEntryRow(props: {/></div>) : null}- {workEntry.questionAnswer ? (+ {expanded && workEntry.questionAnswer ? (<QuestionAnswerHistory answer={workEntry.questionAnswer} />) : null}- {expanded && canExpand && expandedBody ? (+ {expanded && canExpand && expandedBody && !workEntry.questionAnswer ? (<divclassName="mt-1 ms-7 cursor-default rounded-md bg-muted/40 px-3 py-2"onClick={stopRowToggle}@@ -3506,20 +3547,22 @@ function QuestionAnswerHistory({<div className="ms-7 mt-2 space-y-2" onClick={stopRowToggle}>{[...new Set([+ ...Object.keys(answer.questionTextById ?? {}),...Object.keys(answer.answers),...Object.keys(answer.attachmentsByQuestionId),]),].map((questionId) => (<div key={questionId} className="space-y-1">{answer.questionTextById?.[questionId] ? (- <p className="text-sm text-muted-foreground">{answer.questionTextById[questionId]}</p>+ <p className="whitespace-pre-wrap text-sm text-muted-foreground">+ {answer.questionTextById[questionId]}+ </p>+ ) : null}+ {getQuestionAnswerText(answer.answers[questionId]) ? (+ <p className="ms-3 whitespace-pre-wrap text-sm text-muted-foreground">+ {getQuestionAnswerText(answer.answers[questionId])}+ </p>) : null}- <p className="whitespace-pre-wrap text-sm">- {[answer.answers[questionId]]- .flat()- .filter((value): value is string => typeof value === "string")- .join(", ")}- </p><div className="flex flex-wrap gap-2">{(answer.attachmentsByQuestionId[questionId] ?? []).map((attachment) => {const url = urls[attachments.indexOf(attachment)];diff --git a/apps/web/src/session-logic.ts b/apps/web/src/session-logic.tsindex f84c978a04c..0ffcc7fdd7c 100644--- a/apps/web/src/session-logic.ts+++ b/apps/web/src/session-logic.ts@@ -3,6 +3,7 @@ import {type PendingApproval,} from "@t3tools/client-runtime/pending-requests";import { UserInputAttachmentAnswerPayload } from "@t3tools/contracts";+import { foldUserInputActivities } from "@t3tools/client-runtime/work-log/user-input";import * as Option from "effect/Option";import * as Schema from "effect/Schema";import * as Arr from "effect/Array";@@ -451,7 +452,7 @@ export function deriveWorkLogEntries(): WorkLogEntry[] {const ordered = [...activities].toSorted(compareActivitiesByOrder);const entries: DerivedWorkLogEntry[] = [];- for (const activity of ordered) {+ for (const activity of foldUserInputActivities(ordered)) {if (activity.tone !== "error" && isWorktreeSetupActivity(activity.kind)) continue;if (activity.kind === "tool.started") continue;// Agent task.started rows are CTA seeds: they carry the true spawn turn,@@ -1622,14 +1623,25 @@ export function deriveTimelineEntriesWithState(const entries = replaceStreamingTimelineMessages(messages, previous);if (entries !== null) return { messages, proposedPlans, workEntries, entries };}+ const foldedAnswerMessageIds = new Set(+ workEntries.flatMap((entry) =>+ entry.questionAnswer ? [`async-answer:${entry.questionAnswer.requestId}`] : [],+ ),+ );+ const showMessage = (message: ChatMessage) =>+ message.role !== "user" || !foldedAnswerMessageIds.has(message.id);const canAppend =previous !== null &&+ !previous.entries.some((entry) => entry.kind === "message" && !showMessage(entry.message)) &&hasExactArrayPrefix(previous.messages, messages) &&hasExactArrayPrefix(previous.proposedPlans, proposedPlans) &&hasExactArrayPrefix(previous.workEntries, workEntries);if (canAppend) {- const messageRows = messages.slice(previous.messages.length).map(timelineEntryFromMessage);+ const messageRows = messages+ .slice(previous.messages.length)+ .filter(showMessage)+ .map(timelineEntryFromMessage);const proposedPlanRows = proposedPlans.slice(previous.proposedPlans.length).map(timelineEntryFromProposedPlan);@@ -1645,7 +1657,7 @@ export function deriveTimelineEntriesWithState(};}- const messageRows = messages.map(timelineEntryFromMessage);+ const messageRows = messages.filter(showMessage).map(timelineEntryFromMessage);const proposedPlanRows = proposedPlans.map(timelineEntryFromProposedPlan);const workRows = workEntries.map(timelineEntryFromWork);return {diff --git a/packages/client-runtime/package.json b/packages/client-runtime/package.jsonindex d0bf4aad8e9..2a5eb2c7fe9 100644--- a/packages/client-runtime/package.json+++ b/packages/client-runtime/package.json@@ -223,6 +223,10 @@"types": "./src/state/vcs.ts","default": "./src/state/vcs.ts"},+ "./work-log/user-input": {+ "types": "./src/work-log/userInput.ts",+ "default": "./src/work-log/userInput.ts"+ },"./work-log/presentation": {"types": "./src/work-log/presentation.ts","default": "./src/work-log/presentation.ts"diff --git a/packages/client-runtime/src/work-log/userInput.ts b/packages/client-runtime/src/work-log/userInput.tsnew file mode 100644index 00000000000..355083c0483--- /dev/null+++ b/packages/client-runtime/src/work-log/userInput.ts@@ -0,0 +1,186 @@+import { projectQuestionToolInput } from "@t3tools/shared/toolActivity";+import {+ type OrchestrationThreadActivity,+ UserInputAttachmentAnswerPayload,+} from "@t3tools/contracts";+import * as Schema from "effect/Schema";++function record(value: unknown): Record<string, unknown> | undefined {+ return value !== null && typeof value === "object" && !Array.isArray(value)+ ? (value as Record<string, unknown>)+ : undefined;+}++const isQuestionAnswer = Schema.is(UserInputAttachmentAnswerPayload);++function displayOptionAnswer(value: unknown, labels: ReadonlyMap<string, string>): unknown {+ if (typeof value === "string") return labels.get(value) ?? value;+ if (Array.isArray(value)) return value.map((answer) => displayOptionAnswer(answer, labels));+ const nested = record(value);+ return nested && "answers" in nested+ ? { ...nested, answers: displayOptionAnswer(nested.answers, labels) }+ : value;+}++function questionFingerprint(+ turnId: string,+ questions: ReadonlyArray<unknown>,+): string | undefined {+ const texts = questions.map((question) => (typeof question === "string" ? question.trim() : ""));+ return texts.length > 0 && texts.every(Boolean)+ ? JSON.stringify([turnId, texts.toSorted()])+ : undefined;+}++function withoutDuplicateQuestionTools(+ activities: ReadonlyArray<OrchestrationThreadActivity>,+): ReadonlyArray<OrchestrationThreadActivity> {+ const questions = new Set<string>();+ for (const activity of activities) {+ if (activity.kind !== "user-input.answer-submitted" || !activity.turnId) continue;+ const payload = record(activity.payload);+ const texts = Object.values(record(payload?.questionTextById) ?? {});+ const fingerprint = questionFingerprint(activity.turnId, texts);+ if (fingerprint) questions.add(fingerprint);+ }+ if (questions.size === 0) return activities;+ const duplicateToolIds = new Set<string>();+ for (const activity of activities) {+ if (!activity.kind.startsWith("tool.") || !activity.turnId) continue;+ const payload = record(activity.payload);+ if (typeof payload?.toolCallId !== "string") continue;+ const input = projectQuestionToolInput(record(payload.data) ?? {}, payload.title).input;+ if (!input) continue;+ const fingerprint = questionFingerprint(+ activity.turnId,+ input.questions.map((question) => record(question)?.question),+ );+ if (fingerprint && questions.has(fingerprint)) {+ duplicateToolIds.add(JSON.stringify([activity.turnId, payload.toolCallId]));+ }+ }+ return activities.filter((activity) => {+ const payload = record(activity.payload);+ const toolCallId = payload?.toolCallId;+ return (+ activity.tone === "error" ||+ /^(failed|declined|stopped|cancelled)$/.test(String(payload?.status)) ||+ !activity.kind.startsWith("tool.") ||+ typeof toolCallId !== "string" ||+ !duplicateToolIds.has(JSON.stringify([activity.turnId, toolCallId]))+ );+ });+}++/** Keep a question and its answer at the original tool position in the work log. */+export function foldUserInputActivities(+ activities: ReadonlyArray<OrchestrationThreadActivity>,+): ReadonlyArray<OrchestrationThreadActivity> {+ const requests = new Map<string, OrchestrationThreadActivity[]>();+ for (const activity of activities) {+ if (+ activity.kind !== "user-input.requested" &&+ activity.kind !== "user-input.resolved" &&+ activity.kind !== "user-input.answer-submitted"+ )+ continue;+ const requestId = record(activity.payload)?.requestId;+ if (typeof requestId !== "string" || !requestId) continue;+ const group = requests.get(requestId) ?? [];+ group.push(activity);+ requests.set(requestId, group);+ }+ const replacements = new Map<OrchestrationThreadActivity, OrchestrationThreadActivity | null>();+ for (const [requestId, group] of requests) {+ const payloads = group.map((activity) => record(activity.payload)!);+ const questions = new Map<string, Record<string, unknown>>();+ const texts = new Map<string, unknown>();+ for (const payload of payloads) {+ for (const [id, text] of Object.entries(record(payload.questionTextById) ?? {}))+ texts.set(id, text);+ for (const value of Array.isArray(payload.questions) ? payload.questions : []) {+ const question = record(value);+ if (typeof question?.id !== "string") continue;+ questions.set(question.id, question);+ if (typeof question.question === "string") texts.set(question.id, question.question);+ }+ }+ const questionTextById = Object.fromEntries(texts);+ const submitted = group.findLast(+ (activity) =>+ activity.kind === "user-input.answer-submitted" &&+ record(record(activity.payload)?.answers),+ );+ const rawAnswers =+ record(record(submitted?.payload)?.answers) ??+ payloads.map((payload) => record(payload.answers)).findLast(Boolean) ??+ {};+ const answers = Object.fromEntries(+ Object.entries(rawAnswers).map(([id, value]) => {+ const options = questions.get(id)?.options;+ const labels = new Map<string, string>();+ for (const candidate of Array.isArray(options) ? options : []) {+ const option = record(candidate);+ if (typeof option?.value === "string" && typeof option.label === "string")+ labels.set(option.value, option.label);+ }+ return [id, displayOptionAnswer(value, labels)];+ }),+ );+ const attachmentsByQuestionId = Object.fromEntries(+ payloads.flatMap((payload) => Object.entries(record(payload.attachmentsByQuestionId) ?? {})),+ );+ const answer = { requestId, questionTextById, answers, attachmentsByQuestionId };+ if (!isQuestionAnswer(answer)) continue;+ const submittedAnswer =+ Object.keys(answers).length > 0 || Object.keys(attachmentsByQuestionId).length > 0;+ for (const activity of group) replacements.set(activity, null);+ replacements.set(group[0]!, {+ ...group[0]!,+ kind: "user-input.answer-submitted",+ tone: "tool",+ summary: submittedAnswer+ ? "User input submitted"+ : group.some((activity) => activity.kind === "user-input.resolved")+ ? "User input dismissed"+ : "User input requested",+ payload: answer,+ });+ }+ return withoutDuplicateQuestionTools(+ activities.flatMap((activity) => {+ const replacement = replacements.get(activity);+ return replacement === null ? [] : [replacement ?? activity];+ }),+ );+}++export function getQuestionAnswerText(value: unknown): string {+ if (typeof value === "string") return value;+ if (Array.isArray(value)) return value.map(getQuestionAnswerText).filter(Boolean).join(", ");+ const nested = record(value);+ return nested ? getQuestionAnswerText(nested.answers) : "";+}++export function getQuestionAnswerPreview(answer: UserInputAttachmentAnswerPayload): string {+ const answers = Object.values(answer.answers).map(getQuestionAnswerText).filter(Boolean);+ const attachments = Object.values(answer.attachmentsByQuestionId)+ .flat()+ .map((attachment) => attachment.name);+ return (+ answers.length > 0+ ? answers.join(" · ")+ : attachments.length > 0+ ? attachments.join(", ")+ : Object.values(answer.questionTextById ?? {}).join(" · ")+ )+ .replace(/\s+/g, " ")+ .trim();+}++export function hasQuestionAnswer(answer: UserInputAttachmentAnswerPayload): boolean {+ return (+ Object.values(answer.answers).some(getQuestionAnswerText) ||+ Object.values(answer.attachmentsByQuestionId).some((attachments) => attachments.length > 0)+ );+}diff --git a/packages/shared/src/toolActivity.ts b/packages/shared/src/toolActivity.tsindex 2fd04e76696..8c1c65565f5 100644--- a/packages/shared/src/toolActivity.ts+++ b/packages/shared/src/toolActivity.ts@@ -259,3 +259,36 @@ export function deriveToolActivityPresentation(summary: title ?? fallbackSummary,};}++export function projectQuestionToolInput(data: Record<string, unknown>, title: unknown) {+ const item = asRecord(data.item);+ const toolName = data.toolName ?? data.tool ?? item?.tool ?? title;+ if (typeof toolName !== "string") return {};+ const name = toolName+ .split(/__|[./]/)+ .at(-1)+ ?.replace(/[_\s]/g, "")+ .toLowerCase();+ if (!name || !/^(askuserquestion|requestuserinput(?:async)?|askquestion|question)$/.test(name))+ return {};+ const input = asRecord(+ data.input ?? data.rawInput ?? asRecord(data.state)?.input ?? item?.arguments,+ );+ const questions = input?.questions ?? asRecord(input?.params)?.questions;+ if (!Array.isArray(questions)) return {};+ // Clients match native tools to the canonical question; choices and answers+ // already live on the user-input activities and need not cross the wire twice.+ return {+ toolName,+ input: {+ questions: questions.map((value) => {+ const question = asRecord(value);+ return {+ question: asTrimmedString(+ question?.question ?? question?.question_text ?? question?.prompt ?? question?.title,+ ),+ };+ }),+ },+ };+}