fix: chat images keep the version from when the message was written #14009
Closedflamboh(GitHub profile, opens in a new tab)wants to merge 6 commits into
t3code/codex-turn-mapping fromrefs/pull/14009/headopened 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:L
- apps/server/src/orchestration-v2/MessageMediaSnapshots.ts line 152OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +132,21 @@132+ const path = yield* Path.Path;133+ const projections = yield* ProjectionStoreV2;134+135+ const copyIntoAttachments = Effect.fnUntraced(function* (input: {136+ readonly threadId: ThreadId;137+ readonly sourcePath: string;138+ readonly budgetBytes: number;139+ }) {140+ const sourcePath = yield* fileSystem.realPath(input.sourcePath);141+ if (!isWorkspaceImagePreviewPath(sourcePath)) return null;142+ const info = yield* fileSystem.stat(sourcePath);143+ const size = Number(info.size);144+ if (145+ info.type !== "File" ||146+ size > PROVIDER_SEND_TURN_MAX_IMAGE_BYTES ||147+ size > input.budgetBytes148+ ) {149+ return null;150+ }151+ const bytes = yield* fileSystem.readFile(sourcePath);152+ if (bytes.byteLength > PROVIDER_SEND_TURN_MAX_IMAGE_BYTES) return null;apps/server/src/orchestration-v2/ProviderEventIngestor.ts line 310OutdatedResolvedby flamboh(GitHub profile, opens in a new tab)@@ -293,3 +295,16 @@293295 );294296 });295297298+ /** Providers re-send whole items; a completed message keeps the image copies it already took. */299+ const keepMediaSnapshots = Effect.fn("ProviderEventIngestor.keepMediaSnapshots")(function* (300+ item: OrchestrationV2TurnItem,301+ ) {302+ if (303+ item.type !== "assistant_message" ||304+ item.streaming ||305+ item.mediaSnapshots !== undefined ||306+ localMarkdownImagePaths(item.text).length === 0307+ ) {308+ return item;309+ }310+ const { turnItems } = yield* projections.getThreadRecords(item.threadId, ["turnItems"], {apps/server/src/orchestration-v2/MessageMediaSnapshots.ts lines 54 to 60OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +40,21 @@40+ } catch {41+ return value;42+ }43+}44+45+function stripSlashPrefixedWindowsDrive(path: string): string {46+ return SLASH_PREFIXED_WINDOWS_DRIVE_PATTERN.test(path) ? path.slice(1) : path;47+}48+49+/** Mirrors the clients' markdown image classification for absolute host paths. */50+function localImagePath(destination: string): string | null {51+ const trimmed = destination.trim();52+ const source = trimmed.startsWith("<") && trimmed.endsWith(">") ? trimmed.slice(1, -1) : trimmed;53+ let path: string;54+ if (/^file:/i.test(source)) {55+ try {56+ const url = new URL(source);57+ if (url.hostname !== "" && url.hostname.toLowerCase() !== "localhost") return null;58+ path = url.pathname;59+ } catch {60+ return null;apps/server/src/orchestration-v2/MessageMediaSnapshots.ts lines 129 to 152Resolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +61,21 @@61+ }62+ } else {63+ path = source.split("#", 1)[0]!.split("?", 1)[0]!;64+ }65+ path = stripSlashPrefixedWindowsDrive(safeDecode(path));66+ const absolute = (path.startsWith("/") && !path.startsWith("//")) || isWindowsAbsolutePath(path);67+ return absolute && isWorkspaceImagePreviewPath(path) ? path : null;68+}69+70+/** Absolute host image paths a message embeds, in order and without duplicates. */71+export function localMarkdownImagePaths(text: string): ReadonlyArray<string> {72+ if (!text.includes("![") && !/<img\b/i.test(text)) return [];73+ const paths = new Set<string>();74+ for (const match of text.matchAll(MARKDOWN_IMAGE_PATTERN)) {75+ const path = localImagePath(match[1]!);76+ if (path !== null) paths.add(path);77+ }78+ for (const match of text.matchAll(HTML_IMAGE_PATTERN)) {79+ const path = localImagePath(match[1] ?? match[2] ?? "");80+ if (path !== null) paths.add(path);81+ }
- apps/server/src/orchestration-v2/runtimeLayer.ts lines 31 to 31OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -28,3 +28,4 @@2828 import { layerFromOrchestrationEventStore as eventStoreLayer } from "./EventStore.ts";2929 import { layer as idAllocatorLayer } from "./IdAllocator.ts";3030 import { layer as legacyV1ThreadImporterLayer } from "./LegacyV1ThreadImporter.ts";31+import { live as messageMediaSnapshotLayer } from "./MessageMediaSnapshots.ts";apps/server/src/orchestration-v2/EffectWorker.ts lines 34 to 34OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -31,3 +31,4 @@3131 import { ProviderTurnControlServiceV2 } from "./ProviderTurnControlService.ts";3232 import { ProviderTurnStartServiceV2 } from "./ProviderTurnStartService.ts";3333 import { RuntimeRequestServiceV2 } from "./RuntimeRequestService.ts";34+import { MessageMediaSnapshotService } from "./MessageMediaSnapshots.ts";
github-actions[bot](GitHub profile, opens in a new tab) removed labelssize:L
github-actions[bot](GitHub profile, opens in a new tab) added labelssize:XL
- apps/server/src/orchestration-v2/MessageMediaSnapshots.ts line 41OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +21,21 @@21+import * as Path from "effect/Path";22+import * as SqlClient from "effect/unstable/sql/SqlClient";23+24+import { openMediaFile, readMediaFileCapped } from "../assets/MediaFile.ts";25+import { createDeterministicAttachmentId } from "../attachmentStore.ts";26+import { resolveAttachmentRelativePath } from "../attachmentPaths.ts";27+import * as ServerConfig from "../config.ts";28+import type { PendingOrchestrationEffectV2 } from "./EffectOutbox.ts";29+import { EventSinkV2 } from "./EventSink.ts";30+import { IdAllocatorV2 } from "./IdAllocator.ts";31+import { ProjectionStoreV2 } from "./ProjectionStore.ts";32+33+const MAX_SNAPSHOTS_PER_MESSAGE = 20;34+const MAX_SNAPSHOT_BYTES_PER_MESSAGE = 4 * PROVIDER_SEND_TURN_MAX_IMAGE_BYTES;35+36+const MARKDOWN_IMAGE_PATTERN = /!\[((?:\\.|[^\]\\\n])*)\]/g;37+const MARKDOWN_REFERENCE_LABEL_PATTERN = /\[((?:\\.|[^\]\\\n])*)\]/y;38+const MARKDOWN_REFERENCE_DEFINITION_PATTERN =39+ /^ {0,3}\[((?:\\.|[^\]\\\n])+)\]:[ \t]*(?:\n[ \t]*)?(<[^>\n]*>|\S+)/gm;40+const MARKDOWN_ESCAPABLE_PATTERN = /[!-/:-@[-`{-~]/;41+const HTML_IMAGE_PATTERN = /<img\b[^>]*?\ssrc\s*=\s*(?:"([^"]*)"|'([^']*)')/gi;apps/server/src/orchestration-v2/MessageMediaSnapshots.ts lines 208 to 211OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +191,21 @@191+192+ const copyIntoAttachments = Effect.fnUntraced(function* (input: {193+ readonly threadId: ThreadId;194+ readonly sourcePath: string;195+ readonly maxBytes: number;196+ }) {197+ const sourcePath = yield* fileSystem.realPath(input.sourcePath);198+ if (!isWorkspaceImagePreviewPath(sourcePath)) return null;199+ const bytes = yield* Effect.scoped(200+ Effect.flatMap(openMediaFile(sourcePath), (file) =>201+ file === null202+ ? Effect.succeed(null)203+ : readMediaFileCapped(sourcePath, file, input.maxBytes),204+ ),205+ );206+ if (bytes === null) return null;207+ const digest = Encoding.encodeHex(yield* crypto.digest("SHA-256", bytes));208+ const attachmentId = createDeterministicAttachmentId(209+ input.threadId,210+ `media-snapshot:${digest}`,211+ );
- apps/server/src/orchestration-v2/MessageMediaSnapshots.ts line 196OutdatedResolvedby flamboh(GitHub profile, opens in a new tab)@@ -0,0 +176,21 @@176+ threadId: item.threadId,177+ request: { type: "message-media.snapshot", runId: item.runId, turnItemId: item.id },178+ });179+ }180+ return [...effects.values()];181+}182+183+interface MessageMediaSnapshotTarget {184+ readonly threadId: ThreadId;185+ readonly runId: RunId | null;186+ readonly turnItemId: TurnItemId;187+}188+189+export class MessageMediaSnapshotService extends Context.Service<190+ MessageMediaSnapshotService,191+ {192+ readonly snapshot: (input: MessageMediaSnapshotTarget) => Effect.Effect<void>;193+ }194+>()("t3/orchestration-v2/MessageMediaSnapshots/MessageMediaSnapshotService") {}195+196+const make = Effect.gen(function* () {
juliusmarminge closed this
Sign in to join this conversation.
macroscopeapp[bot](GitHub profile, opens in a new tab) reviewed