Skip to content
Source
Sign inSign up
pingdotgg/t3code

fix(chat): show Codex generated images in the thread #6441

Closedsambhavthakkar(GitHub profile, opens in a new tab)wants to merge 4 commits intomain fromrefs/pull/6441/headopened View on GitHub

What Changed

Codex imagegen already writes a file and emits savedPath. T3 dropped that path, labeled the row Image view, and only served workspace files, so generated images never showed in chat.

  • Keep savedPath on the Codex item and label it Generated image
  • Serve $CODEX_HOME/generated_images through signed asset URLs (not the base64 result over the websocket)
  • Render the file inline in web and mobile chat (markdown ![]() and the work row)

Why

The file is already on disk and the protocol already names it. Chat should show the picture, including remote clients.

UI Changes

  • Before: work row is a generic Image view / file path; markdown ![]() does not load
  • After: the generated file renders inline in the thread and can be expanded

Checklist

  • This PR is small and focused
  • I explained what changed and why
  • I included before/after screenshots for any UI changes

Note

Medium Risk Adds host-path asset access outside the workspace with root allowlisting—security-sensitive but scoped to Codex generated_images and exact basename tokens; broad touch across server assets, ingestion, and both clients.

Overview Codex-generated images now render inline in web and mobile chat (markdown images and work-log rows) instead of showing only a path or a generic “Image view” label.

On the server, Codex imageGeneration / imageView items keep full savedPath (no truncation for image_view), map to Generated image where appropriate, and workspace asset URLs can fall back to host-image-exact tokens for files under configured Codex generated_images roots when the path is outside the project workspace. WebSocket asset issuance passes those roots from server settings.

