Skip to content
TypeScript

fix(web): SnapShots taken during a question attach to that question (#15538)

tiliakoosb874ff6c22a7
diff --git a/apps/web/src/components/chat/ChatComposer.tsx b/apps/web/src/components/chat/ChatComposer.tsx
index 5bb07e5a534..137c4d26adb 100644
--- a/apps/web/src/components/chat/ChatComposer.tsx
+++ b/apps/web/src/components/chat/ChatComposer.tsx
@@ -18,6 +18,7 @@ import { RefreshIcon } from "~/components/ui/refresh-icon";
import {
questionAttachmentDraftId,
countQuestionAttachments,
+ trackOpenQuestionAttachmentDraft,
useQuestionAttachmentPreparation,
changeQuestionAttachmentPreparation,
} from "../../questionAttachments";
@@ -2041,6 +2042,33 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
: null;
const attachmentDraftTarget = questionAttachmentTarget ?? composerDraftTarget;
const attachmentDraft = useComposerThreadDraft(attachmentDraftTarget);
+ const questionTakesSnapShots =
+ supportsQuestionAttachments &&
+ activePendingProgress?.activeQuestion?.allowCustomAnswer !== false &&
+ !activePendingIsResponding;
+ const questionRequest = pendingUserInputs[0];
+ // Publish eligibility before async captures can observe a question the UI has already closed.
+ useLayoutEffect(() => {
+ if (!questionAttachmentTarget || !questionRequest || !questionTakesSnapShots) return;
+ return trackOpenQuestionAttachmentDraft(routeThreadRef, {
+ draftId: questionAttachmentTarget,
+ requestKeys: questionRequest.questions.map((question) =>
+ questionAttachmentDraftId(
+ environmentId,
+ activeThreadId!,
+ questionRequest.requestId,
+ question.id,
+ ),
+ ),
+ });
+ }, [
+ activeThreadId,
+ environmentId,
+ questionAttachmentTarget,
+ questionRequest,
+ questionTakesSnapShots,
+ routeThreadRef,
+ ]);
const attachmentTargetKey = composerTargetKey(attachmentDraftTarget);
// An import that finishes after a draft change must compare against the draft open *now*, not
// the one captured in the closure that started it.
@@ -2079,7 +2107,7 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
pendingSnapShotIdSet,
uncommittedSnapShotIds,
standaloneComposerImages,
- } = useComposerImageGroups(composerDraftTarget, composerImages, composerPreviewAnnotations);
+ } = useComposerImageGroups(attachmentDraftTarget, composerImages, composerPreviewAnnotations);
const nonPersistedComposerImageIds = attachmentDraft.nonPersistedImageIds;
const uploadsByImageId = useAttachmentUploadStore((state) => state.uploadsByImageId);
const openPrLink = useOpenPrLink(routeThreadRef);
diff --git a/apps/web/src/components/desktop/SnapShotCoordinator.browser.test.ts b/apps/web/src/components/desktop/SnapShotCoordinator.browser.test.ts
index 4b2287b8707..b38e2f7018d 100644
--- a/apps/web/src/components/desktop/SnapShotCoordinator.browser.test.ts
+++ b/apps/web/src/components/desktop/SnapShotCoordinator.browser.test.ts
@@ -5,6 +5,7 @@ import {
type DesktopSnapShotEvent,
DEFAULT_CLIENT_SETTINGS,
EnvironmentId,
+ PROVIDER_SEND_TURN_MAX_ATTACHMENTS,
ProjectId,
ThreadId,
} from "@t3tools/contracts";
@@ -18,11 +19,17 @@ import * as settings from "../../hooks/useSettings";
import * as newThread from "../../hooks/useHandleNewThread";
import * as snapShotSound from "../../lib/snapShotSound";
import { toastManager } from "../ui/toast";
+import * as imageCompression from "../../lib/imageCompression";
+import {
+ questionAttachmentDraftId,
+ trackOpenQuestionAttachmentDraft,
+} from "../../questionAttachments";
import {
beginSnapShotAnimationWhenReady,
deliverSnapShot,
dismissFailedSnapShot,
resolveExistingSnapShotTarget,
+ resolveSnapShotAttachmentTarget,
resolveSnapShotTargetOnce,
resolveSnapShotDeliveryTarget,
SnapShotCoordinator,
@@ -38,6 +45,7 @@ import {
vi.mock(import("../../hooks/useSettings"), { spy: true });
vi.mock(import("../../hooks/useHandleNewThread"), { spy: true });
vi.mock(import("../../lib/snapShotSound"), { spy: true });
+vi.mock(import("../../lib/imageCompression"), { spy: true });
const storage = vi.hoisted(() => {
const values = new Map<string, string>();
@@ -537,7 +545,7 @@ describe("window capture delivery", () => {
}
});
});
- const delivery = deliverSnapShot(bridge, item, target);
+ const delivery = deliverSnapShot(bridge, item, () => target);
await persisted;
await vi.advanceTimersByTimeAsync(0);
@@ -605,6 +613,128 @@ describe("window capture target resolution", () => {
});
});
+describe("open question delivery", () => {
+ const threadRef = scopeThreadRef(environmentId, ThreadId.make("question-thread"));
+ const first = questionAttachmentDraftId(environmentId, threadRef.threadId, "request-1", "q1");
+ const second = questionAttachmentDraftId(environmentId, threadRef.threadId, "request-1", "q2");
+ const request = { draftId: first, requestKeys: [first, second] };
+ const capture = {
+ id: "12345678-1234-1234-1234-123456789abc",
+ name: "window.png",
+ mimeType: "image/png" as const,
+ sizeBytes: 3,
+ dataUrl: "data:image/png;base64,AQID",
+ source: {
+ kind: "snap-shot" as const,
+ capturedAt: "2026-09-01T00:00:00.000Z",
+ appName: "Editor",
+ windowTitle: "main.ts",
+ },
+ };
+ const makeBridge = (readSnapShot: () => Promise<typeof capture> = async () => capture) => {
+ const acknowledgeSnapShot = vi.fn(async () => undefined);
+ const bridge = { readSnapShot, acknowledgeSnapShot } as unknown as DesktopSnapShotBridge;
+ return { bridge, acknowledgeSnapShot };
+ };
+
+ it("attaches a capture to the open question draft and leaves the thread draft alone", async () => {
+ const pins = new Map();
+ const untrack = trackOpenQuestionAttachmentDraft(threadRef, request);
+ try {
+ const { bridge, acknowledgeSnapShot } = makeBridge();
+ await deliverSnapShot(bridge, capture, () =>
+ resolveSnapShotAttachmentTarget(pins, capture.id, threadRef),
+ );
+ const store = useComposerDraftStore.getState();
+ expect(store.getComposerDraft(first)?.images.map(({ id }) => id)).toEqual([capture.id]);
+ expect(store.getComposerDraft(threadRef)?.images ?? []).toHaveLength(0);
+ expect(acknowledgeSnapShot).toHaveBeenCalledExactlyOnceWith(capture.id);
+ } finally {
+ untrack();
+ }
+ });
+
+ it("falls back to the thread when a newer question replaces the pinned one during compression", async () => {
+ const pins = new Map();
+ const untrackFirst = trackOpenQuestionAttachmentDraft(threadRef, request);
+ let untrackSecond = () => {};
+ const compression = vi
+ .spyOn(imageCompression, "compressImageToByteLimit")
+ .mockImplementationOnce(async (file) => {
+ untrackSecond = trackOpenQuestionAttachmentDraft(threadRef, {
+ ...request,
+ draftId: second,
+ });
+ untrackFirst();
+ return { ok: true, file, recompressed: false };
+ });
+ try {
+ const { bridge, acknowledgeSnapShot } = makeBridge();
+ const resolveTarget = () => resolveSnapShotAttachmentTarget(pins, capture.id, threadRef);
+ expect(resolveTarget()).toBe(first);
+ await deliverSnapShot(bridge, capture, resolveTarget);
+ const store = useComposerDraftStore.getState();
+ expect(store.getComposerDraft(first)?.images ?? []).toHaveLength(0);
+ expect(store.getComposerDraft(second)?.images ?? []).toHaveLength(0);
+ expect(store.getComposerDraft(threadRef)?.images.map(({ id }) => id)).toEqual([capture.id]);
+ expect(acknowledgeSnapShot).toHaveBeenCalledExactlyOnceWith(capture.id);
+ } finally {
+ compression.mockRestore();
+ untrackFirst();
+ untrackSecond();
+ }
+ });
+
+ it("keeps a capture pinned before any question off a question that opens during the read", async () => {
+ const pins = new Map();
+ const resolveTarget = () => resolveSnapShotAttachmentTarget(pins, capture.id, threadRef);
+ // The drain pins a capture it never saw requested before reading it.
+ expect(resolveTarget()).toEqual(threadRef);
+ let untrack = () => {};
+ const { bridge, acknowledgeSnapShot } = makeBridge(async () => {
+ untrack = trackOpenQuestionAttachmentDraft(threadRef, request);
+ return capture;
+ });
+ try {
+ await deliverSnapShot(bridge, capture, resolveTarget);
+ const store = useComposerDraftStore.getState();
+ expect(store.getComposerDraft(first)?.images ?? []).toHaveLength(0);
+ expect(store.getComposerDraft(threadRef)?.images.map(({ id }) => id)).toEqual([capture.id]);
+ expect(acknowledgeSnapShot).toHaveBeenCalledExactlyOnceWith(capture.id);
+ } finally {
+ untrack();
+ }
+ });
+
+ it("refuses a capture once the request's other questions hold the shared limit", async () => {
+ useComposerDraftStore.getState().addImages(
+ first,
+ Array.from({ length: PROVIDER_SEND_TURN_MAX_ATTACHMENTS }, (_, index) => ({
+ type: "image" as const,
+ id: `staged-${index}`,
+ name: `staged-${index}.png`,
+ mimeType: "image/png",
+ sizeBytes: 3,
+ previewUrl: `data:image/png;base64,AQID${index}`,
+ file: new File([new Uint8Array([1, 2, 3])], `staged-${index}.png`, { type: "image/png" }),
+ })),
+ );
+ const untrack = trackOpenQuestionAttachmentDraft(threadRef, { ...request, draftId: second });
+ try {
+ const { bridge, acknowledgeSnapShot } = makeBridge();
+ await expect(deliverSnapShot(bridge, capture, () => second)).rejects.toThrow(
+ "Remove an attachment",
+ );
+ expect(useComposerDraftStore.getState().getComposerDraft(second)?.images ?? []).toHaveLength(
+ 0,
+ );
+ expect(acknowledgeSnapShot).not.toHaveBeenCalled();
+ } finally {
+ untrack();
+ }
+ });
+});
+
describe("durable snapshot delivery", () => {
it.each([false, true])(
"retains a capture on quota failure and retries without duplicates (staged: %s)",
@@ -643,7 +773,7 @@ describe("durable snapshot delivery", () => {
});
void store.syncPersistedAttachments(target, [capture]);
}
- await expect(deliverSnapShot(bridge, capture, target)).rejects.toThrow(
+ await expect(deliverSnapShot(bridge, capture, () => target)).rejects.toThrow(
"could not be saved",
);
expect(acknowledgeSnapShot).not.toHaveBeenCalled();
@@ -651,7 +781,7 @@ describe("durable snapshot delivery", () => {
useComposerDraftStore.getState().getComposerDraft(target)?.nonPersistedImageIds,
).toContain(capture.id);
storage.setItem.mockImplementation(write);
- await deliverSnapShot(bridge, capture, target);
+ await deliverSnapShot(bridge, capture, () => target);
expect(acknowledgeSnapShot).toHaveBeenCalledExactlyOnceWith(capture.id);
expect(useComposerDraftStore.getState().getComposerDraft(target)?.images).toHaveLength(1);
expect(
diff --git a/apps/web/src/components/desktop/SnapShotCoordinator.tsx b/apps/web/src/components/desktop/SnapShotCoordinator.tsx
index 1765536ab79..503572ba86e 100644
--- a/apps/web/src/components/desktop/SnapShotCoordinator.tsx
+++ b/apps/web/src/components/desktop/SnapShotCoordinator.tsx
@@ -1,6 +1,7 @@
import {
type DesktopPendingSnapShot,
type DesktopSnapShotEvent,
+ PROVIDER_SEND_TURN_MAX_ATTACHMENTS,
PROVIDER_SEND_TURN_MAX_IMAGE_BYTES,
type ScopedThreadRef,
} from "@t3tools/contracts";
@@ -33,6 +34,10 @@ import {
getDesktopSnapShotBridge,
type DesktopSnapShotBridge,
} from "../../lib/desktopSnapShot";
+import {
+ countQuestionRequestAttachments,
+ openQuestionAttachmentDraft,
+} from "../../questionAttachments";
import { readFileAsDataUrl } from "../ChatView.logic";
import { stackedThreadToast, toastManager } from "../ui/toast";
@@ -65,6 +70,18 @@ export function resolveExistingSnapShotTarget(
: null;
}
+// Pin absence too: a later question must never claim an earlier capture.
+export function resolveSnapShotAttachmentTarget(
+ pins: Map<string, DraftId | null>,
+ id: string,
+ target: CaptureTarget,
+): CaptureTarget {
+ const open = typeof target === "string" ? null : openQuestionAttachmentDraft(target);
+ if (!pins.has(id)) pins.set(id, open?.draftId ?? null);
+ const pinned = pins.get(id);
+ return pinned && pinned === open?.draftId ? pinned : target;
+}
+
const NEXT_PAINT_FALLBACK_MS = 100;
export async function beginSnapShotAnimationWhenReady(
@@ -141,7 +158,7 @@ async function afterNextPaint(): Promise<void> {
export async function deliverSnapShot(
bridge: DesktopSnapShotBridge,
item: DesktopPendingSnapShot,
- target: CaptureTarget,
+ resolveTarget: () => CaptureTarget,
): Promise<void> {
const store = useComposerDraftStore.getState();
updateSnapShotAnimationSource(item.id, item.source);
@@ -155,12 +172,14 @@ export async function deliverSnapShot(
const file = compressed.file;
const source = resizeSnapShotSource(capture.source, compressed.imageSize);
const dataUrl = compressed.recompressed ? await readFileAsDataUrl(file) : capture.dataUrl;
+ const target = resolveTarget();
const alreadyAttached =
store.getComposerDraft(target)?.images.some(({ id }) => id === capture.id) ?? false;
- if (
- !alreadyAttached &&
- !store.addImage(target, {
- type: "image",
+ if (!alreadyAttached) {
+ const questionAttachmentCount =
+ typeof target === "string" ? countQuestionRequestAttachments(target) : null;
+ const image = {
+ type: "image" as const,
id: capture.id,
name: file.name,
mimeType: file.type,
@@ -168,9 +187,14 @@ export async function deliverSnapShot(
previewUrl: dataUrl,
file,
source,
- })
- ) {
- throw new Error("Remove an attachment, then try this capture again.");
+ };
+ // Only question drafts may bypass addImage's thread-session gate.
+ const added =
+ questionAttachmentCount === null
+ ? store.addImage(target, image)
+ : questionAttachmentCount < PROVIDER_SEND_TURN_MAX_ATTACHMENTS &&
+ store.addImages(target, [image]).includes(capture.id);
+ if (!added) throw new Error("Remove an attachment, then try this capture again.");
}
const persisted: PersistedComposerImageAttachment = {
id: capture.id,
@@ -216,6 +240,7 @@ export function SnapShotCoordinator() {
const animateCaptures = useClientSettings((settings) => settings.snapShotAnimations);
const enabled = useClientSettings((settings) => settings.snapShotEnabled);
const captureTargetsRef = useRef(new Map<string, Promise<CaptureTarget | null>>());
+ const questionPinsRef = useRef(new Map<string, DraftId | null>());
const targetResolutionRef = useRef<Promise<CaptureTarget | null> | null>(null);
const drainingRef = useRef<Promise<void> | null>(null);
const rerunRequestedRef = useRef(false);
@@ -336,8 +361,13 @@ export function SnapShotCoordinator() {
}
try {
- await deliverSnapShot(bridge, item, target);
+ // Pending captures may have arrived without a requested event; pin before reading.
+ resolveSnapShotAttachmentTarget(questionPinsRef.current, item.id, target);
+ await deliverSnapShot(bridge, item, () =>
+ resolveSnapShotAttachmentTarget(questionPinsRef.current, item.id, target),
+ );
captureTargetsRef.current.delete(item.id);
+ questionPinsRef.current.delete(item.id);
soundedCaptureIdsRef.current.delete(item.id);
reportedCaptureFailuresRef.current.delete(item.id);
} catch (error) {
@@ -387,22 +417,29 @@ export function SnapShotCoordinator() {
const target = current ? resolveExistingSnapShotTarget(current, routeThreadRef) : null;
// Creating a new draft would navigate the renderer before a self-capture finishes.
if (target) {
+ resolveSnapShotAttachmentTarget(questionPinsRef.current, event.id, target);
void resolveSnapShotDeliveryTarget(captureTargetsRef.current, event.id, () =>
Promise.resolve(target),
);
+ } else if (!questionPinsRef.current.has(event.id)) {
+ questionPinsRef.current.set(event.id, null);
}
return;
}
case "started": {
playCaptureSound(event.id);
+ const target = resolveSnapShotDeliveryTarget(
+ captureTargetsRef.current,
+ event.id,
+ resolveCaptureTarget,
+ ).then(
+ (target) =>
+ target && resolveSnapShotAttachmentTarget(questionPinsRef.current, event.id, target),
+ );
if (animateCaptures && !window.matchMedia("(prefers-reduced-motion: reduce)").matches) {
void beginSnapShotAnimationWhenReady(
event.id,
- resolveSnapShotDeliveryTarget(
- captureTargetsRef.current,
- event.id,
- resolveCaptureTarget,
- ),
+ target,
pendingAnimationStartsRef.current,
);
}
@@ -412,7 +449,10 @@ export function SnapShotCoordinator() {
void drain();
return;
case "failed": {
- if (event.id) captureTargetsRef.current.delete(event.id);
+ if (event.id) {
+ captureTargetsRef.current.delete(event.id);
+ questionPinsRef.current.delete(event.id);
+ }
dismissFailedSnapShot(
event.id,
soundedCaptureIdsRef.current,
diff --git a/apps/web/src/questionAttachments.ts b/apps/web/src/questionAttachments.ts
index 651c7a3e719..28472c0599a 100644
--- a/apps/web/src/questionAttachments.ts
+++ b/apps/web/src/questionAttachments.ts
@@ -1,4 +1,5 @@
-import type { EnvironmentId, ThreadId } from "@t3tools/contracts";
+import { scopedThreadKey } from "@t3tools/client-runtime/environment";
+import type { EnvironmentId, ScopedThreadRef, ThreadId } from "@t3tools/contracts";
import { create } from "zustand";
import { DraftId, useComposerDraftStore } from "./composerDraftStore";
import { releaseDraftAttachments } from "./lib/attachmentUploadQueue";
@@ -21,6 +22,37 @@ export function questionAttachmentDraftId(
);
}
+type OpenQuestionAttachmentDraft = {
+ readonly draftId: DraftId;
+ readonly requestKeys: ReadonlyArray<DraftId>;
+};
+
+const openQuestionDrafts = new Map<string, OpenQuestionAttachmentDraft>();
+
+export function openQuestionAttachmentDraft(
+ threadRef: ScopedThreadRef,
+): OpenQuestionAttachmentDraft | null {
+ return openQuestionDrafts.get(scopedThreadKey(threadRef)) ?? null;
+}
+
+export function countQuestionRequestAttachments(draftId: DraftId): number | null {
+ for (const draft of openQuestionDrafts.values()) {
+ if (draft.draftId === draftId) return countQuestionAttachments(draft.requestKeys);
+ }
+ return null;
+}
+
+export function trackOpenQuestionAttachmentDraft(
+ threadRef: ScopedThreadRef,
+ draft: OpenQuestionAttachmentDraft,
+): () => void {
+ const key = scopedThreadKey(threadRef);
+ openQuestionDrafts.set(key, draft);
+ return () => {
+ if (openQuestionDrafts.get(key) === draft) openQuestionDrafts.delete(key);
+ };
+}
+
export const useQuestionAttachmentPreparation = create<{ counts: Record<string, number> }>(() => ({
counts: {},
}));