fix(server): snapshot viewed images so previews survive scratch file deletion #47940
OpenEliBlauBalto(GitHub profile, opens in a new tab)wants to merge 5 commits into
main fromrefs/pull/47940/headopened View on GitHubEliBlauBalto(GitHub profile, opens in a new tab) linked this to fix #41480
tanstack-source added labelsbug
github-actions[bot](GitHub profile, opens in a new tab) added labelssize:XXL
- @@ -0,0 +378,21 @@378+ yield* removePrefetch(key);379+ return cached.attachmentId;380+ }381+ }382+ if (input.itemId !== undefined && key !== undefined) {383+ const existing = yield* projections.getTurnItem({384+ threadId: input.threadId,385+ itemId: input.itemId,386+ });387+ if (388+ existing?.type === "dynamic_tool" &&389+ existing.viewedImageAttachmentId !== undefined &&390+ existing.viewedImagePath !== undefined &&391+ normalizeViewedImagePath(existing.viewedImagePath) === normalizedPath392+ ) {393+ yield* removePrefetch(key);394+ recordCaptured(key, existing.viewedImageAttachmentId, normalizedPath);395+ return existing.viewedImageAttachmentId;396+ }397+ }398+ const prefetchedEntry = key === undefined ? null : yield* removePrefetch(key);@@ -130,0 +142,21 @@142+ const normalizedExtension = extension.trim().toLowerCase();143+ const digest = NodeCrypto.createHash("sha256").update(bytes).digest("hex");144+ const baseId = createDeterministicAttachmentId(145+ threadId,146+ `viewed-image:${normalizedExtension}:${digest}`,147+ );148+ return baseId === null ? null : `${VIEWED_IMAGE_ATTACHMENT_PREFIX}${baseId}`;149+}150+151+/** Only this thread's ids qualify, preserving source snapshots when deleting a fork. */152+export function threadViewedImageAttachmentIds(153+ threadId: string,154+ items: Iterable<{ readonly viewedImageAttachmentId?: string | null | undefined }>,155+): string[] {156+ const segment = toSafeThreadAttachmentSegment(threadId);157+ if (segment === null) return [];158+ const expectedSegment = `${VIEWED_IMAGE_ATTACHMENT_PREFIX}${segment}`;159+ return Array.from(items).flatMap((item) => {160+ const attachmentId = item.viewedImageAttachmentId ?? undefined;161+ return attachmentId !== undefined &&162+ parseThreadSegmentFromAttachmentId(attachmentId) === expectedSegment@@ -6828,0 +7021,21 @@7021+ Stream.take(1),7022+ Stream.runDrain,7023+ Effect.forkScoped,7024+ );7025+ yield* Queue.offer(adapterQueue, {7026+ type: "turn_item.updated",7027+ driver: CODEX_DRIVER,7028+ turnItem: { ...detachedBase, status: "running" },7029+ });7030+ yield* Deferred.await(detachedRunningSeen);7031+ yield* Fiber.join(dropSubFiber);7032+ yield* dropSub.close;7033+ yield* fs.remove(detachedImage);7034+ // Emit failed with 0 subscribers, then a completed event on a fresh subscriber to verify7035+ // the pump processed the failure and dropped the prefetched bytes.7036+ yield* Queue.offer(adapterQueue, {7037+ type: "turn_item.updated",7038+ driver: CODEX_DRIVER,7039+ turnItem: { ...detachedBase, status: "failed", completedAt: now },7040+ });7041+ const verifySub = yield* runtime.subscribeEvents!;
Pushed61ba70c
github-actions[bot](GitHub profile, opens in a new tab) removed labelssize:XXL
github-actions[bot](GitHub profile, opens in a new tab) added labelssize:XL
- @@ -0,0 +344,21 @@344+345+ const snapshotter = yield* ViewedImageSnapshot.ViewedImageSnapshot;346+ const threadId = ThreadId.make("thread-guard");347+ expect(yield* snapshotter.snapshot({ threadId, viewedImagePath: secretPng })).toBeNull();348+ expect(yield* snapshotter.snapshot({ threadId, viewedImagePath: textFile })).toBeNull();349+ expect(350+ yield* snapshotter.snapshot({ threadId, viewedImagePath: "file:///tmp/a%00.png" }),351+ ).toBeNull();352+ expect(353+ yield* Effect.flatMap(ViewedImageSnapshot.ViewedImageSnapshot, (svc) =>354+ svc.snapshot({ threadId, viewedImagePath: "relative.png" }),355+ ).pipe(Effect.provide(makeSnapshotLayer(" "))),356+ ).toBeNull();357+ expect(358+ yield* snapshotter.snapshot({ threadId, viewedImagePath: "\\\\evil-host\\share\\x.png" }),359+ ).toBeNull();360+ expect(361+ yield* Effect.flatMap(ViewedImageSnapshot.ViewedImageSnapshot, (svc) =>362+ svc.snapshot({ threadId, viewedImagePath: "..\\other\\x.png" }),363+ ).pipe(Effect.provide(makeSnapshotLayer("\\\\evil-host\\share\\repo"))),364+ ).toBeNull();@@ -0,0 +86,21 @@86+ if (parsed === null) return null;87+ candidate = safeDecodeURIComponent(parsed.path);88+ }89+ if (/[\r\n\0]/.test(candidate)) return null;90+ return stripSlashPrefixedWindowsDrive(candidate);91+}92+93+function readOutputInlineImage(output: unknown): SnapshotPayload | null {94+ const image = toolOutputImages(output)[0];95+ if (image?.data === undefined || image.data.length > MAX_TOOL_OUTPUT_IMAGE_BASE64_LENGTH) {96+ return null;97+ }98+ const extension = inferImageExtension({ mimeType: image.mimeType });99+ if (!SAFE_IMAGE_FILE_EXTENSIONS.has(extension)) return null;100+ const decoded = Base64.decode(image.data);101+ if (decoded._tag !== "Success") return null;102+ const bytes = decoded.success;103+ if (bytes.byteLength === 0 || bytes.byteLength > VIEWED_IMAGE_SNAPSHOT_MAX_BYTES) {104+ return null;105+ }106+ return { bytes, extension };@@ -0,0 +175,21 @@175+ Effect.sync(() => {176+ if (entry !== undefined && prefetched.get(key) === entry) {177+ prefetched.delete(key);178+ prefetchedBytes -= entry.bytes.byteLength;179+ }180+ }),181+ ),182+ Effect.forkIn(layerScope),183+ );184+ // Update map, byte accounting, and evictions synchronously so concurrent prefetches cannot drift.185+ const displacedFibers: Array<Fiber.Fiber<void>> = [];186+ const existing = prefetched.get(key);187+ if (existing !== undefined) {188+ prefetched.delete(key);189+ prefetchedBytes -= existing.bytes.byteLength;190+ displacedFibers.push(existing.expiryFiber);191+ }192+ while (193+ prefetched.size >= MAX_PREFETCH_ENTRIES ||194+ (prefetched.size > 0 && prefetchedBytes + payload.bytes.byteLength > MAX_PREFETCH_BYTES)195+ ) {
Pushedd21c195
juliusmarminge added labelstakeover:needs-julius
juliusmarminge removed labelstakeover:in-progress
Sign in to join this conversation.






Approvability#
Verdict: Needs Human Approval
Macroscope's review found this PR requires human approval — Viewed images will automatically be saved as attachments so previews survive source-file deletion. This changes default image retention; a human must confirm that preserving potentially sensitive scratch images is intended.
You can add or adjust custom eligibility rules. [Learn more](https://docs.macroscope.com/approvability#example-custom-eligibility-rules).