feat(chat): attach files to question answers #9871
Mergedshivamhwp(GitHub profile, opens in a new tab)merged 10 commits into
main fromrefs/pull/9871/headmerged by shivamhwp(GitHub profile, opens in a new tab) View on GitHubgithub-actions[bot](GitHub profile, opens in a new tab) added labelsvouch:trusted
github-actions[bot](GitHub profile, opens in a new tab) added labelssize:XXL
- apps/mobile/src/state/use-composer-drafts.ts line 938Resolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -857,4 +857,4 @@857857 const existing = normalizeDraft(current[draftKey]);858858 const remaining = options?.allowOverflow859859 ? attachments.length860- : Math.max(0, PROVIDER_SEND_TURN_MAX_ATTACHMENTS - existing.attachments.length);860+ : Math.max(apps/mobile/src/features/threads/QuestionAttachments.tsx line 116OutdatedResolvedby shivamhwp(GitHub profile, opens in a new tab)@@ -0,0 +96,21 @@96+ props.requestId,97+ props.question.id,98+ );99+ const attachments = drafts[key]?.attachments ?? [];100+ const pick = async (kind: "media" | "files") => {101+ changeQuestionAttachmentPreparation(key, 1);102+ try {103+ const existingCount = appAtomRegistry.get(composerDraftsAtom)[key]?.attachments.length ?? 0;104+ const result =105+ kind === "files"106+ ? await pickComposerFiles({107+ existingCount,108+ maxBytes: capabilities?.fileAttachments?.maxUploadBytes,109+ })110+ : await pickComposerMedia({111+ existingCount,112+ maxVideoBytes: capabilities?.fileAttachments?.maxUploadBytes,113+ });114+ const picked = "files" in result ? result.files : result.attachments;115+ // Resolution on another client clears the reservation while the picker is open.116+ if ((appAtomRegistry.get(questionAttachmentPreparationAtom)[key] ?? 0) === 0) {apps/server/src/orchestration/Layers/ProjectionPipeline.ts line 1211Resolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -1214,3 +1218,4 @@12141218 yield* Effect.forEach(keptRows, projectionThreadActivityRepository.upsert, {12151219 concurrency: 1,12161220 }).pipe(Effect.asVoid);1221+ attachmentSideEffects.prunedThreadRelativePaths.set(event.payload.threadId, new Set());apps/server/src/orchestration/Normalizer.ts line 321Resolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -271,6 +305,14 @@271305 export const cleanupFailedUploadedAttachments = Effect.fn(272306 "Normalizer.cleanupFailedUploadedAttachments",273307 )(function* (command: ClientOrchestrationCommand, normalizedCommand: OrchestrationCommand) {274- if (command.type !== "thread.turn.start" || normalizedCommand.type !== "thread.turn.start") {275- return;276- }308+ const originalAttachments =309+ command.type === "thread.turn.start"310+ ? command.message.attachments311+ : command.type === "thread.user-input.respond"312+ ? Object.values(command.attachmentsByQuestionId ?? {}).flat()313+ : [];314+ const normalizedAttachments =315+ normalizedCommand.type === "thread.turn.start"316+ ? normalizedCommand.message.attachments317+ : normalizedCommand.type === "thread.user-input.respond"318+ ? Object.values(normalizedCommand.attachmentsByQuestionId ?? {}).flat()
- apps/mobile/src/state/use-selected-thread-requests.ts line 134Resolvedby shivamhwp(GitHub profile, opens in a new tab)@@ -100,0 +120,21 @@120+ const prefix = questionAttachmentDraftPrefix(121+ selectedThreadShell.environmentId,122+ selectedThreadShell.id,123+ );124+ const retained = new Set(125+ activePendingUserInputs.flatMap((request) =>126+ request.questions.map((question) =>127+ questionAttachmentDraftKey(128+ selectedThreadShell.environmentId,129+ selectedThreadShell.id,130+ request.requestId,131+ question.id,132+ ),133+ ),134+ ),135+ );136+ const counts = { ...appAtomRegistry.get(questionAttachmentPreparationAtom) };137+ let changed = false;138+ for (const key of new Set([...Object.keys(attachmentDrafts), ...Object.keys(counts)])) {139+ if (!key.startsWith(prefix) || retained.has(key)) continue;140+ if (attachmentDrafts[key]) clearComposerDraft(key);apps/mobile/src/features/threads/QuestionAttachments.tsx line 103Resolvedby shivamhwp(GitHub profile, opens in a new tab)@@ -0,0 +63,21 @@63+ !selectedThread ||64+ props.disabled ||65+ !configs.get(selectedThread.environmentId)?.environment.capabilities.questionAttachments66+ )67+ return;68+ const key = questionAttachmentDraftKey(69+ selectedThread.environmentId,70+ selectedThread.id,71+ props.requestId,72+ props.question.id,73+ );74+ changeQuestionAttachmentPreparation(key, 1);75+ void convertPastedImagesToAttachments({76+ uris,77+ existingCount: appAtomRegistry.get(composerDraftsAtom)[key]?.attachments.length ?? 0,78+ })79+ .then(async (images) => {80+ if ((appAtomRegistry.get(questionAttachmentPreparationAtom)[key] ?? 0) > 0)81+ append(key, images);82+ else await releaseUnusedComposerAttachmentFiles(images);83+ })
- apps/server/src/provider/userInputAttachments.ts line 24OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +4,21 @@4+import * as FileSystem from "effect/FileSystem";5+import { resolveAttachmentPath } from "../attachmentStore.ts";6+import { ProviderValidationError } from "./Errors.ts";7+8+const quoteReference = Schema.encodeSync(Schema.fromJsonString(Schema.String));9+10+/** Keep provider answer protocols unchanged; paths refer to files on the provider's server. */11+export const appendUserInputAttachmentPaths = Effect.fn("appendUserInputAttachmentPaths")(12+ function* (input: {13+ answers: ProviderUserInputAnswers;14+ attachmentsByQuestionId?: UserInputAttachments | undefined;15+ attachmentsDir: string;16+ }) {17+ const answers = { ...input.answers };18+ const fs = yield* FileSystem.FileSystem;19+ for (const [questionId, attachments] of Object.entries(input.attachmentsByQuestionId ?? {})) {20+ if (attachments.length === 0) continue;21+ const references: string[] = [];22+ for (const attachment of attachments) {23+ const path = resolveAttachmentPath({ attachmentsDir: input.attachmentsDir, attachment });24+ if (!path || !(yield* fs.exists(path).pipe(Effect.orElseSucceed(() => false)))) {
- apps/mobile/src/state/use-selected-thread-requests.ts line 146Resolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -101,5 +135,18 @@135+ );136+ const counts = { ...appAtomRegistry.get(questionAttachmentPreparationAtom) };137+ let changed = false;138+ for (const key of new Set([...Object.keys(attachmentDrafts), ...Object.keys(counts)])) {139+ if (!key.startsWith(prefix) || retained.has(key)) continue;140+ if (attachmentDrafts[key]) clearComposerDraft(key);141+ if (key in counts) {142+ delete counts[key];143+ changed = true;144+ }145+ }146+ if (changed) appAtomRegistry.set(questionAttachmentPreparationAtom, counts);147+ }, [activePendingUserInputs, attachmentDrafts, selectedThread, selectedThreadShell]);101148 const activePendingUserInputDrafts =102149 activePendingUserInput && selectedThreadShell103- ? (userInputDraftsByRequestKey[104- scopedRequestKey(selectedThreadShell.environmentId, activePendingUserInput.requestId)105- ] ?? {})150+ ? Object.fromEntries(151+ activePendingUserInput.questions.map((question) => {152+ const key = questionAttachmentDraftKey(
- apps/server/src/orchestration/Layers/ProjectionPipeline.ts line 2039Resolvedby shivamhwp(GitHub profile, opens in a new tab)@@ -1983,7 +2006,16 @@19832006 });198420071985- const bootstrap: OrchestrationProjectionPipelineShape["bootstrap"] = Effect.forEach(1986- projectors,1987- bootstrapProjector,1988- { concurrency: 1 },1989- ).pipe(2008+ const bootstrap: OrchestrationProjectionPipelineShape["bootstrap"] = Effect.gen(function* () {2009+ const pendingPrunes = new Map<string, OrchestrationEvent>();2010+ yield* Effect.forEach(2011+ projectors,2012+ (projector) => bootstrapProjector(projector, pendingPrunes),2013+ { concurrency: 1, discard: true },2014+ );2015+ // Both message and activity references must finish replaying before files are pruned.2016+ for (const [threadId, event] of pendingPrunes) {2017+ yield* applyAttachmentSideEffects(event, {2018+ deletedThreadIds: new Set(),2019+ prunedThreadRelativePaths: new Map([[threadId, new Set()]]),2020+ });2021+ }
- apps/web/src/questionAttachments.ts line 41OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +21,21 @@21+ );22+}23+24+export const useQuestionAttachmentPreparation = create<{ counts: Record<string, number> }>(() => ({25+ counts: {},26+}));27+28+export function changeQuestionAttachmentPreparation(key: DraftId, delta: number): void {29+ useQuestionAttachmentPreparation.setState((state) =>30+ delta < 0 && !(key in state.counts)31+ ? state32+ : {33+ counts: { ...state.counts, [key]: Math.max(0, (state.counts[key] ?? 0) + delta) },34+ },35+ );36+}37+38+export function clearQuestionAttachmentDraft(key: DraftId): void {39+ const store = useComposerDraftStore.getState();40+ const draft = store.getComposerDraft(key);41+ if (draft) releaseDraftAttachments([...draft.images, ...draft.files]);
- apps/web/src/questionAttachments.ts lines 10 to 10OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +1,10 @@1+import type { ApprovalRequestId, EnvironmentId, ThreadId } from "@t3tools/contracts";2+import { create } from "zustand";3+import { DraftId, useComposerDraftStore } from "./composerDraftStore";4+import { releaseDraftAttachments } from "./lib/attachmentUploadQueue";5+6+export function questionAttachmentDraftPrefix(7+ environmentId: EnvironmentId,8+ threadId: ThreadId,9+): string {10+ return `${environmentId}:question-${encodeURIComponent(JSON.stringify(threadId))}-`;apps/server/src/orchestration/Layers/ProjectionPipeline.ts line 2025OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -1998,4 +2009,17 @@1998- projectors,1999- bootstrapProjector,2000- { concurrency: 1 },2001- ).pipe(2009+ const bootstrap: OrchestrationProjectionPipelineShape["bootstrap"] = Effect.gen(function* () {2010+ const pendingPrunes = new Map<string, OrchestrationEvent>();2011+ const pendingCursors = new Map<string, OrchestrationEvent>();2012+ yield* Effect.forEach(2013+ projectors,2014+ (projector) => bootstrapProjector(projector, pendingPrunes, pendingCursors),2015+ { concurrency: 1, discard: true },2016+ );2017+ // Both message and activity references must finish replaying before files are pruned.2018+ for (const [threadId, event] of pendingPrunes) {2019+ yield* applyAttachmentSideEffects(event, {2020+ deletedThreadIds: new Set(),2021+ prunedThreadRelativePaths: new Map([[threadId, new Set()]]),2022+ });2023+ }2024+ // Failed replay or process exit must leave the revert events eligible for replay.2025+ yield* projectionStateRepository.upsertMany(
- apps/mobile/src/features/threads/thread-work-log.tsx line 860Resolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -856,3 +857,4 @@856857 layout={WORK_LOG_LAYOUT_TRANSITION}857858 className="ml-7 border-l border-adaptive-neutral-300-a60-white-a12 pb-1 pl-3 pt-0.5"858859 >860+ {row.workEntry.questionAnswer ? (
- apps/web/src/components/chat/MessagesTimeline.tsx line 3401OutdatedResolvedby shivamhwp(GitHub profile, opens in a new tab)@@ -3376 +3381,21 @@33763381 });3382+3383+function QuestionAnswerHistory({3384+ answer,3385+}: {3386+ answer: import("@t3tools/contracts").UserInputAttachmentAnswerPayload;3387+}) {3388+ const { activeThreadEnvironmentId } = use(TimelineRowCtx);3389+ const attachments = useMemo(() => Object.values(answer.attachmentsByQuestionId).flat(), [answer]);3390+ const resources = useMemo(3391+ () =>3392+ attachments.map((attachment) => ({3393+ _tag: "attachment" as const,3394+ attachmentId: attachment.id,3395+ })),3396+ [attachments],3397+ );3398+ const urls = useAssetUrls(activeThreadEnvironmentId, resources);3399+ return (3400+ <div className="ms-7 mt-2 space-y-2" onClick={stopRowToggle}>3401+ {Object.keys(answer.answers).map((questionId) => (
- apps/web/src/components/chat/ChatComposer.tsx lines 2259 to 2259Resolvedby shivamhwp(GitHub profile, opens in a new tab)@@ -2219,4 +2253,7 @@22192253 ? {22202254 questionIndex: activePendingProgress.questionIndex,22212255 isLastQuestion: activePendingProgress.isLastQuestion,2222- canAdvance: activePendingProgress.canAdvance,2256+ canAdvance:2257+ activePendingProgress.canAdvance &&2258+ !attachmentBlockReason &&2259+ !(questionPreparations[attachmentTargetKey] ?? 0),
- docs/user/question-attachments.md line 7OutdatedResolvedby shivamhwp(GitHub profile, opens in a new tab)@@ -0,0 +1,7 @@1+# Files in question answers2+3+When an agent asks a question that accepts a custom answer, use **Attach files** or paste an image into the answer field. On mobile, use the attachment button to choose photos or files. You can send a file by itself, with a selected option, or with a typed answer.4+5+Each question keeps its own attachments as you move between questions. Your normal prompt draft stays separate. Wait for uploads to finish before submitting; retry or remove any failed upload. A failed response keeps the draft available to try again.6+7+Files upload to the environment running the thread, including remote environments. The agent receives paths to those saved files in the question answer and can open them with its available tools. Questions that only accept predefined choices do not offer attachments. Older servers need updating before this option appears.
- apps/mobile/src/state/use-selected-thread-requests.ts line 299Resolvedby shivamhwp(GitHub profile, opens in a new tab)@@ -157,9 +279,21 @@279+ id: attachment.uploadedAttachmentId!,280+ name: attachment.name,281+ mimeType: attachment.mimeType,282+ sizeBytes: attachment.sizeBytes,283+ })),284+ );285+ }286+ userInputResponsesInFlight.current.add(responseKey);157287 setRespondingUserInputId(activePendingUserInput.requestId);158288 const result = await respondToUserInput({159289 environmentId: selectedThreadShell.environmentId,160290 input: {161291 threadId: selectedThreadShell.id,162292 requestId: activePendingUserInput.requestId,163293 answers: activePendingUserInputAnswers,294+ ...(attachmentsByQuestionId.size > 0295+ ? { attachmentsByQuestionId: Object.fromEntries(attachmentsByQuestionId) }296+ : {}),164297 },165298 });299+ userInputResponsesInFlight.current.delete(responseKey);
shivamhwp(GitHub profile, opens in a new tab) closed this
Sign in to join this conversation.


Thread transfer impact#
✅ Thread transfer remains within every enforced ceiling.
Baseline:
83d769f· PR result:9a566ef· Source CI: successScenario and decoded snapshot size
10 historical turns, 5 command tools per turn, 878.9 KiB retained MCP result per historical turn, and a 1.05 MiB retained result in the measured turn.
Updated in place by a trusted workflow. PR artifacts are strictly validated and never executed.