Clients add custom markdown image rendering (renderImage on native markdown; ChatWorkspaceImage / MarkdownWorkspaceImage) with signed workspace URLs, loading/error UI, and tap-to-preview. Work-log activities expose imagePath from lifecycle payloads for inline previews. Mobile asset hooks gain useAssetUrlState for non-binary loading/failure handling; list sizing skips fixed height when a row has an image preview.

Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit a1816fc23639c4e9086c7c2e1d2d45730b2a0e29. Bugbot is set up for automated code reviews on this repo. Configure [here](https://www.cursor.com/dashboard/bugbot).

Note

Show Codex-generated images inline in chat threads on web and mobile

  • Adds end-to-end support for rendering image_view work log entries as inline image previews in both the web MessagesTimeline and mobile ThreadFeed, with click-to-expand dialogs and loading/failure states.
  • Introduces a new host-image-exact asset claim in AssetAccess.ts so the server can securely serve generated images that live outside the workspace root, validated against configured generatedImagesRoots.
  • Extends CodexAdapter.ts to populate detail on imageGeneration/imageView items with the saved file path, and preserves full (untruncated) paths through the ingestion pipeline for image_view events.
  • Adds a renderImage prop to NativeMarkdownBlock and SelectableMarkdownText so custom image renderers can be injected into the markdown tree on mobile.
  • Risk: image_view detail strings are no longer truncated anywhere in the pipeline; very long paths are passed through as-is.
Macroscope summarized a1816fc.
    1. coderabbitai[bot](GitHub profile, opens in a new tab)commented

      Important

      Review skipped

      Auto reviews are disabled on this repository. Please check the settings in the CodeRabbit UI or the .coderabbit.yaml file in this repository. To trigger a single review, invoke the @coderabbitai review command.

      ⚙️ Run configuration

      Configuration used: Repository UI

      Review profile: CHILL

      Plan: Pro Plus

      Run ID: 140d9003-d0d1-4b7e-a057-eccf5aa815a3

      You can disable this status message by setting the reviews.review_status to false in the CodeRabbit configuration file.

      Use the checkbox below for a quick retry:

      • 🔍 Trigger review

      Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

      ❤️ Share
      Comment `@coderabbitai help` to get the list of available commands.
    2. github-actions[bot](GitHub profile, opens in a new tab) added labelsvouch:unvouched

    3. One finding on Effect error modeling in apps/server/src/assets/AssetAccess.ts. Everything else in the changed Effect code (namespace imports from effect/*, Effect.catchTags for the single WorkspacePathOutsideRootError tag, Path.Path acquired from the environment in resolveCodexGeneratedImagesRoots, no new Layer.succeed/ManagedRuntime/runPromise in service code) follows the conventions.

      Posted via Macroscope — Effect Service Conventions
    4. One finding on Effect error modeling in apps/server/src/assets/AssetAccess.ts. Everything else in the changed Effect code (namespace imports from effect/*, Effect.catchTags for the single WorkspacePathOutsideRootError tag, Path.Path acquired from the environment in resolveCodexGeneratedImagesRoots, no new Layer.succeed/ManagedRuntime/runPromise in service code) follows the conventions.

      Posted via Macroscope — Effect Service Conventions
    5. @@ -127,3 +133,10 @@
      127133
      128134 const nowIso = Effect.map(DateTime.now, DateTime.formatIso);
      129135 const EDITOR_DISCOVERY_TIMEOUT = Duration.seconds(5);
      136+const decodeCodexSettings = Schema.decodeUnknownOption(CodexSettings);
      137+
      138+const resolveCodexGeneratedImagesRoots = Effect.fn("resolveCodexGeneratedImagesRoots")(
      139+ function* (settings: ServerSettingsValue) {
      140+ const path = yield* Path.Path;
      141+ const roots: string[] = [];
      142+ const instances = Object.values(settings.providerInstances)
      macroscopeapp[bot](GitHub profile, opens in a new tab)commented

      🔴 Critical src/ws.ts:142

      A client authorized for one thread can mint a signed URL for a known image from another configured Codex instance or thread. resolveCodexGeneratedImagesRoots returns generated_images roots for every Codex instance, while asset issuance validates only the requested thread, so an absolute path under any returned root bypasses thread/workspace isolation. Restrict resolution to the thread's modelSelection.instanceId (and its session provider instance) instead of returning all configured roots.

      🤖 Copy this AI Prompt to have your agent fix this:
      In file @apps/server/src/ws.ts around line 142:
      
      A client authorized for one thread can mint a signed URL for a known image from another configured Codex instance or thread. `resolveCodexGeneratedImagesRoots` returns `generated_images` roots for every Codex instance, while asset issuance validates only the requested thread, so an absolute path under any returned root bypasses thread/workspace isolation. Restrict resolution to the thread's `modelSelection.instanceId` (and its session provider instance) instead of returning all configured roots.
      @@ -795,4 +801,5 @@
      795801 payload: {
      796802 itemType: event.payload.itemType,
      797803 ...(event.payload.status ? { status: event.payload.status } : {}),
      798- ...(event.payload.detail ? { detail: truncateDetail(event.payload.detail) } : {}),
      804+ ...(event.payload.detail
      805+ ? { detail: toolLifecycleDetail(event.payload.itemType, event.payload.detail) }
      macroscopeapp[bot](GitHub profile, opens in a new tab)commented

      🟡 Medium Layers/ProviderRuntimeIngestion.ts:805

      image_view activity details are persisted and sent to clients without the 180-character cap, so OpenCode image-tool outputs—including large or base64 text—can create oversized activity records and websocket payloads. toolLifecycleDetail disables truncation for every image_view, even though OpenCode maps any tool name containing “image” to that type and detailFromToolPart supplies the full output or error text; preserve untruncated details only after verifying they are file paths (or only for the Codex generated-image case).

      🤖 Copy this AI Prompt to have your agent fix this:
      In file @apps/server/src/orchestration/Layers/ProviderRuntimeIngestion.ts around line 805:
      
      `image_view` activity details are persisted and sent to clients without the 180-character cap, so OpenCode image-tool outputs—including large or base64 text—can create oversized activity records and websocket payloads. `toolLifecycleDetail` disables truncation for every `image_view`, even though OpenCode maps any tool name containing “image” to that type and `detailFromToolPart` supplies the full output or error text; preserve untruncated details only after verifying they are file paths (or only for the Codex generated-image case).
      @@ -264,9 +264,20 @@
      264264 case "image_view":
      265- return "Image view";
      265+ return item?.type === "imageGeneration" ? "Generated image" : "Image view";
      266266 case "error":
      267267 return "Error";
      268268 default:
      269269 return undefined;
      270270 }
      271271 }
      272272
      273+const IMAGE_GENERATION_RESULT_PATH_MAX_CHARS = 1024;
      274+
      275+function imageGenerationResultPath(result: string | undefined): string | undefined {
      276+ const trimmed = trimText(result);
      277+ if (!trimmed || trimmed.length > IMAGE_GENERATION_RESULT_PATH_MAX_CHARS) {
      278+ return undefined;
      279+ }
      280+ if (trimmed.includes("\n") || /\s/.test(trimmed)) {
      281+ return undefined;
      282+ }
      283+ if (trimmed.includes("/") || trimmed.includes("\\")) {
      macroscopeapp[bot](GitHub profile, opens in a new tab)commented

      🟡 Medium Layers/CodexAdapter.ts:283

      imageGenerationResultPath returns short base64 image data containing / as detail, so image rows treat the payload as a filesystem path and render a failed preview instead of falling back to revisedPrompt. Validate that result is an actual path rather than relying on / alone.

      🤖 Copy this AI Prompt to have your agent fix this:
      In file @apps/server/src/provider/Layers/CodexAdapter.ts around line 283:
      
      `imageGenerationResultPath` returns short base64 image data containing `/` as `detail`, so image rows treat the payload as a filesystem path and render a failed preview instead of falling back to `revisedPrompt`. Validate that `result` is an actual path rather than relying on `/` alone.
    6. @@ -273 +275,21 @@
      275+function imageGenerationResultPath(result: string | undefined): string | undefined {
      276+ const trimmed = trimText(result);
      277+ if (!trimmed || trimmed.length > IMAGE_GENERATION_RESULT_PATH_MAX_CHARS) {
      278+ return undefined;
      279+ }
      280+ if (trimmed.includes("\n") || /\s/.test(trimmed)) {
      281+ return undefined;
      282+ }
      283+ if (trimmed.includes("/") || trimmed.includes("\\")) {
      284+ return trimmed;
      285+ }
      286+ return undefined;
      287+}
      288+
      273289 function itemDetail(itemType: CanonicalItemType, item: CodexLifecycleItem): string | undefined {
      290+ if (item.type === "imageGeneration") {
      291+ return (
      292+ trimText(item.savedPath ?? undefined) ??
      293+ imageGenerationResultPath(item.result) ??
      294+ trimText(item.revisedPrompt ?? undefined)
      295+ );
      macroscopeapp[bot](GitHub profile, opens in a new tab)commented

      🟡 Medium Layers/CodexAdapter.ts:291

      Pathless imageGeneration items return revisedPrompt as detail, so extractImageViewPath sends prompt text such as a ceramic mug to the workspace-asset loader as imagePath, producing a broken image preview. Only actual image paths should populate this detail channel; remove the revisedPrompt fallback.

      Suggested change
      291- return (
      292- trimText(item.savedPath ?? undefined) ??
      293- imageGenerationResultPath(item.result) ??
      294- trimText(item.revisedPrompt ?? undefined)
      295- );
      291+ return (
      292+ trimText(item.savedPath ?? undefined) ??
      293+ imageGenerationResultPath(item.result)
      294+ );
      Also found in 1 other location(s)

      apps/mobile/src/lib/threadActivity.ts:966

      extractImageViewPath treats every non-empty payload.detail as an image path. For an imageGeneration item without savedPath (the protocol makes it optional), CodexAdapter.itemDetail can populate detail with revisedPrompt; this then becomes imagePath, so mobile attempts to request and render the prompt text as a workspace asset and shows a broken image preview. The fallback should only accept detail when it is known to be a path (for example, an actual imageView item), not for pathless image-generation results.

      🤖 Copy this AI Prompt to have your agent fix this:
      In file @apps/server/src/provider/Layers/CodexAdapter.ts around lines 291-295:
      
      Pathless `imageGeneration` items return `revisedPrompt` as `detail`, so `extractImageViewPath` sends prompt text such as `a ceramic mug` to the workspace-asset loader as `imagePath`, producing a broken image preview. Only actual image paths should populate this detail channel; remove the `revisedPrompt` fallback.
      
      Also found in 1 other location(s):
      - apps/mobile/src/lib/threadActivity.ts:966 -- `extractImageViewPath` treats every non-empty `payload.detail` as an image path. For an `imageGeneration` item without `savedPath` (the protocol makes it optional), `CodexAdapter.itemDetail` can populate `detail` with `revisedPrompt`; this then becomes `imagePath`, so mobile attempts to request and render the prompt text as a workspace asset and shows a broken image preview. The fallback should only accept `detail` when it is known to be a path (for example, an actual `imageView` item), not for pathless image-generation results.
      
      @@ -1542,3 +1545,20 @@
      15421545 />
      15431546 );
      15441547 },
      1548+ img({ src, alt }) {
      1549+ const fileLinkMeta = src ? resolveMarkdownFileLinkMeta(src, cwd) : null;
      1550+ if (
      1551+ fileLinkMeta &&
      1552+ isWorkspaceImagePreviewPath(fileLinkMeta.filePath) &&
      1553+ threadRef
      1554+ ) {
      1555+ return (
      1556+ <ChatWorkspaceImage
      1557+ environmentId={threadRef.environmentId}
      1558+ threadRef={threadRef}
      1559+ path={fileLinkMeta.filePath}
      1560+ alt={alt ?? fileLinkMeta.basename}
      1561+ />
      1562+ );
      1563+ }
      1564+ if (src && /^https?:\/\//i.test(src)) {
      macroscopeapp[bot](GitHub profile, opens in a new tab)commented

      🟡 Medium components/ChatMarkdown.tsx:1564

      Protocol-relative images such as ![logo](//cdn.example.com/logo.png) fail to load and, when a thread exists, are sent to ChatWorkspaceImage as a workspace path. The img renderer only identifies http:// and https:// as remote, so resolveMarkdownFileLinkMeta classifies //cdn.example.com/logo.png as a file link; treat // URLs as remote as well.

      🤖 Copy this AI Prompt to have your agent fix this:
      In file @apps/web/src/components/ChatMarkdown.tsx around line 1564:
      
      Protocol-relative images such as `![logo](//cdn.example.com/logo.png)` fail to load and, when a thread exists, are sent to `ChatWorkspaceImage` as a workspace path. The `img` renderer only identifies `http://` and `https://` as remote, so `resolveMarkdownFileLinkMeta` classifies `//cdn.example.com/logo.png` as a file link; treat `//` URLs as remote as well.
      @@ -1821,3 +1965,5 @@
      18211965 (info: { item: ThreadFeedEntry; index: number }) =>
      18221966 renderFeedEntry(info, {
      18231967 environmentId: props.environmentId,
      1968+ threadId: props.threadId,
      1969+ workspaceRoot: props.workspaceRoot,
      macroscopeapp[bot](GitHub profile, opens in a new tab)commented

      🟠 High threads/ThreadFeed.tsx:1969

      Visible image rows keep using the previous workspaceRoot when threadCwd changes without a feed-data change, so images remain missing or resolve against the wrong root until another list invalidation occurs. workspaceRoot is captured by renderItem but is absent from listAppearanceData/extraData, and LegendList does not repaint visible rows when only that closure changes; include it in extraData (or otherwise invalidate/remount the rows).

      🤖 Copy this AI Prompt to have your agent fix this:
      In file @apps/mobile/src/features/threads/ThreadFeed.tsx around line 1969:
      
      Visible image rows keep using the previous `workspaceRoot` when `threadCwd` changes without a feed-data change, so images remain missing or resolve against the wrong root until another list invalidation occurs. `workspaceRoot` is captured by `renderItem` but is absent from `listAppearanceData`/`extraData`, and LegendList does not repaint visible rows when only that closure changes; include it in `extraData` (or otherwise invalidate/remount the rows).
      @@ -0,0 +22,21 @@
      22+ Unable to load image{props.alt ? ` “${props.alt}”` : ""}.
      23+ </div>
      24+ );
      25+ }
      26+
      27+ return (
      28+ <>
      29+ <button
      30+ type="button"
      31+ className={cn(
      32+ "my-2 block max-w-full cursor-zoom-in overflow-hidden rounded-lg border border-border/80 bg-background/70",
      33+ props.className,
      34+ )}
      35+ aria-label={`Preview ${name}`}
      36+ onClick={() => setExpanded(true)}
      37+ >
      38+ <img
      39+ src={props.src}
      40+ alt={name}
      41+ className="block h-auto max-h-[360px] max-w-full object-contain"
      42+ onError={() => setFailed(true)}
      macroscopeapp[bot](GitHub profile, opens in a new tab)commented

      🟡 Medium chat/ChatWorkspaceImage.tsx:15

      After ChatRemoteImage's image load fails, changing props.src still renders the old error state, so corrected remote URLs remain permanently hidden. Because failed is a component-wide boolean, it is never cleared for the new URL; track the failed URL instead (or reset the state when props.src changes).

      -  const [failed, setFailed] = useState(false);
      +  const [failed, setFailed] = useState<string | null>(null);
       
      -  if (failed) {
      +  if (failed === props.src) {
           return (
             <div className="my-2 rounded-lg border border-border/80 bg-background/70 px-3 py-2 text-secondary-label text-xs">
               Unable to load image{props.alt ? ` “${props.alt}”` : ""}.
      @@
      -          onError={() => setFailed(true)}
      +          onError={() => setFailed(props.src)}
      🤖 Copy this AI Prompt to have your agent fix this:
      In file @apps/web/src/components/chat/ChatWorkspaceImage.tsx around lines 15-42:
      
      After `ChatRemoteImage`'s image load fails, changing `props.src` still renders the old error state, so corrected remote URLs remain permanently hidden. Because `failed` is a component-wide boolean, it is never cleared for the new URL; track the failed URL instead (or reset the state when `props.src` changes).
      @@ -2367,3 +2394,5 @@
      23672394 </div>
      23682395 </div>
      23692396 </div>
      2397+ {imagePath && threadRef ? (
      2398+ <div className="ms-7 mt-1" onClick={stopRowToggle} onPointerDown={stopRowToggle}>
      macroscopeapp[bot](GitHub profile, opens in a new tab)commented

      🟡 Medium chat/MessagesTimeline.tsx:2398

      When ChatWorkspaceImage is focused, pressing Enter or Space bubbles to the row's onKeyDown, which calls preventDefault() and toggles expanded instead of activating the image button. Add an onKeyDown handler to this wrapper that stops propagation so keyboard users can open the generated-image dialog.

      🤖 Copy this AI Prompt to have your agent fix this:
      In file @apps/web/src/components/chat/MessagesTimeline.tsx around line 2398:
      
      When `ChatWorkspaceImage` is focused, pressing Enter or Space bubbles to the row's `onKeyDown`, which calls `preventDefault()` and toggles `expanded` instead of activating the image button. Add an `onKeyDown` handler to this wrapper that stops propagation so keyboard users can open the generated-image dialog.
    7. Cursor Bugbot has reviewed your changes using high effort and found 1 potential issue.

      Fix All in Cursor ❌ Bugbot Autofix is OFF. To automatically fix reported issues with cloud agents, enable autofix in the [Cursor dashboard](https://www.cursor.com/dashboard/bugbot).

      Want fixes drafted automatically? Bugbot Autofix can create code changes for findings. A team admin can enable Autofix in the Cursor dashboard.

      Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit 3052999e087cd6b4cb2440e81bee51155754e5de. Configure [here](https://www.cursor.com/dashboard/bugbot).
    8. macroscopeapp[bot](GitHub profile, opens in a new tab)commented

      Approvability

      Verdict: Needs human review

      8 blocking correctness issues found. This PR introduces new capability for displaying Codex-generated images with cross-cutting changes to mobile, web, and server-side authorization logic. A Critical finding identifies a potential thread isolation bypass in asset URL minting that requires human review.

      You can customize Macroscope's approvability policy. [Learn more](https://docs.macroscope.com/approvability#example-custom-eligibility-rules).
    9. juliusmarminge closed this

Sign in to join this conversation.