Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

feat(aio): ai blob read path with authenticated immutable serving (#72679)

Carlos Marchal4a684f1d6f06
diff --git a/posthog/settings/object_storage.py b/posthog/settings/object_storage.py
index 9660fe0ef364..d98f414fac65 100644
--- a/posthog/settings/object_storage.py
+++ b/posthog/settings/object_storage.py
@@ -57,6 +57,14 @@ BILLING_USAGE_REPORTS_S3_BUCKET = os.getenv("BILLING_USAGE_REPORTS_S3_BUCKET") o
# back to the general bucket in dev / self-hosted.
AGENT_BUNDLES_S3_BUCKET = os.getenv("AGENT_BUNDLES_S3_BUCKET") or OBJECT_STORAGE_BUCKET
+# AI observability blob storage — offloaded binary payloads (images, files) from ai_events,
+# content-addressed under `{prefix}{team_id}/sha256/{hash}`. The nodejs ingestion writer reads
+# the same AI_BLOB_S3_BUCKET / AI_BLOB_S3_PREFIX env vars but defaults both to "" (offload
+# disabled) — any deployment enabling offload must set bucket AND prefix identically on both
+# services, or every read silently 404s. Defaults here match the local-dev ingestion wiring.
+AI_BLOB_S3_BUCKET = os.getenv("AI_BLOB_S3_BUCKET", "ai-blobs")
+AI_BLOB_S3_PREFIX = os.getenv("AI_BLOB_S3_PREFIX", "aio/")
+
# Identity matching scratch storage (products/growth `identity_matching_job`). The job writes
# per-run Parquet objects via ClickHouse `INSERT INTO FUNCTION s3(...)` and the read API globs
# them back with `s3(...)`, so only the ClickHouse cluster needs bucket access — the Dagster
diff --git a/posthog/storage/object_storage.py b/posthog/storage/object_storage.py
index 4021b877a931..1f2ebd5adfb0 100644
--- a/posthog/storage/object_storage.py
+++ b/posthog/storage/object_storage.py
@@ -59,6 +59,10 @@ class ObjectStorageClient(metaclass=abc.ABCMeta):
def read_bytes(self, bucket: str, key: str, *, missing_ok: bool = False) -> Optional[bytes]:
pass
+ @abc.abstractmethod
+ def read_object(self, bucket: str, key: str, *, missing_ok: bool = False) -> Optional[tuple[bytes, Optional[str]]]:
+ pass
+
@abc.abstractmethod
def tag(self, bucket: str, key: str, tags: dict[str, str]) -> None:
pass
@@ -126,6 +130,9 @@ class UnavailableStorage(ObjectStorageClient):
def read_bytes(self, bucket: str, key: str, *, missing_ok: bool = False) -> Optional[bytes]:
return None
+ def read_object(self, bucket: str, key: str, *, missing_ok: bool = False) -> Optional[tuple[bytes, Optional[str]]]:
+ return None
+
def tag(self, bucket: str, key: str, tags: dict[str, str]) -> None:
pass
@@ -237,10 +244,14 @@ class ObjectStorage(ObjectStorageClient):
return None
def read_bytes(self, bucket: str, key: str, *, missing_ok: bool = False) -> Optional[bytes]:
+ result = self.read_object(bucket, key, missing_ok=missing_ok)
+ return None if result is None else result[0]
+
+ def read_object(self, bucket: str, key: str, *, missing_ok: bool = False) -> Optional[tuple[bytes, Optional[str]]]:
s3_response = {}
try:
s3_response = self.aws_client.get_object(Bucket=bucket, Key=key)
- return s3_response["Body"].read()
+ return s3_response["Body"].read(), s3_response.get("ContentType")
except ClientError as e:
error_code = e.response.get("Error", {}).get("Code")
if error_code == "NoSuchKey" and missing_ok:
@@ -250,7 +261,6 @@ class ObjectStorage(ObjectStorageClient):
bucket=bucket,
file_name=key,
error=e,
- s3_response={},
)
capture_exception(e)
raise ObjectStorageError("read failed") from e
@@ -514,6 +524,13 @@ def read_bytes(file_name: str, bucket: str | None = None, *, missing_ok: bool =
return object_storage_client().read_bytes(bucket, file_name, missing_ok=missing_ok)
+def read_object(
+ file_name: str, bucket: str | None = None, *, missing_ok: bool = False
+) -> Optional[tuple[bytes, Optional[str]]]:
+ bucket = bucket or settings.OBJECT_STORAGE_BUCKET
+ return object_storage_client().read_object(bucket, file_name, missing_ok=missing_ok)
+
+
def list_objects(prefix: str) -> Optional[list[str]]:
return object_storage_client().list_objects(bucket=settings.OBJECT_STORAGE_BUCKET, prefix=prefix)
diff --git a/products/ai_observability/backend/api/__init__.py b/products/ai_observability/backend/api/__init__.py
index 3e80e6eaa918..e4f55ce65a73 100644
--- a/products/ai_observability/backend/api/__init__.py
+++ b/products/ai_observability/backend/api/__init__.py
@@ -1,3 +1,4 @@
+from .ai_blob import AIBlobViewSet
from .clustering import AIObservabilityClusteringRunViewSet
from .clustering_config import ClusteringConfigViewSet
from .clustering_job import ClusteringJobViewSet
@@ -22,6 +23,7 @@ from .trace_reviews import TraceReviewViewSet
from .translate import AIObservabilityTranslateViewSet
__all__ = [
+ "AIBlobViewSet",
"ClusteringConfigViewSet",
"ClusteringJobViewSet",
"AIObservabilityClusteringRunViewSet",
diff --git a/products/ai_observability/backend/api/ai_blob.py b/products/ai_observability/backend/api/ai_blob.py
new file mode 100644
index 000000000000..226b2b0bdf7f
--- /dev/null
+++ b/products/ai_observability/backend/api/ai_blob.py
@@ -0,0 +1,38 @@
+from django.conf import settings
+from django.http import HttpResponse
+
+from drf_spectacular.utils import extend_schema
+from rest_framework import viewsets
+from rest_framework.decorators import action
+from rest_framework.request import Request
+
+from posthog.api.routing import TeamAndOrgViewSetMixin
+from posthog.storage import object_storage
+
+INLINE_MIMES = {"image/png", "image/jpeg", "image/gif", "image/webp"}
+
+
+class AIBlobViewSet(TeamAndOrgViewSetMixin, viewsets.ViewSet):
+ # llm_analytics (not INTERNAL) so resource-level access controls apply to blob reads.
+ # Deliberately no scope_object_read_actions: the custom action then rejects API keys,
+ # keeping this endpoint session-only for v1.
+ scope_object = "llm_analytics"
+
+ @extend_schema(exclude=True)
+ @action(detail=False, methods=["GET"], url_path=r"v1/sha256/(?P<hash>[0-9a-f]{64})")
+ def serve(self, request: Request, hash: str, **kwargs) -> HttpResponse:
+ key = f"{settings.AI_BLOB_S3_PREFIX}{self.team_id}/sha256/{hash}"
+ result = object_storage.read_object(key, bucket=settings.AI_BLOB_S3_BUCKET, missing_ok=True)
+ if result is None:
+ return HttpResponse(status=404)
+ body, content_type = result
+ if content_type in INLINE_MIMES:
+ response = HttpResponse(body, content_type=content_type)
+ else:
+ response = HttpResponse(body, content_type="application/octet-stream")
+ # Bare attachment: a filename here would override the frontend's `download` attribute.
+ response["Content-Disposition"] = "attachment"
+ response["Cache-Control"] = "private, max-age=86400, immutable"
+ response["ETag"] = f'"{hash}"'
+ response["X-Content-Type-Options"] = "nosniff"
+ return response
diff --git a/products/ai_observability/backend/api/test/test_ai_blob.py b/products/ai_observability/backend/api/test/test_ai_blob.py
new file mode 100644
index 000000000000..bd82e5d49273
--- /dev/null
+++ b/products/ai_observability/backend/api/test/test_ai_blob.py
@@ -0,0 +1,51 @@
+from posthog.test.base import APIBaseTest
+from unittest.mock import patch
+
+from rest_framework import status
+
+HASH = "a" * 64
+
+
+class TestAIBlobEndpoint(APIBaseTest):
+ def _url(self, team_id: int | None = None, hash: str = HASH) -> str:
+ return f"/api/projects/{team_id or self.team.pk}/ai_blob/v1/sha256/{hash}"
+
+ @patch("products.ai_observability.backend.api.ai_blob.object_storage.read_object")
+ def test_serves_inline_image_with_immutable_caching(self, mock_read) -> None:
+ mock_read.return_value = (b"png-bytes", "image/png")
+ response = self.client.get(self._url())
+ assert response.status_code == status.HTTP_200_OK
+ assert response.content == b"png-bytes"
+ assert response["Content-Type"] == "image/png"
+ assert response["Cache-Control"] == "private, max-age=86400, immutable"
+ assert response["ETag"] == f'"{HASH}"'
+ assert response["X-Content-Type-Options"] == "nosniff"
+ assert mock_read.call_args.args[0] == f"aio/{self.team.pk}/sha256/{HASH}"
+ assert mock_read.call_args.kwargs["bucket"] == "ai-blobs"
+
+ @patch("products.ai_observability.backend.api.ai_blob.object_storage.read_object")
+ def test_non_allowlisted_mime_serves_as_download(self, mock_read) -> None:
+ mock_read.return_value = (b"pdf-bytes", "application/pdf")
+ response = self.client.get(self._url())
+ assert response.status_code == status.HTTP_200_OK
+ assert response["Content-Type"] == "application/octet-stream"
+ assert response["Content-Disposition"].startswith("attachment")
+
+ @patch("products.ai_observability.backend.api.ai_blob.object_storage.read_object")
+ def test_missing_object_is_404(self, mock_read) -> None:
+ mock_read.return_value = None
+ assert self.client.get(self._url()).status_code == status.HTTP_404_NOT_FOUND
+
+ def test_bad_hash_is_404_via_routing(self) -> None:
+ assert self.client.get(self._url(hash="zz" * 32)).status_code == status.HTTP_404_NOT_FOUND
+ assert self.client.get(self._url(hash="abc")).status_code == status.HTTP_404_NOT_FOUND
+
+ def test_other_team_is_denied(self) -> None:
+ other_team = self.create_team_with_organization(organization=self.create_organization_with_features([]))
+ response = self.client.get(self._url(team_id=other_team.pk))
+ assert response.status_code in (status.HTTP_403_FORBIDDEN, status.HTTP_404_NOT_FOUND)
+
+ def test_unauthenticated_is_denied(self) -> None:
+ self.client.logout()
+ response = self.client.get(self._url())
+ assert response.status_code in (status.HTTP_401_UNAUTHORIZED, status.HTTP_403_FORBIDDEN)
diff --git a/products/ai_observability/backend/api/test/test_ai_observability_access_control.py b/products/ai_observability/backend/api/test/test_ai_observability_access_control.py
index e9fc9eefe41d..9ac6c04f34ac 100644
--- a/products/ai_observability/backend/api/test/test_ai_observability_access_control.py
+++ b/products/ai_observability/backend/api/test/test_ai_observability_access_control.py
@@ -182,6 +182,15 @@ class TestAIObservabilityAccessControl(APIBaseTest):
response = self.client.get(f"/api/environments/{self.team.id}/{endpoint}/{obj.id}/")
self.assertEqual(response.status_code, status.HTTP_200_OK)
+ @patch("products.ai_observability.backend.api.ai_blob.object_storage.read_object")
+ def test_viewer_can_fetch_ai_blob(self, mock_read):
+ mock_read.return_value = (b"png-bytes", "image/png")
+ self._set_access_level(self.viewer_user, access_level="viewer")
+ self.client.force_login(self.viewer_user)
+
+ response = self.client.get(f"/api/projects/{self.team.id}/ai_blob/v1/sha256/{'a' * 64}")
+ self.assertEqual(response.status_code, status.HTTP_200_OK)
+
def test_viewer_can_list_score_definitions(self):
self._set_access_level(self.viewer_user, access_level="viewer")
self.client.force_login(self.viewer_user)
@@ -600,6 +609,15 @@ class TestAIObservabilityAccessControl(APIBaseTest):
response = self.client.get(f"/api/environments/{self.team.id}/{endpoint}/")
self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN)
+ @patch("products.ai_observability.backend.api.ai_blob.object_storage.read_object")
+ def test_none_access_blocks_ai_blob(self, mock_read):
+ mock_read.return_value = (b"png-bytes", "image/png")
+ self._set_access_level(self.no_access_user, access_level="none")
+ self.client.force_login(self.no_access_user)
+
+ response = self.client.get(f"/api/projects/{self.team.id}/ai_blob/v1/sha256/{'a' * 64}")
+ self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN)
+
# -- Resource inheritance: setting llm_analytics cascades to child resources --
@parameterized.expand(
diff --git a/products/ai_observability/backend/routes.py b/products/ai_observability/backend/routes.py
index 8403f9d07ea3..d939072fc4d4 100644
--- a/products/ai_observability/backend/routes.py
+++ b/products/ai_observability/backend/routes.py
@@ -2,6 +2,7 @@ from posthog.api.routing import RouterRegistry
from posthog.settings import CLOUD_DEPLOYMENT, DEBUG, TEST
from products.ai_observability.backend.api import (
+ AIBlobViewSet,
AIObservabilityClusteringRunViewSet,
AIObservabilityOfflineEvaluationsViewSet,
AIObservabilitySummarizationViewSet,
@@ -32,6 +33,7 @@ from products.ai_observability.backend.api import (
def register_routes(routers: RouterRegistry) -> None:
+ routers.projects.register(r"ai_blob", AIBlobViewSet, "project_ai_blob", ["project_id"])
routers.root.register(r"llm_proxy", LLMProxyViewSet, "llm_proxy")
# @me/spend is only useful where billing data is available; mirrors the
# CLOUD/DEBUG/TEST gate the registration carried inline.
diff --git a/products/ai_observability/frontend/ConversationDisplay/ConversationMessagesDisplay.tsx b/products/ai_observability/frontend/ConversationDisplay/ConversationMessagesDisplay.tsx
index 6fc32835bf1d..f9e6634181e9 100644
--- a/products/ai_observability/frontend/ConversationDisplay/ConversationMessagesDisplay.tsx
+++ b/products/ai_observability/frontend/ConversationDisplay/ConversationMessagesDisplay.tsx
@@ -1,4 +1,5 @@
import clsx from 'clsx'
+import { useValues } from 'kea'
import React from 'react'
import { IconCode, IconEye, IconMarkdown, IconMarkdownFilled, IconWrench } from '@posthog/icons'
@@ -9,7 +10,9 @@ import { HighlightedJSONViewer } from 'lib/components/HighlightedJSONViewer'
import { IconExclamation, IconEyeHidden } from 'lib/lemon-ui/icons'
import { LemonMarkdown } from 'lib/lemon-ui/LemonMarkdown'
import { isObject } from 'lib/utils/guards'
+import { teamLogic } from 'scenes/teamLogic'
+import { resolveAiBlobUrl, resolveDataUri } from '../aiBlob'
import { getJsonContainerForDisplay, JSONValueDisplay } from '../components/JSONValueDisplay'
import { MessageSentimentBar } from '../components/SentimentTag'
import { LLMInputOutput } from '../LLMInputOutput'
@@ -377,18 +380,23 @@ function getImageDisplayMessage(value: Record<string, unknown>): ImageDisplayMes
}
export const ImageMessageDisplay = ({ message }: { message: ImageDisplayMessage }): JSX.Element => {
+ const { currentTeamId } = useValues(teamLogic)
const { content } = message
if (typeof content === 'string') {
return <span>{content}</span>
} else if (content?.image) {
- return <img src={content.image} alt="User sent image" />
+ return <img src={resolveAiBlobUrl(content.image, currentTeamId)} alt="User sent image" />
}
return <span>{String(content ?? '')}</span>
}
-function renderContentItem(item: MultiModalContentItem, searchQuery?: string): JSX.Element | null {
+function renderContentItem(
+ item: MultiModalContentItem,
+ currentTeamId: number | string | null,
+ searchQuery?: string
+): JSX.Element | null {
if (typeof item === 'string') {
return searchQuery?.trim() ? (
<SearchHighlight string={item} substring={searchQuery} className="whitespace-pre-wrap" />
@@ -422,54 +430,48 @@ function renderContentItem(item: MultiModalContentItem, searchQuery?: string): J
}
if (isOpenAIImageURLMessage(item)) {
- return <img src={item.image_url.url} alt="Message content" className="max-w-full max-h-[400px] rounded" />
- }
-
- if (isAnthropicImageMessage(item)) {
return (
<img
- src={`data:${item.source.media_type};base64,${item.source.data}`}
+ src={resolveAiBlobUrl(item.image_url.url, currentTeamId)}
alt="Message content"
className="max-w-full max-h-[400px] rounded"
/>
)
}
+ if (isAnthropicImageMessage(item)) {
+ const src = resolveDataUri(item.source.data, item.source.media_type, currentTeamId)
+ return <img src={src} alt="Message content" className="max-w-full max-h-[400px] rounded" />
+ }
+
if (isGeminiImageMessage(item)) {
const inlineData = getGeminiInlineData(item)
if (!inlineData) {
return null
}
- return (
- <img
- src={`data:${inlineData.mime_type};base64,${inlineData.data}`}
- alt="Message content"
- className="max-w-full max-h-[400px] rounded"
- />
- )
+ const src = resolveDataUri(inlineData.data, inlineData.mime_type, currentTeamId)
+ return <img src={src} alt="Message content" className="max-w-full max-h-[400px] rounded" />
}
if (isOpenAIFileMessage(item)) {
- if (!item.file.file_data.startsWith('data:')) {
+ const resolved = resolveAiBlobUrl(item.file.file_data, currentTeamId)
+ if (resolved === item.file.file_data && !item.file.file_data.startsWith('data:')) {
return <span className="text-muted">{item.file.filename}</span>
}
return (
// eslint-disable-next-line react/forbid-elements
- <a href={item.file.file_data} download={item.file.filename} className="text-link hover:underline">
+ <a href={resolved} download={item.file.filename} className="text-link hover:underline">
{item.file.filename}
</a>
)
}
if (isAnthropicDocumentMessage(item)) {
+ const href = resolveDataUri(item.source.data, item.source.media_type, currentTeamId)
const fileName = `document.${item.source.media_type.split('/')[1] || 'bin'}`
return (
// eslint-disable-next-line react/forbid-elements
- <a
- href={`data:${item.source.media_type};base64,${item.source.data}`}
- download={fileName}
- className="text-link hover:underline"
- >
+ <a href={href} download={fileName} className="text-link hover:underline">
{fileName}
</a>
)
@@ -480,14 +482,11 @@ function renderContentItem(item: MultiModalContentItem, searchQuery?: string): J
if (!inlineData) {
return null
}
+ const href = resolveDataUri(inlineData.data, inlineData.mime_type, currentTeamId)
const fileName = `document.${inlineData.mime_type.split('/')[1] || 'bin'}`
return (
// eslint-disable-next-line react/forbid-elements
- <a
- href={`data:${inlineData.mime_type};base64,${inlineData.data}`}
- download={fileName}
- className="text-link hover:underline"
- >
+ <a href={href} download={fileName} className="text-link hover:underline">
{fileName}
</a>
)
@@ -496,14 +495,11 @@ function renderContentItem(item: MultiModalContentItem, searchQuery?: string): J
if (isOpenAIAudioMessage(item) || isGeminiAudioMessage(item)) {
const mimeType = 'mime_type' in item ? item.mime_type : undefined
const transcript = 'transcript' in item ? item.transcript : undefined
+ const src = resolveDataUri(item.data, mimeType ?? 'audio/wav', currentTeamId)
return (
<div className="space-y-2">
- <audio
- controls
- className="w-[500px]"
- src={mimeType ? `data:${mimeType};base64,${item.data}` : `data:audio/wav;base64,${item.data}`}
- />
+ <audio controls className="w-[500px]" src={src} />
{transcript && typeof transcript === 'string' && (
<div className="text-xs text-muted p-2 bg-bg-light rounded border">
<div className="font-semibold mb-1">Transcript:</div>
@@ -627,6 +623,7 @@ export const LLMMessageDisplay = React.memo(
onToggleXmlRendering?: () => void
messageSentiment?: { label: string; score: number }
}): JSX.Element => {
+ const { currentTeamId } = useValues(teamLogic)
const { role, content, ...additionalKwargs } = message
let resolvedIsRenderingMarkdown = isRenderingMarkdown
let resolvedIsRenderingXml = isRenderingXml
@@ -674,7 +671,7 @@ export const LLMMessageDisplay = React.memo(
<>
{content.map((item, index) => (
<React.Fragment key={index}>
- {renderContentItem(item, searchQuery)}
+ {renderContentItem(item, currentTeamId, searchQuery)}
{index < content.length - 1 && <div className="border-t my-2" />}
</React.Fragment>
))}
diff --git a/products/ai_observability/frontend/aiBlob.test.ts b/products/ai_observability/frontend/aiBlob.test.ts
new file mode 100644
index 000000000000..ea877d02db8a
--- /dev/null
+++ b/products/ai_observability/frontend/aiBlob.test.ts
@@ -0,0 +1,44 @@
+import { parseAiBlobPointer, resolveAiBlobUrl, resolveDataUri } from './aiBlob'
+
+const HASH = 'a'.repeat(64)
+const POINTER = `phaiblob://v1/sha256/${HASH}?mime=image%2Fpng&size=131072`
+
+describe('aiBlob', () => {
+ it('parses a pointer', () => {
+ expect(parseAiBlobPointer(POINTER)).toEqual({
+ version: 'v1',
+ algo: 'sha256',
+ hash: HASH,
+ mime: 'image/png',
+ size: 131072,
+ })
+ })
+
+ it('resolves a pointer to the environment endpoint', () => {
+ expect(resolveAiBlobUrl(POINTER, 1)).toBe(`/api/projects/1/ai_blob/v1/sha256/${HASH}`)
+ })
+
+ it.each([
+ ['http url', 'https://example.com/a.png'],
+ ['data uri', 'data:image/png;base64,AAAA'],
+ ['plain text', 'hello'],
+ ['bad hash', 'phaiblob://v1/sha256/xyz?mime=a&size=1'],
+ ['unknown algo', `phaiblob://v1/md5/${HASH}?mime=a&size=1`],
+ ['old scheme', `phblob://v1/sha256/${HASH}?mime=a&size=1`],
+ ])('passes through unchanged: %s', (_name, value) => {
+ expect(parseAiBlobPointer(value)).toBeNull()
+ expect(resolveAiBlobUrl(value, 1)).toBe(value)
+ })
+
+ it('passes through when teamId is missing', () => {
+ expect(resolveAiBlobUrl(POINTER, null)).toBe(POINTER)
+ })
+
+ it('resolves a pointer data field to the blob endpoint, ignoring the passed mime type', () => {
+ expect(resolveDataUri(POINTER, 'image/png', 1)).toBe(`/api/projects/1/ai_blob/v1/sha256/${HASH}`)
+ })
+
+ it('builds a data: URI from raw base64 when the data field is not a pointer', () => {
+ expect(resolveDataUri('AAAA', 'image/png', 1)).toBe('data:image/png;base64,AAAA')
+ })
+})
diff --git a/products/ai_observability/frontend/aiBlob.ts b/products/ai_observability/frontend/aiBlob.ts
new file mode 100644
index 000000000000..3c1fa5cb977c
--- /dev/null
+++ b/products/ai_observability/frontend/aiBlob.ts
@@ -0,0 +1,47 @@
+/** Frontend twin of the ingestion pointer module: the only place phaiblob:// URIs are interpreted. */
+export interface AiBlobPointer {
+ version: string
+ algo: string
+ hash: string
+ mime: string | null
+ size: number | null
+}
+
+const POINTER_SCHEME = 'phaiblob://'
+const POINTER_RE = /^phaiblob:\/\/(v1)\/(sha256)\/([0-9a-f]{64})(?:\?(.*))?$/
+
+export function parseAiBlobPointer(value: string): AiBlobPointer | null {
+ if (!value.startsWith(POINTER_SCHEME)) {
+ return null
+ }
+ const match = POINTER_RE.exec(value)
+ if (!match) {
+ return null
+ }
+ const params = new URLSearchParams(match[4] ?? '')
+ const sizeRaw = params.get('size')
+ return {
+ version: match[1],
+ algo: match[2],
+ hash: match[3],
+ mime: params.get('mime'),
+ size: sizeRaw && /^\d+$/.test(sizeRaw) ? parseInt(sizeRaw, 10) : null,
+ }
+}
+
+export function resolveAiBlobUrl(value: string, teamId: number | string | null): string {
+ const pointer = parseAiBlobPointer(value)
+ if (!pointer || teamId === null || teamId === undefined || teamId === '') {
+ return value
+ }
+ return `/api/projects/${teamId}/ai_blob/${pointer.version}/${pointer.algo}/${pointer.hash}`
+}
+
+/**
+ * Resolves a raw `data` field (base64 payload or, post-offload, a phaiblob:// pointer) to a
+ * renderable src: the blob endpoint URL if it's a pointer, otherwise the `data:` URI it always was.
+ */
+export function resolveDataUri(rawData: string, mimeType: string, teamId: number | string | null): string {
+ const resolved = resolveAiBlobUrl(rawData, teamId)
+ return resolved !== rawData ? resolved : `data:${mimeType};base64,${rawData}`
+}