: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.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
fix(tasks): run html artifact scripts in web previews (#111376)
Shy Alterd83be51c8cf5
diff --git a/.semgrep/rules/security/csp-header-outside-csp-middleware.yaml b/.semgrep/rules/security/csp-header-outside-csp-middleware.yamlindex 029677f4180c..caa3542d95bd 100644--- a/.semgrep/rules/security/csp-header-outside-csp-middleware.yaml+++ b/.semgrep/rules/security/csp-header-outside-csp-middleware.yaml@@ -21,15 +21,16 @@ rules:- metavariable-regex:metavariable: $HEADERregex: (?i)^["']?content-security-policy(-report-only)?["']?$- # Four documents sandbox untrusted HTML, so each carries a policy of its own rather than- # the app policy. Each exception names the policy it allows, not the file, so a fifth- # document in the same file trips the rule, and a change to one of these four policies+ # Five documents sandbox untrusted HTML, so each carries a policy of its own rather than+ # the app policy. Each exception names the policy it allows, not the file, so a sixth+ # document in the same file trips the rule, and a change to one of these five policies# trips it too. Each exception also pins the enforced header name, because the `sandbox`- # directive these four documents rely on has no effect when a browser gets the policy as+ # directive these five documents rely on has no effect when a browser gets the policy as# `Content-Security-Policy-Report-Only`. Adding an exception needs a team-security review.- pattern-not: $RESPONSE["Content-Security-Policy"] = artifact_csp(...)# The draft canvas policy is server-defined and requires team-security review.- pattern-not: $RESPONSE["Content-Security-Policy"] = _canvas_sandbox_document_csp(...)+ - pattern-not: $RESPONSE["Content-Security-Policy"] = _task_html_artifact_preview_csp(...)- pattern-not: $RESPONSE["Content-Security-Policy"] = _public_survey_csp(...)- pattern-not: >-$RESPONSE["Content-Security-Policy"] = "sandbox; default-src 'none'; img-src https:diff --git a/docs/internal/canvas-delivery.md b/docs/internal/canvas-delivery.mdindex 4db2e2f7772a..d8cde32db1a2 100644--- a/docs/internal/canvas-delivery.md+++ b/docs/internal/canvas-delivery.md@@ -43,6 +43,50 @@ The header permits the fixed compiler and module CDNs, but blocks external imageUse a built canvas with declared network origins for external images.Changes to this server policy and its tests require security review.+Task HTML previews use the same artifact origin.+The task API checks read access before issuing a short-lived URL for one artifact version.+For a living artifact version, the API also checks analytics access for every run of the task, because any run of the task can write a version.+Task preview responses use `Cache-Control: no-store`, including when the CDN handles `/canvas-artifacts/`.++The artifact host does not serve the file as the document.+It serves a shim document with no script, and the shim holds the file in an inner frame through the `srcdoc` attribute, HTML-escaped.+The shim's CSP applies to both frames, because a `srcdoc` document inherits the policy of its parent.+That policy blocks network APIs and external resources, runs in an opaque-origin sandbox, and sets `frame-src 'none'`.+The `frame-src` of a parent applies to every navigation of its child frame, including a navigation that the child starts itself.+So the browser refuses `location = ...`, a meta refresh, a link click, and a form submission before the request leaves.+A `srcdoc` frame is not subject to `frame-src`, so the file still loads.+This holds in Chromium, Firefox, and WebKit.++A preview opens with scripts off.+The CSP sandbox has no `allow-scripts` flag, and the inner frame has an empty `sandbox` attribute, so the file cannot run code.+The user must select "Run scripts" to get a URL with a CSP that allows inline JavaScript.++CSP does not cover every channel, such as WebRTC, DNS prefetch and preconnect.+A static preview renames every `<link>` and `<meta>` tag of the file to an unknown element, and adds `x-dns-prefetch-control: off` after its doctype, so the file cannot ask the browser for a DNS lookup or a connection.+For this reason, the API gives a script URL only when whoever wrote that artifact version had full network access.+The server records this on the manifest entry or the living artifact version at write time, from the authenticated writer, never from the request body.+A sandbox agent gets the network access of the run that its token belongs to.+A person, through a session, a personal API key, or a PostHog Desktop grant, gets full access.+Any other OAuth application gets no access.+An edit records full access only when its base version has it.+An upload checks every earlier file with the same name in the run, and a finalized upload also checks the version it names in `base_artifact_id`. So a client that does not send `base_artifact_id` still cannot unlock scripts.+The stored bytes of the base, or of the latest file with that name, must also still match its hash, so an edit of replaced bytes stays static.+A living artifact edit checks the current version.+A living artifact copied from a run file checks that file, and the copied bytes must still match its hash.+A file from a Slack thread, a file written before this record existed, or a file from any other write path has no record and stays static.+Because the record belongs to the artifact, it does not matter which run or task holds the file, so an agent cannot get scripts by writing into another run or task.+A run with no sandbox environment counts as full access.+A run whose environment is deleted, is not accessible, or changed after the run started does not count.+A caller cannot change `sandbox_environment_id` in run state, so an agent cannot remove its own restriction.+The record also keeps a SHA-256 hash of the HTML bytes that the writer saved.+A stored living artifact version keeps the same hash in its version record.+A presigned upload form stays valid after finalize and can still replace the object, so the preview runs scripts only when the bytes it serves still match that hash.+Otherwise it serves the file with scripts off.++The task preview has no PostHog credentials or API bridge.+Do not put secrets in an HTML artifact that runs code.+Self-hosted deployments need `CANVAS_ARTIFACT_ORIGIN` for the web preview in production; the app origin is used only in development and tests.+## Cache policyShared caching is off by default:diff --git a/posthog/settings/data_stores.py b/posthog/settings/data_stores.pyindex cd4909aba5c8..fd7d2e2e77d2 100644--- a/posthog/settings/data_stores.py+++ b/posthog/settings/data_stores.py@@ -731,6 +731,11 @@ CACHES["ingress_dedup"] = {"LOCATION": REDIS_URL,}+CACHES["task_artifact_preview"] = {+ **CACHES["default"],+ "LOCATION": REDIS_URL,+}+# Dedicated cache for the feature flags service (if configured)# Django only writes to this cache (never reads), so no reader URL neededif FLAGS_REDIS_URL:@@ -796,6 +801,7 @@ if TEST:CACHES["organization_access"] = CACHES["default"]CACHES["cohort_dependencies"] = CACHES["default"]CACHES["ingress_dedup"] = CACHES["default"]+ CACHES["task_artifact_preview"] = CACHES["default"]# Cache timeout for materialized columns metadata (in seconds)MATERIALIZED_COLUMNS_CACHE_TIMEOUT: int = get_from_env("MATERIALIZED_COLUMNS_CACHE_TIMEOUT", 900, type_cast=int)diff --git a/posthog/urls.py b/posthog/urls.pyindex 1cf2f2c7916b..47b0daa8ca94 100644--- a/posthog/urls.py+++ b/posthog/urls.py@@ -73,6 +73,7 @@ from products.slack_app.backend.views import (from products.streamlit_apps.backend.presentation.bridge_views import StreamlitBridgeViewfrom products.surveys.backend.api.survey import public_survey_pagefrom products.tasks.backend.facade.agent_proxy import agent_proxy_callback+from products.tasks.backend.presentation.views.artifact_preview import task_artifact_previewfrom products.tasks.backend.presentation.views.gateway_generation_requests import gateway_generation_requestfrom products.warehouse_sources.backend.presentation.views.public_source_configs import PublicSourceConfigViewSetfrom products.workflows.backend.presentation.views import hog_flow@@ -355,6 +356,11 @@ urlpatterns = [canvas_sandbox_document,name="canvas-sandbox-document",),+ re_path(+ r"^canvas-artifacts/task-preview/(?P<token>[A-Za-z0-9_-]+)/index\.html$",+ task_artifact_preview,+ name="task-artifact-preview",+ ),re_path(r"^canvas-artifacts/(?P<token>[^/]+)/(?P<artifact_path>.+)$", canvas_artifact, name="canvas-artifact"),# Preserve the host and query when redirecting the legacy signup URL.opt_slash_path("sign-up", RedirectView.as_view(url="/signup", permanent=True, query_string=True)),diff --git a/products/canvas/backend/artifacts.py b/products/canvas/backend/artifacts.pyindex 4929c3c0cb55..30dbde49b308 100644--- a/products/canvas/backend/artifacts.py+++ b/products/canvas/backend/artifacts.py@@ -84,7 +84,7 @@ def create_canvas_artifact_token(build: CanvasBuild) -> str | None:)-def _artifact_origin() -> str:+def artifact_delivery_origin() -> str:"""The origin artifacts are linked from and served on.DEBUG/TEST with no CANVAS_ARTIFACT_ORIGIN falls back to the application@@ -102,7 +102,7 @@ def create_canvas_artifact_url(build: CanvasBuild, artifact_path: str) -> str |token = create_canvas_artifact_token(build)if token is None:return None- return f"{_artifact_origin()}/canvas-artifacts/{token}/{artifact_path}"+ return f"{artifact_delivery_origin()}/canvas-artifacts/{token}/{artifact_path}"def _read_token(token: str) -> dict[str, Any]:@@ -117,9 +117,9 @@ def _read_token(token: str) -> dict[str, Any]:raise Http404-def _require_artifact_host(request: HttpRequest) -> None:+def require_artifact_host(host: str) -> None:configured_host = _configured_artifact_host()- if settings.CANVAS_ARTIFACT_ORIGIN and (configured_host is None or request.get_host().lower() != configured_host):+ if settings.CANVAS_ARTIFACT_ORIGIN and (configured_host is None or host.lower() != configured_host):raise Http404@@ -183,7 +183,7 @@ def create_canvas_sandbox_document_url() -> str | None:_publish_sandbox_document(document)except ObjectStorageError:return None- return f"{_artifact_origin()}/canvas-artifacts/sandbox/{document.content_hash}/index.html"+ return f"{artifact_delivery_origin()}/canvas-artifacts/sandbox/{document.content_hash}/index.html"@xframe_options_exempt@@ -194,7 +194,7 @@ def canvas_sandbox_document(request: HttpRequest, content_hash: str) -> HttpRespwhich refuses the CDNs the document transpiles and resolves imports from. It holds nocredentials: the canvas code arrives later by postMessage."""- _require_artifact_host(request)+ require_artifact_host(request.get_host())document = _sandbox_document()if not re.fullmatch(r"[0-9a-f]{64}", content_hash):raise Http404@@ -215,7 +215,7 @@ def canvas_sandbox_document(request: HttpRequest, content_hash: str) -> HttpResp@xframe_options_exemptdef canvas_artifact(request: HttpRequest, token: str, artifact_path: str) -> HttpResponse:- _require_artifact_host(request)+ require_artifact_host(request.get_host())claims = _read_token(token)token_expires_at = (claims["bucket"] + 2) * ARTIFACT_TOKEN_BUCKET_SECONDSteam_id = claims.get("team_id")diff --git a/products/canvas/backend/facade/api.py b/products/canvas/backend/facade/api.pyindex 8fd8a1bce890..10a5ac0c6e74 100644--- a/products/canvas/backend/facade/api.py+++ b/products/canvas/backend/facade/api.py@@ -8,9 +8,12 @@ from django.http import Http404, HttpRequestfrom products.canvas.backend.actions import canvas_actions_disabled as canvas_actions_disabledfrom products.canvas.backend.artifacts import (+ ARTIFACT_PERMISSIONS_POLICY as ARTIFACT_PERMISSIONS_POLICY,+ artifact_delivery_origin as artifact_delivery_origin,canvas_artifact as _canvas_artifact,canvas_sandbox_document as _canvas_sandbox_document,create_canvas_sandbox_document_url as create_canvas_sandbox_document_url,+ require_artifact_host as require_artifact_host,)from products.canvas.backend.connectors import (call_connector_tool as call_connector_tool,diff --git a/products/posthog_ai/frontend/scenes/TaskTracker/TaskRunArtifacts.stories.tsx b/products/posthog_ai/frontend/scenes/TaskTracker/TaskRunArtifacts.stories.tsxindex 4b740a573019..823fa5b82b4c 100644--- a/products/posthog_ai/frontend/scenes/TaskTracker/TaskRunArtifacts.stories.tsx+++ b/products/posthog_ai/frontend/scenes/TaskTracker/TaskRunArtifacts.stories.tsx@@ -119,8 +119,10 @@ const SUMMARY_HTML = `<!doctype html><div class="step"><span>Details</span><div class="track"><div class="bar" style="width: 35%"></div></div><span class="value">35%</span></div><div class="step"><span>Trial started</span><div class="track"><div class="bar" style="width: 30%"></div></div><span class="value">30%</span></div><div class="note">The plan picker step drops from 62% to 44% against the week before.</div>+ <button id="preview-action">Run chart action</button><img src="https://example.com/html-pixel.png" alt="" width="1" height="1" /></main>+<script>document.getElementById('preview-action').addEventListener('click', function () { this.textContent = 'Chart action ran' })</script></body></html>`@@ -398,6 +400,10 @@ function taskMocks([`/api/projects/:team_id/tasks/${TASK_ID}/runs/${RUN_ID}/logs`]: () => new HttpResponse(logs),[`/api/projects/:team_id/tasks/${TASK_ID}/runs/:run_id/artifacts/artifact-chart/download/`]: () =>new HttpResponse(CHART_SVG, { headers: { 'Content-Type': 'image/svg+xml' } }),+ [`/api/projects/:team_id/tasks/${TASK_ID}/runs/:run_id/artifacts/:artifact_id/preview/`]: {+ url: `data:text/html;charset=utf-8,${encodeURIComponent(SUMMARY_HTML)}`,+ scripts_available: true,+ },'/api/projects/:team_id/task_channels/': [],'/api/projects/:team_id/integrations/': { results: [] },'/api/environments/:team_id/conversations/': { results: [], next: null },diff --git a/products/posthog_ai/frontend/scenes/TaskTracker/artifactHtml.test.ts b/products/posthog_ai/frontend/scenes/TaskTracker/artifactHtml.test.tsdeleted file mode 100644index 237ae0c7d598..000000000000--- a/products/posthog_ai/frontend/scenes/TaskTracker/artifactHtml.test.ts+++ /dev/null@@ -1,19 +0,0 @@-import { ARTIFACT_HTML_CSP, withStrictCsp } from './artifactHtml'--describe('withStrictCsp', () => {- test.each([- [- 'a full document',- '<!doctype html><html><head><title>x</title></head><body><img src="https://example.com/a.png"></body></html>',- ],- ['a head tag inside a comment', '<!-- <head> --><img src="https://example.com/a.png">'],- ['a head tag inside a title', '<title><head></title><img src="https://example.com/a.png">'],- ['a head tag inside a script', '<script>"<head>"</script><img src="https://example.com/a.png">'],- ['a fragment', '<p>Hello</p><img src="https://example.com/a.png">'],- ])('the policy is the first element of the parsed head for %s', (_, html) => {- const doc = new DOMParser().parseFromString(withStrictCsp(html), 'text/html')- const first = doc.head.firstElementChild- expect(first?.getAttribute('http-equiv')).toBe('Content-Security-Policy')- expect(first?.getAttribute('content')).toBe(ARTIFACT_HTML_CSP)- })-})diff --git a/products/posthog_ai/frontend/scenes/TaskTracker/artifactHtml.ts b/products/posthog_ai/frontend/scenes/TaskTracker/artifactHtml.tsdeleted file mode 100644index 140b461a5363..000000000000--- a/products/posthog_ai/frontend/scenes/TaskTracker/artifactHtml.ts+++ /dev/null@@ -1,12 +0,0 @@-// A sandbox stops scripts but not subresources, so the policy keeps the page from fetching anything.-export const ARTIFACT_HTML_CSP =- "default-src 'none'; style-src 'unsafe-inline'; img-src data:; font-src data:; form-action 'none'"--/**- * Wraps untrusted HTML so the policy is the first thing the parser reads. The policy never goes inside the- * untrusted text: a `<head>` in a comment, a title or a script would put it where the browser ignores it.- * A second doctype, `html` or `head` later in the text is dropped by the parser, so the trusted head stays.- */-export function withStrictCsp(html: string): string {- return `<!doctype html><html><head><meta http-equiv="Content-Security-Policy" content="${ARTIFACT_HTML_CSP}"></head><body>${html}</body></html>`-}diff --git a/products/posthog_ai/frontend/scenes/TaskTracker/components/TaskRunArtifacts.tsx b/products/posthog_ai/frontend/scenes/TaskTracker/components/TaskRunArtifacts.tsxindex f16890270dc8..54dfe6eacc9c 100644--- a/products/posthog_ai/frontend/scenes/TaskTracker/components/TaskRunArtifacts.tsx+++ b/products/posthog_ai/frontend/scenes/TaskTracker/components/TaskRunArtifacts.tsx@@ -12,7 +12,6 @@ import {IconEllipsis,IconExpand45,IconExternal,- IconLock,IconPencil,IconShare,IconHide,@@ -79,7 +78,6 @@ import { TodaySheetMenu } from '~/layout/today/TodaySheetMenu'import { taskCommentContextsLogic } from '../../../logics/taskCommentContextsLogic'import { isCommentableArtifact, regionAnchorAt, supportsSelectionComments } from '../artifactComments'-import { withStrictCsp } from '../artifactHtml'import { TaskArtifactCommentsLogicProps, taskArtifactCommentsLogic } from '../taskArtifactCommentsLogic'import {ArtifactFile,@@ -97,7 +95,12 @@ import {objectPageUrl,postHogObjectRef,} from '../taskRunArtifacts'-import { FullPageSource, artifactDownloadUrl, taskRunArtifactsLogic } from '../taskRunArtifactsLogic'+import {+ ArtifactHtmlPreview,+ FullPageSource,+ artifactDownloadUrl,+ taskRunArtifactsLogic,+} from '../taskRunArtifactsLogic'import { ArtifactCommentActions } from './ArtifactCommentActions'import { ArtifactCommentsButton, ArtifactCommentsPage } from './ArtifactCommentsPage'import { ArtifactEditor } from './ArtifactEditor'@@ -198,22 +201,74 @@ function IconAction({)}-/**- * Agent-written HTML is untrusted. An empty `sandbox` gives the document an opaque origin with scripts,- * forms, popups and top navigation all off, so it cannot reach the app's cookies, storage or DOM.- */-function SandboxedHtmlFrame({ html, name }: { html: string; name: string }): JSX.Element {+function SandboxedHtmlFrame({ url, name, scripts }: { url: string; name: string; scripts: boolean }): JSX.Element {return (<iframeclassName="size-full border-0 bg-white"- sandbox=""+ sandbox={scripts ? 'allow-scripts' : ''}referrerPolicy="no-referrer"- srcDoc={withStrictCsp(html)}+ src={url}title={`Preview of ${name}`}/>)}+function HtmlScriptsBar({+ preview,+ loading,+ onRunScripts,+ onStopScripts,+ onReload,+}: {+ preview: ArtifactHtmlPreview+ loading: boolean+ onRunScripts: () => void+ onStopScripts: () => void+ onReload: () => void+}): JSX.Element {+ const message = preview.scriptsError+ ? preview.scriptsError+ : preview.scriptsEnabled+ ? 'Scripts are on. This page can send its content and what you type in it to other sites.'+ : preview.scriptsAvailable+ ? 'Scripts are off. Run them only if you trust this file. A page with scripts can send its content to other sites.'+ : 'Scripts are off. Only files made with full network access can run scripts.'+ return (+ <div+ className={cn(+ 'flex min-h-9 shrink-0 items-center gap-2 border-b border-border px-3 py-1.5',+ preview.scriptsEnabled ? 'bg-warning text-warning-foreground' : 'bg-background'+ )}+ >+ <Text size="xs" render={<span />} className="min-w-0">+ {message}+ </Text>+ <Button+ size="xs"+ variant="outline"+ className="ml-auto shrink-0"+ disabled={loading}+ onClick={onReload}+ data-attr="task-artifact-reload-preview"+ >+ Reload+ </Button>+ {(preview.scriptsEnabled || preview.scriptsAvailable) && (+ <Button+ size="xs"+ variant="outline"+ className="shrink-0"+ loading={loading}+ onClick={preview.scriptsEnabled ? onStopScripts : onRunScripts}+ data-attr={preview.scriptsEnabled ? 'task-artifact-stop-scripts' : 'task-artifact-run-scripts'}+ >+ {preview.scriptsEnabled ? 'Turn off scripts' : 'Run scripts'}+ </Button>+ )}+ </div>+ )+}+function CsvPreview({ text }: { text: string }): JSX.Element {const { header, rows, truncated } = useMemo(() => {const [first = [], ...rest] = parseCsv(text)@@ -413,11 +468,14 @@ function ArtifactPreview({ taskId, mode }: { taskId: string; mode: PreviewMode }currentProjectId,artifactTextLoading,todayPhone,+ htmlPreview,+ htmlPreviewLoading,} = useValues(taskRunArtifactsLogic({ taskId }))- const { ensureSelectedText, loadArtifactText } = useActions(taskRunArtifactsLogic({ taskId }))+ const { ensureSelectedText, fetchHtmlPreview, loadArtifactText, loadHtmlPreview, runHtmlPreviewScripts } =+ useActions(taskRunArtifactsLogic({ taskId }))useEffect(() => {- ensureSelectedText()- }, [selectedArtifact?.id, selectedRun?.id, currentProjectId, ensureSelectedText])+ ensureSelectedText(mode === 'source')+ }, [selectedArtifact?.id, selectedRun?.id, currentProjectId, mode, ensureSelectedText])if (!selectedArtifact || !selectedKind) {return null}@@ -463,6 +521,60 @@ function ArtifactPreview({ taskId, mode }: { taskId: string; mode: PreviewMode }</Empty>)}+ if (selectedKind === 'html' && mode === 'rendered') {+ if (+ !htmlPreview ||+ htmlPreview.artifactId !== selectedArtifact.id ||+ (htmlPreviewLoading && !htmlPreview.url)+ ) {+ return (+ <div className="flex h-full items-center justify-center">+ <Spinner />+ </div>+ )+ }+ if (!htmlPreview.url) {+ return (+ <Empty className="h-full">+ <EmptyHeader>+ <EmptyTitle>This HTML preview didn't load</EmptyTitle>+ <EmptyDescription>{htmlPreview.error}</EmptyDescription>+ </EmptyHeader>+ <EmptyContent>+ <Button+ variant="outline"+ loading={htmlPreviewLoading}+ onClick={() => loadHtmlPreview(selectedArtifact)}+ data-attr="task-artifact-retry-preview"+ >+ Try again+ </Button>+ </EmptyContent>+ </Empty>+ )+ }+ return (+ <div className="flex h-full flex-col">+ <HtmlScriptsBar+ preview={htmlPreview}+ loading={htmlPreviewLoading}+ onRunScripts={() => runHtmlPreviewScripts(selectedArtifact)}+ onStopScripts={() => loadHtmlPreview(selectedArtifact)}+ onReload={() =>+ fetchHtmlPreview({ artifact: selectedArtifact, scripts: htmlPreview.scriptsEnabled })+ }+ />+ <div className="min-h-0 flex-1">+ <SandboxedHtmlFrame+ key={htmlPreview.url}+ url={htmlPreview.url}+ name={selectedArtifact.name}+ scripts={htmlPreview.scriptsEnabled}+ />+ </div>+ </div>+ )+ }if (!selectedText) {return selectedKind === 'html' ? (<div className="flex h-full items-center justify-center">@@ -507,9 +619,6 @@ function ArtifactPreview({ taskId, mode }: { taskId: string; mode: PreviewMode }if (mode === 'source') {return <SourceView text={selectedText.text} />}- if (selectedKind === 'html') {- return <SandboxedHtmlFrame html={selectedText.text} name={selectedArtifact.name} />- }if (selectedKind === 'csv') {return <CsvPreview text={selectedText.text} />}@@ -812,18 +921,6 @@ function ArtifactToolbar({</TooltipContent></Tooltip>{versioned && selectedFile && <VersionSelect taskId={taskId} file={selectedFile} />}- {kind === 'html' && (- <Tooltip>- <TooltipTrigger render={<Badge className="shrink-0" />}>- <IconLock />- Sandboxed- </TooltipTrigger>- <TooltipContent>- This page runs with scripts off and no network. It can't read your PostHog data, cookies or- session.- </TooltipContent>- </Tooltip>- )}<div className="ml-auto flex shrink-0 items-center gap-1">{hasRenderedForm && (<ToggleGroupdiff --git a/products/posthog_ai/frontend/scenes/TaskTracker/taskRunArtifacts.test.ts b/products/posthog_ai/frontend/scenes/TaskTracker/taskRunArtifacts.test.tsindex be10084eea3e..04cc0dbf0ea9 100644--- a/products/posthog_ai/frontend/scenes/TaskTracker/taskRunArtifacts.test.ts+++ b/products/posthog_ai/frontend/scenes/TaskTracker/taskRunArtifacts.test.ts@@ -318,6 +318,13 @@ describe('taskRunArtifacts', () => {'video/mp4','video',],+ [+ 'a stored Slack file HTML previews as HTML',+ { storage_path: 'tasks/doc.v1.html' },+ 'interactive.html',+ 'text/html',+ 'html',+ ],['a stored Slack file CSV has no inline preview',{ storage_path: 'tasks/doc.v1.csv' },diff --git a/products/posthog_ai/frontend/scenes/TaskTracker/taskRunArtifacts.ts b/products/posthog_ai/frontend/scenes/TaskTracker/taskRunArtifacts.tsindex 075cdfb71ce3..369953aeefcd 100644--- a/products/posthog_ai/frontend/scenes/TaskTracker/taskRunArtifacts.ts+++ b/products/posthog_ai/frontend/scenes/TaskTracker/taskRunArtifacts.ts@@ -73,12 +73,14 @@ export function artifactPreviewKind(artifact: TaskRunArtifactResponseApi & { living?: LivingVersion }): ArtifactPreviewKind {if (artifact.living && artifact.living.text === null) {- if (!artifact.living.stored || (artifact.size ?? 0) > LIVING_PREVIEW_MAX_BYTES) {+ if (!artifact.living.stored) {return 'none'}- // A stored file plays in an `img` or a `video` from its URL. Text needs a read of the body, so it downloads.const kind = fileKind(artifact)- return kind === 'image' || kind === 'video' ? kind : 'none'+ return (artifact.size ?? 0) <= LIVING_PREVIEW_MAX_BYTES &&+ (kind === 'image' || kind === 'video' || kind === 'html')+ ? kind+ : 'none'}if (artifact.type === 'reference') {return 'reference'diff --git a/products/posthog_ai/frontend/scenes/TaskTracker/taskRunArtifactsLogic.test.ts b/products/posthog_ai/frontend/scenes/TaskTracker/taskRunArtifactsLogic.test.tsindex 39771a7aebcd..e6c3609f1698 100644--- a/products/posthog_ai/frontend/scenes/TaskTracker/taskRunArtifactsLogic.test.ts+++ b/products/posthog_ai/frontend/scenes/TaskTracker/taskRunArtifactsLogic.test.ts@@ -43,6 +43,18 @@ describe('taskRunArtifactsLogic', () => {if (url.includes('/artifacts/download/')) {return Promise.resolve(new Response('# Report'))}+ if (url.includes('/artifacts/') && url.includes('/preview/')) {+ return Promise.resolve(+ new Response(+ JSON.stringify({+ url: 'https://usercontent.example/canvas-artifacts/task-preview/token/index.html',+ }),+ {+ headers: { 'Content-Type': 'application/json' },+ }+ )+ )+ }const payload = /\/runs\/(\?.*)?$/.test(url)? { results: runArtifacts.length ? [{ id: RUN_ID }] : [] }: url.includes('/living_artifacts/')@@ -131,6 +143,143 @@ describe('taskRunArtifactsLogic', () => {await expectLogic(logic).toMatchValues({ activeTab: 'conversation', selectedFileKey: null })})+ it('downloads HTML source only when an edit starts from the preview', async () => {+ runArtifacts = [+ {+ id: 'html-1',+ name: 'interactive.html',+ type: 'output',+ source: 'agent_output',+ content_type: 'text/html',+ storage_path: 'tasks/artifacts/html-1',+ uploaded_at: '2026-09-28T18:00:00Z',+ },+ ]+ const logic = taskRunArtifactsLogic({ taskId: TASK_ID })+ logic.mount()+ await expectLogic(logic, () => logic.actions.setActiveTab('artifacts')).toFinishAllListeners()+ await expectLogic(logic, () => logic.actions.ensureSelectedText()).toFinishAllListeners()+ expect(global.fetch).not.toHaveBeenCalledWith(+ expect.stringContaining('/artifacts/download/'),+ expect.anything()+ )++ const fetch = global.fetch+ let finishDownload: (response: Response) => void = () => {}+ global.fetch = jest.fn((input: RequestInfo | URL, init?: RequestInit) =>+ String(input).includes('/artifacts/download/')+ ? new Promise<Response>((resolve) => (finishDownload = resolve))+ : fetch(input, init)+ )+ logic.actions.startEditing()+ logic.actions.startEditing()+ expect(logic.values.editDisabledReason).toBe('The file is loading')+ expect(+ jest.mocked(global.fetch).mock.calls.filter(([input]) => String(input).includes('/artifacts/download/'))+ ).toHaveLength(1)++ await expectLogic(logic, () => finishDownload(new Response('# Report'))).toFinishAllListeners()++ expect(logic.values.editSession).toMatchObject({ baseArtifactId: 'html-1', original: '# Report' })+ })++ it('loads the selected HTML preview once and retries failures only on request', async () => {+ runArtifacts = ['interactive.html', 'second.html'].map((name, index) => ({+ id: `html-${index + 1}`,+ name,+ type: 'output',+ source: 'agent_output',+ content_type: 'text/html',+ storage_path: `tasks/artifacts/html-${index + 1}`,+ uploaded_at: '2026-09-28T18:00:00Z',+ }))+ const fetch = global.fetch+ const pending: Array<(response: Response) => void> = []+ global.fetch = jest.fn((input: RequestInfo | URL, init?: RequestInit) =>+ String(input).includes('/preview/')+ ? new Promise<Response>((resolve) => pending.push(resolve))+ : fetch(input, init)+ )+ const respond = (index: number, path: string, status = 200): void => {+ pending[index](+ new Response(+ JSON.stringify({+ url: `https://usercontent.example/canvas-artifacts/task-preview/${path}/index.html`,+ scripts_available: true,+ }),+ { status, headers: { 'Content-Type': 'application/json' } }+ )+ )+ }+ const logic = taskRunArtifactsLogic({ taskId: TASK_ID })+ logic.mount()+ await expectLogic(logic, () => logic.actions.setActiveTab('artifacts')).toFinishAllListeners()+ await expectLogic(logic, () => logic.actions.ensureSelectedText()).toMatchValues({ htmlPreviewLoading: true })+ logic.actions.ensureSelectedText()+ expect(pending).toHaveLength(1)+ expect(global.fetch).toHaveBeenCalledWith(+ expect.stringContaining(`/tasks/${TASK_ID}/runs/${RUN_ID}/artifacts/html-1/preview/`),+ expect.anything()+ )++ logic.actions.selectArtifact('second.html')+ logic.actions.ensureSelectedText()+ expect(pending).toHaveLength(2)+ await expectLogic(logic, () => respond(1, 'second'))+ .toDispatchActions(['fetchHtmlPreviewSuccess'])+ .toMatchValues({+ htmlPreviewLoading: false,+ htmlPreview: expect.objectContaining({ artifactId: 'html-2' }),+ })+ respond(0, 'first')+ await expectLogic(logic).toFinishAllListeners()+ expect(logic.values.htmlPreview?.artifactId).toBe('html-2')+ expect(logic.values.htmlPreview?.url).toContain('/task-preview/second/')++ const secondArtifact = logic.values.selectedArtifact as RunArtifact+ logic.actions.loadHtmlPreview(secondArtifact)+ await expectLogic(logic, () => respond(2, 'failed', 503))+ .toDispatchActions(['fetchHtmlPreviewSuccess'])+ .toMatchValues({+ htmlPreviewLoading: false,+ htmlPreview: expect.objectContaining({ url: null, error: expect.any(String) }),+ })+ logic.actions.ensureSelectedText()+ expect(pending).toHaveLength(3)+ logic.actions.loadHtmlPreview(secondArtifact)+ await expectLogic(logic, () => respond(3, 'retry')).toFinishAllListeners()+ expect(logic.values.htmlPreview?.url).toContain('/task-preview/retry/')++ logic.actions.runHtmlPreviewScripts(secondArtifact)+ expect(global.fetch).toHaveBeenLastCalledWith(expect.stringContaining('scripts=true'), expect.anything())+ await expectLogic(logic, () => respond(4, 'denied', 403)).toFinishAllListeners()+ expect(logic.values.htmlPreview).toMatchObject({+ url: expect.stringContaining('/task-preview/retry/'),+ scriptsEnabled: false,+ scriptsError: expect.any(String),+ })++ logic.actions.runHtmlPreviewScripts(secondArtifact)+ await expectLogic(logic, () => respond(5, 'scripts')).toFinishAllListeners()+ expect(logic.values.htmlPreview).toMatchObject({+ scriptsEnabled: true,+ scriptsAvailable: true,+ scriptsError: null,+ })++ logic.actions.runHtmlPreviewScripts(secondArtifact)+ logic.actions.selectArtifact('interactive.html')+ logic.actions.ensureSelectedText()+ expect(pending).toHaveLength(8)+ respond(7, 'first-again')+ await expectLogic(logic, () => respond(6, 'late-scripts')).toFinishAllListeners()+ expect(logic.values.htmlPreview).toMatchObject({+ artifactId: 'html-1',+ url: expect.stringContaining('/task-preview/first-again/'),+ })+ expect(logic.values.htmlPreviewLoading).toBe(false)+ })+it.each([['a stored Slack file version streams from its version URL',@@ -151,6 +300,32 @@ describe('taskRunArtifactsLogic', () => {expect(artifactDownloadUrl(1, TASK_ID, version)).toBe(expected)})+ it('keeps a crafted artifact id inside one preview path segment', async () => {+ const craftedId = 'html-1/../html-2/preview/?scripts=true#'+ runArtifacts = [+ {+ id: craftedId,+ name: 'crafted.html',+ type: 'output',+ source: 'agent_output',+ content_type: 'text/html',+ storage_path: 'tasks/artifacts/crafted',+ uploaded_at: '2026-09-28T18:00:00Z',+ },+ ]+ const logic = taskRunArtifactsLogic({ taskId: TASK_ID })+ logic.mount()+ await expectLogic(logic, () => logic.actions.setActiveTab('artifacts')).toFinishAllListeners()+ await expectLogic(logic, () => logic.actions.ensureSelectedText()).toFinishAllListeners()++ const previewUrl = jest+ .mocked(global.fetch)+ .mock.calls.map(([input]) => String(input))+ .find((url) => url.includes('/preview/'))+ expect(previewUrl).toContain(`/artifacts/${encodeURIComponent(craftedId)}/preview/`)+ expect(previewUrl).not.toContain('scripts=true')+ })+it('asks before a save replaces a version the agent wrote during the edit', async () => {runArtifacts = [reportVersion('report-v1', '2026-09-28T18:00:00Z')]jest.mocked(uploadRunOutputVersion).mockResolvedValue('report-v3')@@ -175,6 +350,7 @@ describe('taskRunArtifactsLogic', () => {name: 'report.md',content: '# Report, edited',contentType: 'text/markdown',+ baseArtifactId: 'report-v1',})expect(logic.values).toMatchObject({ isEditing: false, editConflict: null })})diff --git a/products/posthog_ai/frontend/scenes/TaskTracker/taskRunArtifactsLogic.ts b/products/posthog_ai/frontend/scenes/TaskTracker/taskRunArtifactsLogic.tsindex 4347a8be26b2..fe1c0a950c8d 100644--- a/products/posthog_ai/frontend/scenes/TaskTracker/taskRunArtifactsLogic.ts+++ b/products/posthog_ai/frontend/scenes/TaskTracker/taskRunArtifactsLogic.ts@@ -27,6 +27,7 @@ import { todayShellLogic } from '~/layout/today/todayShellLogic'import {getTasksRunsArtifactsDownloadCreateUrl,getTasksRunsArtifactsDownloadRetrieveUrl,+ tasksRunsArtifactsPreviewRetrieve,tasksRunsArtifactsDismissCreate,getTasksRunsLivingArtifactsVersionContentUrl,tasksRunsLivingArtifactsList,@@ -74,6 +75,16 @@ export interface ArtifactText {error: string | null}+export interface ArtifactHtmlPreview {+ artifactId: string+ url: string | null+ error: string | null+ expiresAt: number+ scriptsEnabled: boolean+ scriptsAvailable: boolean+ scriptsError: string | null+}+/** The file version an edit started from, and the text it had then. */export interface ArtifactEditSession {fileKey: string@@ -122,6 +133,8 @@ export interface taskRunArtifactsLogicValues {editSaving: booleaneditSession: ArtifactEditSession | nullfiles: ArtifactFile[]+ htmlPreview: ArtifactHtmlPreview | null+ htmlPreviewLoading: booleanisEditing: booleanlivingArtifacts: TaskRunLivingArtifactResponseApi[]livingArtifactsLoading: boolean@@ -171,8 +184,23 @@ export interface taskRunArtifactsLogicActions {editSaved: (artifactId: string) => {artifactId: string}- ensureSelectedText: () => {- value: true+ ensureSelectedText: (source?: boolean) => {+ source: boolean+ }+ fetchHtmlPreview: ({ artifact, scripts }: HtmlPreviewRequest) => HtmlPreviewRequest+ fetchHtmlPreviewFailure: (+ error: string,+ errorObject?: any+ ) => {+ error: string+ errorObject?: any+ }+ fetchHtmlPreviewSuccess: (+ htmlPreview: ArtifactHtmlPreview,+ payload?: HtmlPreviewRequest+ ) => {+ htmlPreview: ArtifactHtmlPreview+ payload?: HtmlPreviewRequest}loadArtifactMedia: (artifact: RunArtifact) => RunArtifactloadArtifactMediaFailure: (@@ -219,6 +247,7 @@ export interface taskRunArtifactsLogicActions {chainRuns: TaskRunDetailDTOApi[]payload?: string[]}+ loadHtmlPreview: (artifact: RunArtifact) => RunArtifactloadLivingArtifacts: (runId: string) => stringloadLivingArtifactsFailure: (error: string,@@ -256,6 +285,7 @@ export interface taskRunArtifactsLogicActions {restoreFile: (file: ArtifactFile) => {file: ArtifactFile}+ runHtmlPreviewScripts: (artifact: RunArtifact) => RunArtifactsaveEdit: () => {value: true}@@ -343,7 +373,8 @@ export interface taskRunArtifactsLogicMeta {editDisabledReason: (selectedEditableKind: EditableArtifactKind | null,selectedVersionIndex: number,- selectedText: ArtifactText | null+ selectedText: ArtifactText | null,+ artifactTextLoading: boolean) => string | nullselectedText: (selectedArtifact: RunArtifact | null,@@ -359,6 +390,52 @@ export type taskRunArtifactsLogicType = MakeLogicType<taskRunArtifactsLogicMeta>+function emptyHtmlPreview(artifactId: string): ArtifactHtmlPreview {+ return {+ artifactId,+ url: null,+ error: null,+ expiresAt: 0,+ scriptsEnabled: false,+ scriptsAvailable: false,+ scriptsError: null,+ }+}++interface HtmlPreviewRequest {+ artifact: RunArtifact+ scripts: boolean+}++async function requestHtmlPreview(+ projectId: number | null,+ taskId: string,+ artifact: RunArtifact,+ scripts: boolean+): Promise<ArtifactHtmlPreview> {+ if (projectId === null || !artifact.id) {+ return { ...emptyHtmlPreview(artifact.id ?? ''), error: 'Preview is unavailable.' }+ }+ try {+ const result = await tasksRunsArtifactsPreviewRetrieve(+ String(projectId),+ taskId,+ artifact.runId,+ encodeURIComponent(artifact.living?.artifactId ?? artifact.id),+ { ...(artifact.living ? { version: artifact.living.version } : {}), ...(scripts ? { scripts } : {}) }+ )+ return {+ ...emptyHtmlPreview(artifact.id),+ url: result.url,+ expiresAt: Date.now() + 4 * 60 * 1000,+ scriptsEnabled: scripts,+ scriptsAvailable: result.scripts_available,+ }+ } catch {+ return { ...emptyHtmlPreview(artifact.id), error: 'This HTML preview did not load. Try again.' }+ }+}+// A long-lived task can have many runs. Older runs past this cap keep their files out of the list.const MAX_CHAIN_RUNS = 20@@ -439,7 +516,9 @@ export const taskRunArtifactsLogic = kea<taskRunArtifactsLogicType>([selectVersion: (artifactId: string | null) => ({ artifactId }),stepArtifact: (delta: number) => ({ delta }),downloadArtifact: (artifact: RunArtifact) => ({ artifact }),- ensureSelectedText: true,+ ensureSelectedText: (source: boolean = false) => ({ source }),+ loadHtmlPreview: (artifact: RunArtifact) => artifact,+ runHtmlPreviewScripts: (artifact: RunArtifact) => artifact,openFromUrl: (fileKey: string, versionId: string | null) => ({ fileKey, versionId }),reportLinkCopied: true,reportObjectOpened: (objectKind: string) => ({ objectKind }),@@ -538,6 +617,22 @@ export const taskRunArtifactsLogic = kea<taskRunArtifactsLogicType>([null as ArtifactText | null,{loadArtifactText: async (artifact: RunArtifact): Promise<ArtifactText | null> => {+ const livingUrl = artifact.living?.stored+ ? artifactDownloadUrl(values.currentProjectId, props.taskId, artifact)+ : null+ if (livingUrl && artifact.id) {+ try {+ // nosemgrep: prefer-codegen-api -- A file download: the generated function parses the body as JSON.+ const response = await api.getResponse(livingUrl)+ return { artifactId: artifact.id, text: await response.text(), error: null }+ } catch {+ return {+ artifactId: artifact.id,+ text: null,+ error: 'This file did not load. Try again later.',+ }+ }+ }if (values.currentProjectId === null || !artifact.id || !artifact.storage_path) {return null}@@ -564,8 +659,41 @@ export const taskRunArtifactsLogic = kea<taskRunArtifactsLogicType>([},},],+ htmlPreview: [+ null as ArtifactHtmlPreview | null,+ {+ fetchHtmlPreview: async (+ { artifact, scripts }: HtmlPreviewRequest,+ breakpoint+ ): Promise<ArtifactHtmlPreview> => {+ const previous = values.htmlPreview+ const preview = await requestHtmlPreview(values.currentProjectId, props.taskId, artifact, scripts)+ breakpoint()+ if (+ scripts &&+ preview.url === null &&+ previous !== null &&+ previous.artifactId === artifact.id &&+ previous.url+ ) {+ return {+ ...previous,+ scriptsError: "Scripts didn't start. Try again, or keep using the page with scripts off.",+ }+ }+ return preview+ },+ },+ ],})),reducers({+ htmlPreview: {+ loadHtmlPreview: (_, artifact: RunArtifact): ArtifactHtmlPreview => emptyHtmlPreview(artifact.id ?? ''),+ runHtmlPreviewScripts: (state, artifact: RunArtifact): ArtifactHtmlPreview =>+ state !== null && state.artifactId === artifact.id && state.url+ ? { ...state, scriptsError: null }+ : emptyHtmlPreview(artifact.id ?? ''),+ },activeTab: ['conversation' as TaskRunTab,{ setActiveTab: (_, { tab }) => tab, openFromUrl: () => 'artifacts' },@@ -776,11 +904,12 @@ export const taskRunArtifactsLogic = kea<taskRunArtifactsLogicType>([],/** Why the open file can't be edited now, or null when it can. */editDisabledReason: [- (s) => [s.selectedEditableKind, s.selectedVersionIndex, s.selectedText],+ (s) => [s.selectedEditableKind, s.selectedVersionIndex, s.selectedText, s.artifactTextLoading],(selectedEditableKind: EditableArtifactKind | null,selectedVersionIndex: number,- selectedText: ArtifactText | null+ selectedText: ArtifactText | null,+ artifactTextLoading: boolean): string | null => {if (!selectedEditableKind) {return "This file type can't be edited here"@@ -789,9 +918,12 @@ export const taskRunArtifactsLogic = kea<taskRunArtifactsLogicType>([if (selectedVersionIndex !== 0) {return 'Only the latest version can be edited'}- if (!selectedText || selectedText.text === null) {+ if ((!selectedText || selectedText.text === null) && selectedEditableKind !== 'html') {return 'The file has not loaded yet'}+ if (selectedEditableKind === 'html' && artifactTextLoading) {+ return 'The file is loading'+ }return null},],@@ -806,7 +938,7 @@ export const taskRunArtifactsLogic = kea<taskRunArtifactsLogicType>([},],}),- listeners(({ actions, values, props }) => {+ listeners(({ actions, values, props, cache }) => {const editProperties = (session: ArtifactEditSession): Record<string, unknown> => ({kind: session.kind,content_type: session.contentType,@@ -826,6 +958,7 @@ export const taskRunArtifactsLogic = kea<taskRunArtifactsLogicType>([name: session.name,content,contentType: session.contentType,+ baseArtifactId: session.baseArtifactId,})// Read the manifests before the edit ends, so the new version is in the list when the preview opens.actions.loadChainRunsSuccess(@@ -845,13 +978,22 @@ export const taskRunArtifactsLogic = kea<taskRunArtifactsLogicType>([actions.setEditSaving(false)}}- const loadSelectedText = (): void => {+ const loadSelectedText = ({ source }: { source: boolean }): void => {const artifact = values.selectedArtifactconst kind = values.selectedKindif (values.activeTab !== 'artifacts' || !artifact || !kind) {return}- if (isTextPreview(kind) && !values.selectedText) {+ if (+ kind === 'html' &&+ (values.htmlPreview?.artifactId !== artifact.id ||+ (!values.htmlPreviewLoading &&+ !values.htmlPreview?.error &&+ (values.htmlPreview?.expiresAt ?? 0) < Date.now()))+ ) {+ actions.loadHtmlPreview(artifact)+ }+ if (isTextPreview(kind) && !values.selectedText && (kind !== 'html' || source)) {actions.loadArtifactText(artifact)} else if (kind === 'video' && !artifact.living && !values.selectedMedia) {// A living version plays from its same-origin URL, so only an uploaded video loads into a blob.@@ -915,6 +1057,27 @@ export const taskRunArtifactsLogic = kea<taskRunArtifactsLogicType>([})},ensureSelectedText: loadSelectedText,+ loadArtifactTextSuccess: ({ artifactText }) => {+ if (!artifactText || cache.editAfterTextLoads !== artifactText.artifactId) {+ return+ }+ cache.editAfterTextLoads = null+ if (values.selectedArtifact?.id !== artifactText.artifactId) {+ return+ }+ if (artifactText.text === null) {+ toast.error({ title: "Couldn't load this file for editing. Try again." })+ return+ }+ actions.startEditing()+ },+ loadHtmlPreview: (artifact) => {+ actions.fetchHtmlPreview({ artifact, scripts: false })+ },+ runHtmlPreviewScripts: (artifact) => {+ posthog.capture('task artifact scripts run', { living: !!values.selectedArtifact?.living })+ actions.fetchHtmlPreview({ artifact, scripts: true })+ },loadChainRuns: (runIds) => {if (runIds[0]) {actions.loadLivingArtifacts(runIds[0])@@ -1006,7 +1169,14 @@ export const taskRunArtifactsLogic = kea<taskRunArtifactsLogicType>([const artifact = values.selectedArtifactconst kind = values.selectedEditableKindconst text = values.selectedText?.text- if (values.editDisabledReason || !file || !artifact?.id || !kind || typeof text !== 'string') {+ if (values.editDisabledReason || !file || !artifact?.id || !kind) {+ return+ }+ if (typeof text !== 'string') {+ if (kind === 'html') {+ cache.editAfterTextLoads = artifact.id+ actions.loadArtifactText(artifact)+ }return}const session: ArtifactEditSession = {diff --git a/products/posthog_ai/frontend/utils/artifactUpload.ts b/products/posthog_ai/frontend/utils/artifactUpload.tsindex baa1fd582c2c..c90bdf688827 100644--- a/products/posthog_ai/frontend/utils/artifactUpload.ts+++ b/products/posthog_ai/frontend/utils/artifactUpload.ts@@ -136,7 +136,12 @@ export async function uploadRunOutputVersion(projectId: string,taskId: string,runId: string,- { name, content, contentType }: { name: string; content: string; contentType: string }+ {+ name,+ content,+ contentType,+ baseArtifactId,+ }: { name: string; content: string; contentType: string; baseArtifactId: string }): Promise<string> {const file = new File([content], name, { type: contentType })const {@@ -158,6 +163,7 @@ export async function uploadRunOutputVersion(type: TaskRunArtifactTypeEnumApi.Output,storage_path: prepared.storage_path,content_type: contentType,+ base_artifact_id: baseArtifactId,},],})diff --git a/products/tasks/backend/constants.py b/products/tasks/backend/constants.pyindex 23e9c54c20be..37b3cb9e1fd1 100644--- a/products/tasks/backend/constants.py+++ b/products/tasks/backend/constants.py@@ -18,6 +18,14 @@ CI_STATUSES = ("passing", "failing", "pending", "none")# skips the JSONB scan while a query repeats the predicate verbatim, so readers filtering on the# prefix must use this constant rather than a literal of their own.GITHUB_PR_URL_PREFIX = "https://github.com/"+ARTIFACT_OPEN_NETWORK_WRITER_KEY = "written_with_open_network"+ARTIFACT_SCRIPT_SHA256_KEY = "script_sha256"+++def is_html_artifact(name: str, content_type: str) -> bool:+ mime_type = content_type.split(";", 1)[0].strip().lower()+ return mime_type == "text/html" or name.lower().endswith((".html", ".htm"))+SANDBOX_EVENT_INGEST_FEATURE_FLAG = "tasks-cloud-runs-sandbox-event-ingest"WORKFLOW_DISPATCH_SHADOW_FEATURE_FLAG = "tasks-workflow-dispatch-shadow"diff --git a/products/tasks/backend/facade/api.py b/products/tasks/backend/facade/api.pyindex b4854de0099a..cd309f1cdd99 100644--- a/products/tasks/backend/facade/api.py+++ b/products/tasks/backend/facade/api.py@@ -74,6 +74,7 @@ from products.tasks.backend.constants import (ANALYSIS_TARGET_REPOSITORY_STATE_KEY,ANALYSIS_TARGET_RUN_ID_STATE_KEY,ANALYSIS_TARGET_TASK_ID_STATE_KEY,+ ARTIFACT_SCRIPT_SHA256_KEY as ARTIFACT_SCRIPT_SHA256_KEY,CI_STATUSES as CI_STATUSES, # re-exported for presentationCODEX_OWN_SUBSCRIPTION_CLOUD_FEATURE_FLAG as CODEX_OWN_SUBSCRIPTION_CLOUD_FEATURE_FLAG,DEV_STACK_PREVIEW_PORT,@@ -93,6 +94,7 @@ from products.tasks.backend.constants import (TIMED_OUT_INACTIVITY_STATE_KEY as TIMED_OUT_INACTIVITY_STATE_KEY, # re-exported for the scout reaperget_required_model_flag,is_blocked_sandbox_env_key,+ is_html_artifact as is_html_artifact,is_same_run_resume_state,)from products.tasks.backend.error_telemetry import truncate_error_message@@ -338,7 +340,10 @@ __all__ = ["presign_task_run_artifact_download","presign_task_run_living_artifact_version_download","read_task_run_artifact",+ "read_task_run_html_artifact","read_task_run_living_artifact_version",+ "sandbox_token_has_open_network",+ "is_html_artifact","get_task_run_log_urls","get_task_run_log_size","read_task_run_log_content",@@ -2691,6 +2696,7 @@ def delete_sandbox_custom_image(image_id: str | UUID, team_id: int, user_id: int# These keys are reserved for server-owned run state, never PATCH input._PROTECTED_RUN_STATE_KEYS = frozenset({+ "sandbox_environment_id",# Worker-interpreted trial markers must never be caller-writable."scout_trial","scout_trial_judge",@@ -4118,6 +4124,7 @@ def _build_artifact_manifest_entry(content_type: str,storage_path: str,uploaded_at: str,+ script_sha256: str | None = None,metadata: dict[str, Any] | None = None,) -> dict[str, Any]:entry: dict[str, Any] = {@@ -4130,6 +4137,8 @@ def _build_artifact_manifest_entry("storage_path": storage_path,"uploaded_at": uploaded_at,}+ if script_sha256 is not None:+ entry[ARTIFACT_SCRIPT_SHA256_KEY] = script_sha256if metadata:entry["metadata"] = metadatareturn entry@@ -4142,6 +4151,37 @@ def _find_artifact_manifest_entry(manifest: list[dict], artifact_id: str, storag)+ARTIFACT_SCRIPT_HASH_BUDGET_BYTES = 64 * 1024 * 1024+++def _earlier_versions_run_scripts(manifest: list[dict], name: str) -> bool:+ return all(isinstance(e.get(ARTIFACT_SCRIPT_SHA256_KEY), str) for e in manifest if e.get("name") == name)+++def _new_version_may_run_scripts(manifest: list[dict], name: str, base: dict | None, budget: int) -> tuple[bool, int]:+ from products.tasks.backend.logic.services.living_artifacts import ( # noqa: PLC0415 — keep storage deps off the api import path+ stored_bytes_match_digest,+ )++ if not _earlier_versions_run_scripts([*manifest, *([base] if base else [])], name):+ return False, 0+ previous = base or next((e for e in reversed(manifest) if e.get("name") == name), None)+ if previous is None:+ return True, 0+ size = previous.get("size")+ if not isinstance(size, int) or size > budget:+ return False, 0+ return stored_bytes_match_digest(previous.get("storage_path"), previous.get(ARTIFACT_SCRIPT_SHA256_KEY)), size+++def _append_versions(manifest: list[dict], entries: list[dict]) -> list[dict]:+ for entry in entries:+ if ARTIFACT_SCRIPT_SHA256_KEY in entry and not _earlier_versions_run_scripts(manifest, entry["name"]):+ del entry[ARTIFACT_SCRIPT_SHA256_KEY]+ manifest.append(entry)+ return manifest++def _save_artifact_manifest(run: TaskRun, manifest: list[dict]) -> None:run.artifacts = manifestrun.save(update_fields=["artifacts", "updated_at"])@@ -4154,6 +4194,7 @@ def upload_task_run_artifacts(*,artifacts: list[dict],uploaded_by: Literal["agent", "user"] | None = None,+ written_with_open_network: bool = False,) -> tuple[list[dict], list[dict]] | None:"""Write artifact bytes to S3 and append them to the run manifest.@@ -4174,6 +4215,7 @@ def upload_task_run_artifacts(return Noneuploaded: list[dict] = []+ hash_budget = ARTIFACT_SCRIPT_HASH_BUDGET_BYTESfor artifact in artifacts:artifact_id = str(artifact.get("id") or uuid_module.uuid4().hex)safe_name, storage_path = _build_artifact_storage_path(run, artifact_id, artifact["name"])@@ -4184,6 +4226,14 @@ def upload_task_run_artifacts(if content_type:extras["ContentType"] = content_type+ may_run_scripts = written_with_open_network+ if may_run_scripts and is_html_artifact(safe_name, content_type or ""):+ may_run_scripts, spent = _new_version_may_run_scripts(+ [*(run.artifacts or []), *uploaded], safe_name, None, hash_budget+ )+ hash_budget -= spent+ script_sha256 = hashlib.sha256(content_bytes).hexdigest() if may_run_scripts else None+object_storage.write(storage_path, content_bytes, extras or None)_tag_artifact_object(run, storage_path)@@ -4197,6 +4247,7 @@ def upload_task_run_artifacts(content_type=content_type or "",storage_path=storage_path,uploaded_at=django_timezone.now().isoformat(),+ script_sha256=script_sha256,metadata=artifact.get("metadata"),))@@ -4213,8 +4264,9 @@ def upload_task_run_artifacts(with transaction.atomic():run = TaskRun.objects.select_for_update().get(pk=run.pk)uploaded_ids = {entry["id"] for entry in uploaded}- manifest = [entry for entry in (run.artifacts or []) if entry.get("id") not in uploaded_ids]- manifest.extend(uploaded)+ manifest = _append_versions(+ [entry for entry in (run.artifacts or []) if entry.get("id") not in uploaded_ids], uploaded+ )_save_artifact_manifest(run, manifest)if uploaded_by == "agent":@@ -4392,6 +4444,7 @@ def finalize_task_run_artifact_uploads(artifacts: list[dict],uploaded_by: Literal["agent", "user"],uploaded_by_user_id: int | None,+ written_with_open_network: bool = False,) -> tuple[list[dict] | None, str | None]:"""Verify directly-uploaded S3 objects and attach them to the run manifest.@@ -4418,6 +4471,7 @@ def finalize_task_run_artifact_uploads(artifact_prefix = f"{run.get_artifact_s3_prefix()}/"finalized_entries: list[dict] = []new_entries: list[dict] = []+ hash_budget = ARTIFACT_SCRIPT_HASH_BUDGET_BYTESnew_storage_paths: list[str] = []for artifact in artifacts:@@ -4446,6 +4500,27 @@ def finalize_task_run_artifact_uploads(if content_length > max_size_bytes:return None, build_task_run_artifact_size_error(safe_name, max_size_bytes)+ script_sha256 = None+ base_artifact_id = artifact.get("base_artifact_id")+ base_entry = next((e for e in manifest if e.get("id") == base_artifact_id), None) if base_artifact_id else None+ if (+ written_with_open_network+ and (base_artifact_id is None or base_entry is not None)+ and is_html_artifact(safe_name, content_type)+ and content_length <= hash_budget+ ):+ may_run_scripts, spent = _new_version_may_run_scripts(+ manifest, safe_name, base_entry, hash_budget - content_length+ )+ hash_budget -= content_length + spent+ if may_run_scripts:+ try:+ uploaded_bytes = object_storage.read_bytes(storage_path, missing_ok=True)+ except Exception:+ logger.warning("task_run.artifact_script_hash_failed", extra={"task_run_id": str(run.id)})+ uploaded_bytes = None+ script_sha256 = hashlib.sha256(uploaded_bytes).hexdigest() if uploaded_bytes is not None else None+entry = _build_artifact_manifest_entry(artifact_id=artifact_id,name=safe_name,@@ -4455,6 +4530,7 @@ def finalize_task_run_artifact_uploads(content_type=content_type,storage_path=storage_path,uploaded_at=django_timezone.now().isoformat(),+ script_sha256=script_sha256,metadata=artifact.get("metadata"),)entry["uploaded_by"] = uploaded_by@@ -4472,8 +4548,9 @@ def finalize_task_run_artifact_uploads(with transaction.atomic():locked_run = TaskRun.objects.select_for_update().get(pk=run.pk)new_ids = {entry["id"] for entry in new_entries}- merged = [entry for entry in (locked_run.artifacts or []) if entry.get("id") not in new_ids]- merged.extend(new_entries)+ merged = _append_versions(+ [entry for entry in (locked_run.artifacts or []) if entry.get("id") not in new_ids], new_entries+ )_save_artifact_manifest(locked_run, merged)# Count versions from the locked merge, or a concurrent same-named finalize is missed.manifest = merged@@ -4531,19 +4608,20 @@ def get_task_run_living_artifact(return serialized-def read_task_run_living_artifact_version(- run_id: str | UUID, task_id: str | UUID, team_id: int, *, artifact_id: str | UUID, version: int-) -> tuple[contracts.LivingArtifactVersionContent | None, str | None]:- """Read the content of one living artifact version.+_LivingVersionResult = TypeVar("_LivingVersionResult")- Returns ``(content, error)``: ``(None, None)`` if the run isn't found, ``(None, "not_found")`` if the- artifact or version isn't found or keeps no content, ``(None, "too_large")`` if a stored version is- over the preview limit, ``(None, "read_failed")`` if the storage read raised, else ``(content, None)``.- """++def _task_run_living_artifact_version(+ run_id: str | UUID,+ task_id: str | UUID,+ team_id: int,+ artifact_id: str | UUID,+ version: int,+ load: Callable[[Any, int], _LivingVersionResult | None],+) -> tuple[_LivingVersionResult | None, str | None]:from products.tasks.backend.logic.services.living_artifacts import ( # noqa: PLC0415 — keep storage deps off the api import pathLivingArtifactVersionTooLarge,get_task_artifact_for_run,- read_living_artifact_version,)run = _get_visible_run(run_id, task_id, team_id)@@ -4557,15 +4635,46 @@ def read_task_run_living_artifact_version(if artifact is None:return None, "not_found"try:- content = read_living_artifact_version(artifact, version)+ result = load(artifact, version)except LivingArtifactVersionTooLarge:return None, "too_large"except Exception:logger.exception("Failed to read living artifact %s version %s for team %s", artifact_id, version, team_id)return None, "read_failed"- if content is None:+ if result is None:return None, "not_found"- return content, None+ return result, None+++def read_task_run_living_artifact_version(+ run_id: str | UUID, task_id: str | UUID, team_id: int, *, artifact_id: str | UUID, version: int+) -> tuple[contracts.LivingArtifactVersionContent | None, str | None]:+ """Read the content of one living artifact version.++ Returns ``(content, error)``: ``(None, None)`` if the run isn't found, ``(None, "not_found")`` if the+ artifact or version isn't found or keeps no content, ``(None, "too_large")`` if a stored version is+ over the preview limit, ``(None, "read_failed")`` if the storage read raised, else ``(content, None)``.+ """+ from products.tasks.backend.logic.services.living_artifacts import ( # noqa: PLC0415 — keep storage deps off the api import path+ read_living_artifact_version,+ )++ return _task_run_living_artifact_version(+ run_id, task_id, team_id, artifact_id, version, read_living_artifact_version+ )+++def describe_task_run_living_artifact_version(+ run_id: str | UUID, task_id: str | UUID, team_id: int, *, artifact_id: str | UUID, version: int+) -> tuple[contracts.LivingArtifactVersionPreview | None, str | None]:+ """Describe one living artifact version for a preview, without reading its stored bytes. Errors as in the read."""+ from products.tasks.backend.logic.services.living_artifacts import ( # noqa: PLC0415 — keep storage deps off the api import path+ describe_living_artifact_version,+ )++ return _task_run_living_artifact_version(+ run_id, task_id, team_id, artifact_id, version, describe_living_artifact_version+ )def presign_task_run_living_artifact_version_download(@@ -4618,6 +4727,7 @@ def create_task_run_living_artifact(*,artifact: dict,caller_is_agent: bool = False,+ written_with_open_network: bool = False,) -> tuple[dict | None, str | None]:from products.tasks.backend.logic.services.living_artifacts import ( # noqa: PLC0415 — keep storage deps off the api import pathcreate_living_artifact,@@ -4628,7 +4738,7 @@ def create_task_run_living_artifact(if run is None:return None, Nonetry:- created = create_living_artifact(run=run, **artifact)+ created = create_living_artifact(run=run, written_with_open_network=written_with_open_network, **artifact)except Exception as exc:logger.warning("Failed to create living artifact for task run %s: %s", run.id, exc)return None, str(exc)@@ -4644,6 +4754,7 @@ def edit_task_run_living_artifact(team_id: int,*,caller_is_agent: bool = False,+ written_with_open_network: bool = False,artifact_id: str | UUID,content: str | None = None,content_bytes: bytes | None = None,@@ -4676,6 +4787,7 @@ def edit_task_run_living_artifact(source_storage_path=source_storage_path,name=name,metadata=metadata,+ written_with_open_network=written_with_open_network,)except Exception as exc:logger.warning("Failed to edit living artifact %s for task run %s: %s", artifact_id, run.id, exc)@@ -4782,6 +4894,68 @@ def presign_task_run_artifact_download(return url, None+def _run_has_open_network(run: TaskRun) -> bool:+ if not (run.state or {}).get("sandbox_environment_id"):+ return True+ environment = run.get_sandbox_environment()+ return (+ environment is not None+ and environment.network_access_level == SandboxNetworkAccessLevel.FULL+ and environment.updated_at <= run.created_at+ )+++def sandbox_token_has_open_network(+ team_id: int, token_id: UUID | int | str, *, task_id: UUID | str | None = None+) -> bool:+ runs = TaskRun.objects.filter(team_id=team_id, state__sandbox_oauth_token_ids__contains=[str(token_id)])+ if task_id is not None:+ runs = runs.filter(task_id=task_id)+ checked = False+ for run in runs.select_related("task"):+ if not _run_has_open_network(run):+ return False+ checked = True+ return checked+++def task_run_artifact_entry(+ run_id: str | UUID, task_id: str | UUID, team_id: int, *, artifact_id: str+) -> dict[str, Any] | None:+ run = _get_visible_run(run_id, task_id, team_id)+ if run is None:+ return None+ return next(+ (+ entry+ for entry in run.artifacts or []+ if entry.get("id") == artifact_id+ and entry.get("storage_path")+ and not entry.get("dismissed_at")+ and (+ (entry.get("type") == "output" and entry.get("uploaded_by") == "user")+ or (entry.get("type") in ("output", "artifact") and entry.get("source") == "agent_output")+ )+ ),+ None,+ )+++def read_task_run_html_artifact(+ run_id: str | UUID, task_id: str | UUID, team_id: int, *, artifact_id: str+) -> bytes | None:+ from posthog.storage import object_storage # noqa: PLC0415 — keep storage deps off the api import path++ entry = task_run_artifact_entry(run_id, task_id, team_id, artifact_id=artifact_id)+ if entry is None or not is_html_artifact(str(entry.get("name") or ""), str(entry.get("content_type") or "")):+ return None+ try:+ return object_storage.read_bytes(str(entry["storage_path"]), missing_ok=True)+ except Exception:+ logger.exception("task_run.artifact_preview_read_failed", extra={"task_run_id": str(run_id)})+ return None++def read_task_run_artifact(run_id: str | UUID, task_id: str | UUID, team_id: int, *, storage_path: str) -> tuple[bytes | None, dict | None, str | None]:diff --git a/products/tasks/backend/facade/client_provenance.py b/products/tasks/backend/facade/client_provenance.pyindex 370a4844db2f..8466a47b5fbc 100644--- a/products/tasks/backend/facade/client_provenance.py+++ b/products/tasks/backend/facade/client_provenance.py@@ -1,8 +1,9 @@from rest_framework.request import Requestfrom posthog.oauth_provenance import (+ get_oauth_access_token as get_oauth_access_token,get_oauth_client_id,- is_interactive_desktop_grant,+ is_interactive_desktop_grant as is_interactive_desktop_grant,is_sandbox_oauth_request as is_sandbox_oauth_request,is_sandbox_origin_request as is_sandbox_origin_request,)diff --git a/products/tasks/backend/facade/contracts.py b/products/tasks/backend/facade/contracts.pyindex 21ac665516a4..b39fd5287b68 100644--- a/products/tasks/backend/facade/contracts.py+++ b/products/tasks/backend/facade/contracts.py@@ -1062,6 +1062,14 @@ class LivingArtifactVersionContent:name: strcontent_type: strcontent: bytes+ script_sha256: str | None+++@dataclass(frozen=True, kw_only=True)+class LivingArtifactVersionPreview:+ name: str+ content_type: str+ script_sha256: str | None@dataclass(frozen=True, kw_only=True)diff --git a/products/tasks/backend/logic/services/living_artifacts.py b/products/tasks/backend/logic/services/living_artifacts.pyindex e904ea352d12..17c4cc2a0f3b 100644--- a/products/tasks/backend/logic/services/living_artifacts.py+++ b/products/tasks/backend/logic/services/living_artifacts.py@@ -5,6 +5,7 @@ import osimport jsonimport timeimport uuid+import hashlibimport zipfileimport mimetypesfrom abc import ABC, abstractmethod@@ -35,7 +36,12 @@ from posthog.utils import absolute_urifrom products.exports.backend.facade.api import get_delivery_image_urlfrom products.slack_app.backend.services.slack_messages import post_slack_thread_reply, slack_message_exists-from products.tasks.backend.facade.contracts import LivingArtifactVersionContent+from products.tasks.backend.constants import (+ ARTIFACT_OPEN_NETWORK_WRITER_KEY,+ ARTIFACT_SCRIPT_SHA256_KEY,+ is_html_artifact,+)+from products.tasks.backend.facade.contracts import LivingArtifactVersionContent, LivingArtifactVersionPreviewfrom products.tasks.backend.models import TaskArtifact, TaskRunlogger = structlog.get_logger(__name__)@@ -116,6 +122,7 @@ def create_living_artifact(source_storage_path: str | None = None,metadata: dict[str, Any] | None = None,export_asset_id: int | None = None,+ written_with_open_network: bool = False,) -> TaskArtifact:content_payload = resolve_artifact_content(run=run,@@ -161,13 +168,52 @@ def create_living_artifact("source_artifact_id": source_artifact_id,"source_storage_path": source_storage_path,},- versions=[commit.version],+ versions=[+ {+ **commit.version,+ ARTIFACT_OPEN_NETWORK_WRITER_KEY: written_with_open_network+ and _source_runs_scripts(content_payload),+ }+ ],current_version=1,export_asset_id=export_asset_id,)return artifact+def stored_bytes_match_digest(storage_path: object, digest: object) -> bool:+ if not isinstance(storage_path, str) or not isinstance(digest, str):+ return False+ try:+ stored = object_storage.read_bytes(storage_path, missing_ok=True)+ except Exception:+ logger.warning("task_artifact.script_digest_read_failed", storage_path=storage_path)+ return False+ return stored is not None and hashlib.sha256(stored).hexdigest() == digest+++def _version_may_keep_scripts(artifact: TaskArtifact, version: int, *, verify_bytes: bool) -> bool:+ resolved = resolve_living_artifact_version(artifact, version)+ if resolved is None or resolved.record.get(ARTIFACT_OPEN_NETWORK_WRITER_KEY) is not True:+ return False+ return (+ not verify_bytes+ or not resolved.storage_path+ or stored_bytes_match_digest(resolved.storage_path, resolved.record.get("content_sha256"))+ )+++def _source_runs_scripts(content: ArtifactContent) -> bool:+ if content.source_artifact is None:+ return True+ digest = content.source_artifact.get(ARTIFACT_SCRIPT_SHA256_KEY)+ return (+ isinstance(digest, str)+ and content.content_bytes is not None+ and hashlib.sha256(content.content_bytes).hexdigest() == digest+ )++def edit_living_artifact(*,artifact: TaskArtifact,@@ -179,6 +225,7 @@ def edit_living_artifact(source_storage_path: str | None = None,name: str | None = None,metadata: dict[str, Any] | None = None,+ written_with_open_network: bool = False,) -> TaskArtifact:# `run` is the run performing the edit — a follow-up run editing a prior run's artifact# must resolve Slack mappings (repointed to the latest run) and storage paths as itself,@@ -201,6 +248,10 @@ def edit_living_artifact(artifact_type=artifact.artifact_type,content=content_payload,)+ base_version_number = int(artifact.current_version or 0)+ base_keeps_scripts = written_with_open_network and _version_may_keep_scripts(+ artifact, base_version_number, verify_bytes=is_html_artifact(next_name, content_payload.content_type)+ )existing_content = selected_adapter.open(artifact)next_content = selected_adapter.apply_edit(existing_content, content_payload.body)commit = selected_adapter.commit(@@ -217,7 +268,20 @@ def edit_living_artifact(with transaction.atomic():locked = TaskArtifact.objects.for_team(artifact.team_id).select_for_update().get(pk=artifact.pk)versions = list(locked.versions or [])- versions.append(commit.version)+ base_version = next(+ (v for v in versions if isinstance(v, dict) and v.get("version") == locked.current_version), None+ )+ versions.append(+ {+ **commit.version,+ ARTIFACT_OPEN_NETWORK_WRITER_KEY: written_with_open_network+ and base_keeps_scripts+ and locked.current_version == base_version_number+ and base_version is not None+ and base_version.get(ARTIFACT_OPEN_NETWORK_WRITER_KEY) is True+ and _source_runs_scripts(content_payload),+ }+ )locked.name = next_namelocked.adapter = commit.adapterlocked.location = commit.location@@ -428,6 +492,38 @@ def _stored_version_size(resolved: LivingVersionLocation) -> int | None:return length if isinstance(length, int) else None+def _describe_resolved_version(+ artifact: TaskArtifact, resolved: LivingVersionLocation, *, require_known_size: bool+) -> LivingArtifactVersionPreview | None:+ written_with_open_network = resolved.record.get(ARTIFACT_OPEN_NETWORK_WRITER_KEY) is True+ if resolved.storage_path:+ size = _stored_version_size(resolved)+ if size is None and require_known_size:+ return None+ if size is not None and size > LIVING_VERSION_PREVIEW_MAX_BYTES:+ raise LivingArtifactVersionTooLarge()+ stored_sha256 = resolved.record.get("content_sha256")+ script_sha256 = stored_sha256 if written_with_open_network and isinstance(stored_sha256, str) else None+ else:+ text = resolved.record.get("content")+ if not isinstance(text, str):+ return None+ script_sha256 = hashlib.sha256(text.encode("utf-8")).hexdigest() if written_with_open_network else None+ return LivingArtifactVersionPreview(+ name=artifact.name, content_type=resolved.content_type, script_sha256=script_sha256+ )+++def describe_living_artifact_version(artifact: TaskArtifact, version: int) -> LivingArtifactVersionPreview | None:+ """Return the name, type and script digest of one version without reading stored bytes.++ Returns None when the version is unknown or keeps no content. A stored version above the preview+ limit raises LivingArtifactVersionTooLarge.+ """+ resolved = resolve_living_artifact_version(artifact, version)+ return None if resolved is None else _describe_resolved_version(artifact, resolved, require_known_size=True)++def read_living_artifact_version(artifact: TaskArtifact, version: int) -> LivingArtifactVersionContent | None:"""Return the content of one version, or None when the version is unknown or keeps no content.@@ -438,22 +534,21 @@ def read_living_artifact_version(artifact: TaskArtifact, version: int) -> Livingresolved = resolve_living_artifact_version(artifact, version)if resolved is None:return None-+ preview = _describe_resolved_version(artifact, resolved, require_known_size=False)+ if preview is None:+ return Noneif resolved.storage_path:- size = _stored_version_size(resolved)- if size is not None and size > LIVING_VERSION_PREVIEW_MAX_BYTES:- raise LivingArtifactVersionTooLarge()payload = object_storage.read_bytes(resolved.storage_path, missing_ok=True)if payload is None:return None- return LivingArtifactVersionContent(name=artifact.name, content_type=resolved.content_type, content=payload)-- text = resolved.record.get("content")- if isinstance(text, str):- return LivingArtifactVersionContent(- name=artifact.name, content_type=resolved.content_type, content=text.encode("utf-8")- )- return None+ else:+ payload = str(resolved.record.get("content")).encode("utf-8")+ return LivingArtifactVersionContent(+ name=preview.name,+ content_type=preview.content_type,+ content=payload,+ script_sha256=preview.script_sha256,+ )# The task part of TaskRun.get_artifact_s3_prefix. Keep the two formats the same.@@ -900,6 +995,7 @@ class SlackFileArtifactAdapter(LivingArtifactAdapter):content_type=resolved_content_type,source_artifact=source_artifact,size=len(payload),+ content_sha256=hashlib.sha256(payload).hexdigest(),)version_payload["delivery_status"] = "pending"return ArtifactCommit(@@ -1612,6 +1708,7 @@ def _version_payload(source_artifact: dict[str, Any] | None = None,content: str | None = None,size: int | None = None,+ content_sha256: str | None = None,) -> dict[str, Any]:payload: dict[str, Any] = {"version": version,@@ -1626,6 +1723,8 @@ def _version_payload(payload["source_storage_path"] = source_artifact.get("storage_path")if size is not None:payload["size"] = size+ if content_sha256 is not None:+ payload["content_sha256"] = content_sha256if content is not None:payload["content"] = contentreturn payloaddiff --git a/products/tasks/backend/presentation/serializers.py b/products/tasks/backend/presentation/serializers.pyindex 6d0b36651812..43fd47814f15 100644--- a/products/tasks/backend/presentation/serializers.py+++ b/products/tasks/backend/presentation/serializers.py@@ -1847,6 +1847,14 @@ class TaskRunArtifactFinalizeUploadSerializer(serializers.Serializer):required=False,help_text="Skill bundle metadata, required when the artifact type is skill_bundle.",)+ base_artifact_id = serializers.CharField(+ max_length=255,+ required=False,+ help_text=(+ "ID of the artifact in the same run that this file edits. An HTML edit can run scripts only when "+ "its base artifact can."+ ),+ )def validate(self, attrs):return validate_task_run_artifact_metadata(attrs)@@ -2004,6 +2012,16 @@ class TaskRunArtifactPresignResponseSerializer(serializers.Serializer):expires_in = serializers.IntegerField(help_text="URL expiry in seconds")+class TaskRunArtifactPreviewResponseSerializer(serializers.Serializer):+ url = serializers.URLField(help_text="Short-lived URL for the isolated HTML preview")+ scripts_available = serializers.BooleanField(+ help_text=(+ "Whether the caller can request a preview that runs scripts. False when whoever wrote this artifact "+ "version had limited network access, or when the version has no record of it."+ )+ )++class TaskRunArtifactsDismissRequestSerializer(serializers.Serializer):artifact_ids = serializers.ListField(child=serializers.CharField(max_length=128),diff --git a/products/tasks/backend/presentation/views/api.py b/products/tasks/backend/presentation/views/api.pyindex 7229deaa813b..97d4167383aa 100644--- a/products/tasks/backend/presentation/views/api.py+++ b/products/tasks/backend/presentation/views/api.py@@ -81,7 +81,9 @@ from products.tasks.backend.facade.access import (from products.tasks.backend.facade.billing import TaskTokenUsageUnavailable, get_task_usagefrom products.tasks.backend.facade.client_provenance import (TASK_CLIENT_PROVENANCE_HEADER,+ get_oauth_access_token,get_task_client_provenance,+ is_interactive_desktop_grant,is_sandbox_oauth_request,is_sandbox_origin_request,)@@ -167,6 +169,7 @@ from products.tasks.backend.presentation.serializers import (TaskRunAppendLogRequestSerializer,TaskRunArtifactPresignRequestSerializer,TaskRunArtifactPresignResponseSerializer,+ TaskRunArtifactPreviewResponseSerializer,TaskRunArtifactsDismissRequestSerializer,TaskRunArtifactsDismissResponseSerializer,TaskRunArtifactsFinalizeUploadRequestSerializer,@@ -225,6 +228,7 @@ from products.tasks.backend.presentation.serializers import (WizardCloudRunSerializer,)from products.tasks.backend.presentation.task_review_serializers import TaskReviewQuerySerializer, TaskReviewSerializer+from products.tasks.backend.presentation.views.artifact_preview import create_artifact_preview_urlfrom ee.hogai.utils.aio import async_to_sync@@ -1726,6 +1730,16 @@ def _sandbox_bound_task_id(request) -> UUID | None:return request.successful_authenticator.access_token.sandbox_task_id+def _writer_has_open_network(request: Request, team_id: int) -> bool:+ if is_sandbox_oauth_request(request):+ token = get_oauth_access_token(request)+ token_id = getattr(token, "id", None)+ return token_id is not None and tasks_facade.sandbox_token_has_open_network(+ team_id, token_id, task_id=getattr(token, "sandbox_task_id", None)+ )+ return get_oauth_access_token(request) is None or is_interactive_desktop_grant(request)++def _hidden_scout_trial_task_ids(request: Request, team_id: int) -> Iterable[UUID]:if is_sandbox_oauth_request(request):return tasks_facade.scout_trial_task_ids(team_id, visible_task_id=_sandbox_bound_task_id(request))@@ -1881,6 +1895,7 @@ class TaskRunViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):"artifacts_presign","artifacts_download","artifacts_download_by_id",+ "artifacts_preview",)_VISIBILITY_ONLY_ACTIONS = ("analyze",)@@ -2656,6 +2671,7 @@ class TaskRunViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):self.team_id,artifacts=request.validated_data["artifacts"],uploaded_by="agent" if self._is_sandbox_agent_request(task_id) else "user",+ written_with_open_network=_writer_has_open_network(request, self.team_id),)if result is None:raise NotFound()@@ -2767,6 +2783,7 @@ class TaskRunViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):artifacts=request.validated_data["artifacts"],uploaded_by="agent" if is_agent_upload else "user",uploaded_by_user_id=None if is_agent_upload else self._user_id(),+ written_with_open_network=_writer_has_open_network(request, self.team_id),)if finalized_entries is None and error is None:raise NotFound()@@ -2953,6 +2970,100 @@ class TaskRunViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):raise NotFound()return HttpResponseRedirect(url)+ @extend_schema(+ parameters=[+ OpenApiParameter("artifact_id", OpenApiTypes.STR, OpenApiParameter.PATH, description="Artifact id"),+ OpenApiParameter(+ "version",+ OpenApiTypes.INT,+ OpenApiParameter.QUERY,+ description="Living artifact version",+ required=False,+ ),+ OpenApiParameter(+ "scripts",+ OpenApiTypes.BOOL,+ OpenApiParameter.QUERY,+ description=(+ "Return a URL whose page runs its scripts. Without it the page renders with scripts off. "+ "Refused when scripts_available is false."+ ),+ required=False,+ ),+ ],+ responses={+ 200: TaskRunArtifactPreviewResponseSerializer,+ 400: OpenApiResponse(description="Invalid version or scripts value"),+ 403: OpenApiResponse(description="Scripts or analytics data are not available to the caller"),+ 404: OpenApiResponse(description="HTML artifact not found"),+ 503: OpenApiResponse(description="Artifact preview origin unavailable"),+ },+ summary="Open an isolated HTML artifact preview",+ description=(+ "Returns a short-lived URL for one HTML artifact version on the artifact origin. "+ "The page runs its scripts only when scripts=true."+ ),+ )+ @action(+ detail=True,+ methods=["get"],+ url_path=r"artifacts/(?P<artifact_id>[^/]+)/preview",+ required_scopes=["task:read"],+ )+ def artifacts_preview(self, request, pk=None, artifact_id=None, **kwargs):+ task_id = self._ensure_task_accessible()+ raw_version = request.query_params.get("version")+ if raw_version is not None and (+ len(raw_version) > 20 or not raw_version.isascii() or not raw_version.isdecimal() or int(raw_version) < 1+ ):+ raise ValidationError({"version": "Enter a positive version number."})+ version = int(raw_version) if raw_version is not None else None+ raw_scripts = request.query_params.get("scripts", "false")+ if raw_scripts not in ("true", "false"):+ raise ValidationError({"scripts": "Enter true or false."})+ run_scripts = raw_scripts == "true"+ if version is not None and not run_context.may_read_task_run_context(+ request=request, team_id=self.team_id, task_id=task_id, run_id=None+ ):+ raise PermissionDenied("The analytics data in this task run is not available to you.")+ if version is None:+ artifact = tasks_facade.task_run_artifact_entry(pk, task_id, self.team_id, artifact_id=artifact_id)+ if artifact is None or not tasks_facade.is_html_artifact(+ str(artifact.get("name") or ""), str(artifact.get("content_type") or "")+ ):+ raise NotFound()+ stored_sha256 = artifact.get(tasks_facade.ARTIFACT_SCRIPT_SHA256_KEY)+ script_digest = stored_sha256 if isinstance(stored_sha256, str) else None+ else:+ preview, error = tasks_facade.describe_task_run_living_artifact_version(+ pk, task_id, self.team_id, artifact_id=artifact_id, version=version+ )+ if (+ error is not None+ or preview is None+ or not tasks_facade.is_html_artifact(preview.name, preview.content_type)+ ):+ raise NotFound()+ script_digest = preview.script_sha256+ scripts_available = script_digest is not None+ if run_scripts and not scripts_available:+ raise PermissionDenied(+ "Scripts can't run in this artifact because its task run has limited network access."+ )+ url = create_artifact_preview_url(+ team_id=self.team_id,+ task_id=task_id,+ run_id=str(pk),+ artifact_id=artifact_id,+ version=version,+ script_digest=script_digest if run_scripts else None,+ )+ if url is None:+ return Response({"error": "Artifact preview is unavailable"}, status=status.HTTP_503_SERVICE_UNAVAILABLE)+ return Response(+ TaskRunArtifactPreviewResponseSerializer({"url": url, "scripts_available": scripts_available}).data+ )+def _preview_unavailable_page(self, outcome: str, task_id: str) -> HttpResponse:if outcome == "ended":heading = "This preview has ended"@@ -4489,6 +4600,7 @@ class TaskRunLivingArtifactViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSself.team_id,artifact=request.validated_data,caller_is_agent=is_sandbox_agent_request(request, task_id),+ written_with_open_network=_writer_has_open_network(request, self.team_id),)if artifact is None and error is None:raise NotFound()@@ -4622,6 +4734,7 @@ class TaskRunLivingArtifactViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewStask_id,self.team_id,caller_is_agent=is_sandbox_agent_request(request, task_id),+ written_with_open_network=_writer_has_open_network(request, self.team_id),artifact={"name": self._with_png_extension(name),"artifact_type": TaskArtifactType.FILE,@@ -4704,6 +4817,7 @@ class TaskRunLivingArtifactViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewStask_id,self.team_id,caller_is_agent=is_sandbox_agent_request(request, task_id),+ written_with_open_network=_writer_has_open_network(request, self.team_id),artifact_id=pk,content=request.validated_data.get("content"),content_bytes=request.validated_data.get("content_bytes"),diff --git a/products/tasks/backend/presentation/views/artifact_preview.py b/products/tasks/backend/presentation/views/artifact_preview.pynew file mode 100644index 000000000000..6ff407392245--- /dev/null+++ b/products/tasks/backend/presentation/views/artifact_preview.py@@ -0,0 +1,196 @@+import re+import json+import hashlib+import secrets+from collections.abc import AsyncIterator+from urllib.parse import urlsplit+from uuid import UUID++from django.conf import settings+from django.core.cache import caches+from django.http import Http404, HttpRequest, StreamingHttpResponse+from django.utils.connection import ConnectionProxy+from django.views.decorators.clickjacking import xframe_options_exempt++from posthog.api.streaming import streaming_response+from posthog.csp_middleware import app_frame_ancestor_sources+from posthog.dataclasses import frozen++from products.tasks.backend.facade import api as tasks_facade+from products.tasks.backend.presentation.serializers import TASK_RUN_ARTIFACT_MAX_SIZE_BYTES++PREVIEW_TOKEN_TTL_SECONDS = 300++cache = ConnectionProxy(caches, "task_artifact_preview")+++def _cache_key(token: str) -> str:+ return f"task-artifact-preview:{hashlib.sha256(token.encode()).hexdigest()}"+++def create_artifact_preview_url(+ *,+ team_id: int,+ task_id: str,+ run_id: str,+ artifact_id: str,+ version: int | None = None,+ script_digest: str | None = None,+) -> str | None:+ if not settings.CANVAS_ARTIFACT_ORIGIN and not (settings.DEBUG or settings.TEST):+ return None+ token = secrets.token_urlsafe(32)+ cache.set(+ _cache_key(token),+ json.dumps([team_id, task_id, run_id, artifact_id, version, script_digest]),+ timeout=PREVIEW_TOKEN_TTL_SECONDS,+ )+ from products.canvas.backend.facade.api import artifact_delivery_origin++ return f"{artifact_delivery_origin()}/canvas-artifacts/task-preview/{token}/index.html"+++@frozen+class _PreviewClaims:+ team_id: int+ task_id: UUID+ run_id: UUID+ artifact_id: str+ version: int | None+ script_digest: str | None+++def _preview_claims(token: str) -> _PreviewClaims:+ if not re.fullmatch(r"[A-Za-z0-9_-]{43}", token):+ raise Http404+ raw_claims = cache.get(_cache_key(token))+ if not isinstance(raw_claims, str):+ raise Http404+ try:+ team_id, task_id, run_id, artifact_id, version, script_digest = json.loads(raw_claims)+ if (+ not isinstance(team_id, int)+ or isinstance(team_id, bool)+ or not isinstance(artifact_id, str)+ or not (script_digest is None or isinstance(script_digest, str))+ ):+ raise ValueError+ if version is not None and (not isinstance(version, int) or isinstance(version, bool) or version < 1):+ raise ValueError+ return _PreviewClaims(+ team_id=team_id,+ task_id=UUID(task_id),+ run_id=UUID(run_id),+ artifact_id=artifact_id,+ version=version,+ script_digest=script_digest,+ )+ except (TypeError, ValueError):+ raise Http404 from None+++def _task_html_artifact_preview_csp(*, scripts: bool) -> str:+ site = urlsplit(settings.SITE_URL)+ ancestors = dict.fromkeys([f"{site.scheme}://{site.netloc}", *app_frame_ancestor_sources()])+ return "; ".join(+ [+ "sandbox allow-scripts" if scripts else "sandbox",+ "default-src 'none'",+ "script-src 'unsafe-inline'" if scripts else "script-src 'none'",+ "style-src 'unsafe-inline'",+ "img-src data: blob:",+ "font-src data:",+ "connect-src 'none'",+ "form-action 'none'",+ "base-uri 'none'",+ "object-src 'none'",+ "frame-src 'none'",+ "worker-src 'none'",+ f"frame-ancestors {' '.join(ancestors)}",+ ]+ )+++SHIM_CHUNK_BYTES = 1024 * 1024+_HTML_ATTRIBUTE_ESCAPES = ((b"&", b"&"), (b"<", b"<"), (b">", b">"), (b'"', b"""), (b"'", b"'"))+++_NETWORK_HINT_TAGS = re.compile(rb"<(link|meta)(?=[\t\n\f\r />])", re.IGNORECASE)+_DNS_PREFETCH_OFF = b'<meta http-equiv="x-dns-prefetch-control" content="off">'+++def _leading_doctype_end(content: bytes) -> int:+ position = 3 if content.startswith(b"\xef\xbb\xbf") else 0+ while True:+ while position < len(content) and content[position : position + 1].isspace():+ position += 1+ if not content.startswith(b"<!--", position):+ break+ comment_end = content.find(b"-->", position + 4)+ if comment_end == -1:+ return 0+ position = comment_end + 3+ if content[position : position + 9].lower() != b"<!doctype":+ return 0+ doctype_end = content.find(b">", position)+ return doctype_end + 1 if doctype_end != -1 else 0+++def _without_network_hints(content: bytes) -> bytes:+ content = _NETWORK_HINT_TAGS.sub(rb"<x-\1", content)+ split = _leading_doctype_end(content)+ return content[:split] + _DNS_PREFETCH_OFF + content[split:]+++def _escape_html_attribute(chunk: bytes) -> bytes:+ for raw, entity in _HTML_ATTRIBUTE_ESCAPES:+ chunk = chunk.replace(raw, entity)+ return chunk+++async def _task_html_artifact_shim(content: bytes, *, scripts: bool) -> AsyncIterator[bytes]:+ yield (+ '<!DOCTYPE html><html><head><meta charset="utf-8">'+ "<style>html,body{margin:0;height:100%}iframe{display:block;width:100%;height:100%;border:0}</style>"+ f'</head><body><iframe sandbox="{"allow-scripts" if scripts else ""}" title="Artifact" srcdoc="'+ ).encode()+ for start in range(0, len(content), SHIM_CHUNK_BYTES):+ yield _escape_html_attribute(content[start : start + SHIM_CHUNK_BYTES])+ yield b'"></iframe></body></html>'+++@xframe_options_exempt+def task_artifact_preview(request: HttpRequest, token: str) -> StreamingHttpResponse:+ from products.canvas.backend.facade.api import ARTIFACT_PERMISSIONS_POLICY, require_artifact_host++ require_artifact_host(request.get_host())+ claims = _preview_claims(token)+ if claims.version is None:+ content = tasks_facade.read_task_run_html_artifact(+ claims.run_id, claims.task_id, claims.team_id, artifact_id=claims.artifact_id+ )+ error = None+ else:+ living_content, error = tasks_facade.read_task_run_living_artifact_version(+ claims.run_id, claims.task_id, claims.team_id, artifact_id=claims.artifact_id, version=claims.version+ )+ if living_content is None or not tasks_facade.is_html_artifact(+ living_content.name, living_content.content_type+ ):+ raise Http404+ content = living_content.content+ if error is not None or content is None or len(content) > TASK_RUN_ARTIFACT_MAX_SIZE_BYTES:+ raise Http404+ scripts = claims.script_digest is not None and hashlib.sha256(content).hexdigest() == claims.script_digest+ response = streaming_response(+ _task_html_artifact_shim(content if scripts else _without_network_hints(content), scripts=scripts),+ content_type="text/html; charset=utf-8",+ )+ response["Content-Disposition"] = "inline"+ response["Cache-Control"] = "no-store"+ response["Referrer-Policy"] = "no-referrer"+ response["X-Content-Type-Options"] = "nosniff"+ response["Cross-Origin-Resource-Policy"] = "cross-origin"+ response["Content-Security-Policy"] = _task_html_artifact_preview_csp(scripts=scripts)+ response["Permissions-Policy"] = ARTIFACT_PERMISSIONS_POLICY+ return responsediff --git a/products/tasks/backend/tests/test_api.py b/products/tasks/backend/tests/test_api.pyindex 21dbd3008bbd..f9eb9020b9d3 100644--- a/products/tasks/backend/tests/test_api.py+++ b/products/tasks/backend/tests/test_api.py@@ -8,7 +8,7 @@ from collections.abc import AsyncGenerator, Iteratorfrom datetime import UTC, datetime, timedeltafrom decimal import Decimalfrom typing import Any, ClassVar, cast-from urllib.parse import quote+from urllib.parse import quote, urlsplitimport time_machinefrom unittest.mock import ANY, AsyncMock, MagicMock, call, patch@@ -20,6 +20,7 @@ from django.http import StreamingHttpResponsefrom django.test import SimpleTestCase, TestCase, override_settingsfrom django.test.utils import CaptureQueriesContextfrom django.utils import timezone as django_timezone+from django.utils.html import escapeimport jwtimport posthoganalytics@@ -41,6 +42,7 @@ from posthog.models.utils import generate_random_token_personalfrom posthog.ph_client import filter_scout_experiment_capturefrom posthog.scopes import MCP_BUILT_IN_AGENT_SCOPEfrom posthog.storage import object_storage+from posthog.storage.object_storage import ObjectStorageErrorfrom posthog.temporal.oauth import (ARRAY_APP_CLIENT_ID_DEV,ARRAY_APP_CLIENT_ID_US,@@ -9179,8 +9181,9 @@ class TestTaskRunAPI(BaseTaskAPITest):self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)+ @parameterized.expand([("open_base_version", True), ("restricted_base_version", False)])@patch("products.tasks.backend.logic.services.living_artifacts._slack_integration_for_mapping")- def test_living_artifact_create_open_and_edit(self, mock_integration_for_mapping):+ def test_living_artifact_create_open_and_edit(self, _name, base_open, mock_integration_for_mapping):task = self.create_task()run = TaskRun.objects.create(task=task, team=self.team, status=TaskRun.Status.IN_PROGRESS)integration = Integration.objects.create(@@ -9231,6 +9234,10 @@ class TestTaskRunAPI(BaseTaskAPITest):)self.assertEqual(open_response.status_code, status.HTTP_200_OK)self.assertEqual(open_response.json()["content"], "# Living report")+ if not base_open:+ created = TaskArtifact.objects.for_team(self.team.id).get(id=artifact["id"])+ created.versions = [{**created.versions[0], "written_with_open_network": False}]+ created.save(update_fields=["versions"])edit_response = self.client.post(f"/api/projects/@current/tasks/{task.id}/runs/{run.id}/living_artifacts/{artifact['id']}/edit/",@@ -9242,6 +9249,8 @@ class TestTaskRunAPI(BaseTaskAPITest):updated = edit_response.json()self.assertEqual(updated["current_version"], 2)self.assertEqual([version["version"] for version in updated["versions"]], [1, 2])+ stored = TaskArtifact.objects.for_team(self.team.id).get(id=artifact["id"])+ self.assertEqual([version["written_with_open_network"] for version in stored.versions], [base_open, base_open])self.assertEqual(slack.api_call.call_args_list[0].args[0], "canvases.create")self.assertEqual(slack.api_call.call_args_list[1].args[0], "canvases.edit")@@ -10247,6 +10256,521 @@ class TestTaskRunAPI(BaseTaskAPITest):self.assertIn('attachment; filename="plan.md"', response["Content-Disposition"])mock_read_bytes.assert_called_once_with(storage_path, missing_ok=True)+ @override_settings(+ CANVAS_ARTIFACT_ORIGIN="https://usercontent.example", ALLOWED_HOSTS=["testserver", "usercontent.example"]+ )+ @patch(+ "posthog.storage.object_storage.read_bytes",+ return_value=b'<link rel="preconnect" href="https://example.com"><button onclick="this.textContent=\'ready\'">Run</button>',+ )+ def test_html_artifact_preview_runs_from_isolated_origin(self, mock_read_bytes):+ task = self.create_task()+ artifact_id = uuid.uuid4().hex+ run = TaskRun.objects.create(+ task=task,+ team=self.team,+ status=TaskRun.Status.IN_PROGRESS,+ artifacts=[+ {+ "id": artifact_id,+ "name": "interactive.html",+ "type": "output",+ "source": "agent_output",+ "content_type": "text/html",+ "storage_path": f"tasks/artifacts/team_{self.team.id}/task_{task.id}/run_{uuid.uuid4().hex}/interactive.html",+ "script_sha256": hashlib.sha256(mock_read_bytes.return_value).hexdigest(),+ },+ {+ "id": "unmarked-html",+ "name": "unmarked.html",+ "type": "output",+ "source": "agent_output",+ "content_type": "text/html",+ "storage_path": "tasks/artifacts/unmarked.html",+ },+ {+ "id": "private-html",+ "name": "private.html",+ "type": "attachment",+ "content_type": "text/html",+ "storage_path": "tasks/artifacts/private.html",+ },+ ],+ )+ api_path = f"/api/projects/@current/tasks/{task.id}/runs/{run.id}/artifacts/{artifact_id}/preview/"++ static = self.client.get(api_path)+ self.assertEqual(static.status_code, status.HTTP_200_OK)+ self.assertTrue(static.json()["scripts_available"])+ static_preview = self.client.get(urlsplit(static.json()["url"]).path, HTTP_HOST="usercontent.example")+ static_csp = static_preview["Content-Security-Policy"]+ static_page = b"".join(static_preview).decode()+ self.assertIn('<iframe sandbox="" ', static_page)+ self.assertIn(escape('<meta http-equiv="x-dns-prefetch-control" content="off"><x-link rel='), static_page)+ self.assertNotIn(escape("<link"), static_page)+ self.assertIn("sandbox;", static_csp)+ self.assertIn("script-src 'none'", static_csp)+ self.assertNotIn("allow-scripts", static_csp)+ self.assertEqual(self.client.get(f"{api_path}?scripts=yes").status_code, status.HTTP_400_BAD_REQUEST)+ unmarked_path = api_path.replace(artifact_id, "unmarked-html")+ self.assertFalse(self.client.get(unmarked_path).json()["scripts_available"])+ self.assertEqual(self.client.get(f"{unmarked_path}?scripts=true").status_code, status.HTTP_403_FORBIDDEN)++ minted = self.client.get(f"{api_path}?scripts=true")+ self.assertEqual(minted.status_code, status.HTTP_200_OK)+ preview_path = urlsplit(minted.json()["url"]).path+ preview = self.client.get(preview_path, HTTP_HOST="usercontent.example")++ self.assertEqual(preview.status_code, status.HTTP_200_OK)+ served_page = b"".join(preview).decode()+ self.assertIn(+ f'<iframe sandbox="allow-scripts" title="Artifact" srcdoc="{escape(mock_read_bytes.return_value.decode())}">',+ served_page,+ )+ self.assertNotIn(mock_read_bytes.return_value.decode(), served_page)+ self.assertEqual(preview["Cache-Control"], "no-store")+ self.assertIn("sandbox allow-scripts", preview["Content-Security-Policy"])+ self.assertIn("script-src 'unsafe-inline'", preview["Content-Security-Policy"])+ self.assertIn("frame-src 'none'", preview["Content-Security-Policy"])+ self.assertNotIn("allow-same-origin", preview["Content-Security-Policy"])+ self.assertEqual(self.client.get(preview_path).status_code, status.HTTP_404_NOT_FOUND)+ self.assertEqual(+ self.client.get(api_path.replace(artifact_id, uuid.uuid4().hex)).status_code, status.HTTP_404_NOT_FOUND+ )+ self.assertEqual(+ self.client.get(api_path.replace(artifact_id, "private-html")).status_code, status.HTTP_404_NOT_FOUND+ )++ with patch("products.tasks.backend.presentation.views.artifact_preview.cache.get", return_value=None):+ self.assertEqual(+ self.client.get(preview_path, HTTP_HOST="usercontent.example").status_code, status.HTTP_404_NOT_FOUND+ )++ @parameterized.expand([("finalized_upload", "upload"), ("living_slack_file_version", "living")])+ @override_settings(+ CANVAS_ARTIFACT_ORIGIN="https://usercontent.example", ALLOWED_HOSTS=["testserver", "usercontent.example"]+ )+ @patch("posthog.storage.object_storage.read_bytes")+ @patch("posthog.storage.object_storage.head_object")+ @patch("posthog.storage.object_storage.write")+ @patch("posthog.storage.object_storage.tag")+ @patch("products.tasks.backend.logic.services.living_artifacts._slack_integration_for_mapping")+ def test_html_artifact_replaced_after_it_was_saved_does_not_run_scripts(+ self, _name, writer, mock_integration_for_mapping, _mock_tag, _mock_write, mock_head_object, mock_read_bytes+ ):+ approved = b"<p>Approved report</p>"+ mock_head_object.return_value = {"ContentLength": len(approved), "ContentType": "text/html"}+ mock_read_bytes.return_value = approved+ task = self.create_task()+ run = TaskRun.objects.create(task=task, team=self.team, status=TaskRun.Status.IN_PROGRESS)+ runs_path = f"/api/projects/@current/tasks/{task.id}/runs/{run.id}"+ if writer == "upload":+ artifact_id = uuid.uuid4().hex+ saved = self.client.post(+ f"{runs_path}/artifacts/finalize_upload/",+ {+ "artifacts": [+ {+ "id": artifact_id,+ "name": "report.html",+ "type": "output",+ "source": "agent_output",+ "storage_path": f"{run.get_artifact_s3_prefix()}/{artifact_id[:8]}_report.html",+ "content_type": "text/html",+ }+ ]+ },+ format="json",+ )+ api_path = f"{runs_path}/artifacts/{artifact_id}/preview/?scripts=true"+ else:+ integration = Integration.objects.create(+ team=self.team, kind="slack", integration_id="T123", config={"scope": "chat:write,files:write"}+ )+ SlackThreadTaskMapping.objects.create(+ team=self.team,+ integration=integration,+ slack_workspace_id="T123",+ channel="C123",+ thread_ts="1111.1",+ task=task,+ task_run=run,+ mentioning_slack_user_id="U123",+ )+ slack_integration = MagicMock()+ slack_integration.missing_scopes.return_value = set()+ mock_integration_for_mapping.return_value = slack_integration+ saved = self.client.post(+ f"{runs_path}/living_artifacts/",+ {+ "name": "report.html",+ "artifact_type": "file",+ "adapter": "slack_file",+ "content_base64": base64.b64encode(approved).decode("ascii"),+ "content_type": "text/html",+ },+ format="json",+ )+ api_path = f"{runs_path}/artifacts/{saved.json()['id']}/preview/?version=1&scripts=true"+ self.assertEqual(saved.status_code, status.HTTP_200_OK)++ def served_csp() -> str:+ minted = self.client.get(api_path)+ self.assertEqual(minted.status_code, status.HTTP_200_OK)+ served = self.client.get(urlsplit(minted.json()["url"]).path, HTTP_HOST="usercontent.example")+ self.assertIn(escape(mock_read_bytes.return_value.decode()), b"".join(served).decode())+ return served["Content-Security-Policy"]++ self.assertIn("sandbox allow-scripts", served_csp())+ mock_read_bytes.return_value = b"<script>location.replace('https://attacker.example/')</script>"+ self.assertNotIn("allow-scripts", served_csp())++ if writer == "living":+ edited = self.client.post(+ f"{runs_path}/living_artifacts/{saved.json()['id']}/edit/",+ {+ "content_base64": base64.b64encode(b"<p>Fixed a typo</p>").decode("ascii"),+ "content_type": "text/html",+ },+ format="json",+ )+ self.assertEqual(edited.status_code, status.HTTP_200_OK, edited.content)+ preview = self.client.get(f"{runs_path}/artifacts/{saved.json()['id']}/preview/?version=2")+ self.assertEqual(preview.status_code, status.HTTP_200_OK)+ self.assertFalse(preview.json()["scripts_available"])++ @parameterized.expand(+ [+ ("edit_of_an_open_file", "upload_edit", "match", True),+ ("edit_of_a_restricted_file", "upload_edit", None, False),+ ("desktop_edit_of_an_open_file", "upload_edit_without_base", "match", True),+ ("desktop_edit_of_a_restricted_file", "upload_edit_without_base", None, False),+ ("inline_upload_over_an_open_file", "inline_upload", "match", True),+ ("inline_upload_over_a_restricted_file", "inline_upload", None, False),+ ("inline_upload_over_an_open_file_replaced_after_save", "inline_upload", "stale", False),+ ("edit_of_an_open_file_replaced_after_save", "upload_edit", "stale", False),+ ("edit_over_the_hash_budget", "upload_edit_over_budget", "match", False),+ ("new_file_whose_read_fails", "upload_new_file_read_fails", "match", False),+ ("living_copy_of_an_open_file", "living_copy", "match", True),+ ("living_copy_of_a_restricted_file", "living_copy", None, False),+ ("living_copy_of_an_open_file_replaced_after_save", "living_copy", "stale", False),+ ]+ )+ @override_settings(+ CANVAS_ARTIFACT_ORIGIN="https://usercontent.example", ALLOWED_HOSTS=["testserver", "usercontent.example"]+ )+ @patch("posthog.storage.object_storage.read_bytes")+ @patch("posthog.storage.object_storage.head_object")+ @patch("posthog.storage.object_storage.write")+ @patch("posthog.storage.object_storage.tag")+ @patch("products.tasks.backend.logic.services.living_artifacts._slack_integration_for_mapping")+ def test_html_written_by_a_person_from_another_file_runs_scripts_only_when_that_file_can(+ self,+ _name,+ writer,+ base_record,+ expected_scripts,+ mock_integration_for_mapping,+ _mock_tag,+ _mock_write,+ mock_head_object,+ mock_read_bytes,+ ):+ html = b"<script>document.title = 'report'</script>"+ mock_head_object.return_value = {"ContentLength": len(html), "ContentType": "text/html"}+ mock_read_bytes.return_value = html+ task = self.create_task()+ run = TaskRun.objects.create(task=task, team=self.team, status=TaskRun.Status.IN_PROGRESS)+ base_id = uuid.uuid4().hex+ run.artifacts = [+ {+ "id": base_id,+ "name": "report.html",+ "type": "output",+ "source": "agent_output",+ "content_type": "text/html",+ "storage_path": f"{run.get_artifact_s3_prefix()}/{base_id[:8]}_report.html",+ "uploaded_at": "2026-09-28T18:00:00Z",+ "size": len(html),+ **(+ {"script_sha256": hashlib.sha256(html if base_record == "match" else b"<p>Saved</p>").hexdigest()}+ if base_record+ else {}+ ),+ }+ ]+ run.save(update_fields=["artifacts"])+ runs_path = f"/api/projects/@current/tasks/{task.id}/runs/{run.id}"+ if writer == "inline_upload":+ saved = self.client.post(+ f"{runs_path}/artifacts/",+ {+ "artifacts": [+ {"name": "report.html", "type": "output", "source": "agent_output", "content": html.decode()}+ ]+ },+ format="json",+ )+ api_path = f"{runs_path}/artifacts/{saved.json()['artifacts'][-1]['id']}/preview/"+ elif writer in (+ "upload_edit",+ "upload_edit_without_base",+ "upload_edit_over_budget",+ "upload_new_file_read_fails",+ ):+ edit_id = uuid.uuid4().hex+ edit_name = "other.html" if writer == "upload_new_file_read_fails" else "report.html"+ if writer == "upload_new_file_read_fails":+ mock_read_bytes.side_effect = ObjectStorageError("timed out")+ budget = 1 if writer == "upload_edit_over_budget" else tasks_facade.ARTIFACT_SCRIPT_HASH_BUDGET_BYTES+ with patch.object(tasks_facade, "ARTIFACT_SCRIPT_HASH_BUDGET_BYTES", budget):+ saved = self.client.post(+ f"{runs_path}/artifacts/finalize_upload/",+ {+ "artifacts": [+ {+ "id": edit_id,+ "name": edit_name,+ "type": "output",+ "storage_path": f"{run.get_artifact_s3_prefix()}/{edit_id[:8]}_{edit_name}",+ "content_type": "text/html",+ **({"base_artifact_id": base_id} if writer == "upload_edit" else {}),+ }+ ]+ },+ format="json",+ )+ api_path = f"{runs_path}/artifacts/{edit_id}/preview/"+ else:+ integration = Integration.objects.create(+ team=self.team, kind="slack", integration_id="T123", config={"scope": "chat:write,files:write"}+ )+ SlackThreadTaskMapping.objects.create(+ team=self.team,+ integration=integration,+ slack_workspace_id="T123",+ channel="C123",+ thread_ts="1111.1",+ task=task,+ task_run=run,+ mentioning_slack_user_id="U123",+ )+ slack_integration = MagicMock()+ slack_integration.missing_scopes.return_value = set()+ mock_integration_for_mapping.return_value = slack_integration+ saved = self.client.post(+ f"{runs_path}/living_artifacts/",+ {+ "name": "report.html",+ "artifact_type": "file",+ "adapter": "slack_file",+ "source_artifact_id": base_id,+ },+ format="json",+ )+ api_path = f"{runs_path}/artifacts/{saved.json()['id']}/preview/?version=1"+ self.assertEqual(saved.status_code, status.HTTP_200_OK, saved.content)++ preview = self.client.get(api_path)++ self.assertEqual(preview.status_code, status.HTTP_200_OK)+ self.assertEqual(preview.json()["scripts_available"], expected_scripts)++ @override_settings(+ CANVAS_ARTIFACT_ORIGIN="https://usercontent.example", ALLOWED_HOSTS=["testserver", "usercontent.example"]+ )+ def test_html_living_artifact_preview_uses_selected_version(self):+ task = self.create_task()+ run = TaskRun.objects.create(task=task, team=self.team, status=TaskRun.Status.IN_PROGRESS)+ artifact = self._create_slack_file_living_artifact(task, run)+ artifact.name = "interactive.html"+ versions = artifact.versions+ versions[1]["content_type"] = "text/html"+ versions[1]["content"] = "<script>document.body.textContent = 'ready'</script>"+ artifact.versions = versions+ artifact.save(update_fields=["name", "versions"])++ api_path = f"/api/projects/@current/tasks/{task.id}/runs/{run.id}/artifacts/{artifact.id}/preview/"+ minted = self.client.get(f"{api_path}?version=2")+ self.assertEqual(minted.status_code, status.HTTP_200_OK)+ preview_path = urlsplit(minted.json()["url"]).path+ preview = self.client.get(preview_path, HTTP_HOST="usercontent.example")+ self.assertEqual(preview.status_code, status.HTTP_200_OK)+ self.assertIn(escape(versions[1]["content"]), b"".join(preview).decode())+ self.assertEqual(self.client.get(f"{api_path}?version=1").status_code, status.HTTP_404_NOT_FOUND)+ self.assertEqual(self.client.get(f"{api_path}?version={'9' * 21}").status_code, status.HTTP_400_BAD_REQUEST)++ @parameterized.expand(+ [+ ("agent_without_environment", "agent", None, 1, True),+ ("agent_with_full_network", "agent", SandboxEnvironment.NetworkAccessLevel.FULL, 1, True),+ ("agent_with_trusted_network", "agent", SandboxEnvironment.NetworkAccessLevel.TRUSTED, 1, False),+ ("agent_with_custom_network", "agent", SandboxEnvironment.NetworkAccessLevel.CUSTOM, 1, False),+ ("agent_environment_changed_after_run", "agent", SandboxEnvironment.NetworkAccessLevel.FULL, -1, False),+ ("agent_environment_deleted", "agent", "deleted", 1, False),+ ("human_on_restricted_run", "human", SandboxEnvironment.NetworkAccessLevel.TRUSTED, 1, True),+ ("other_oauth_application", "oauth_app", None, 1, False),+ ]+ )+ @override_settings(+ CANVAS_ARTIFACT_ORIGIN="https://usercontent.example", ALLOWED_HOSTS=["testserver", "usercontent.example"]+ )+ @patch("posthog.storage.object_storage.write")+ @patch("posthog.storage.object_storage.tag")+ def test_html_artifact_scripts_follow_the_network_access_of_the_writer(+ self, _name, writer, network_access_level, run_started_minutes_after_environment, scripts_available, *_mocks+ ):+ task = self.create_task()+ state: dict[str, Any] = {}+ environment = None+ if network_access_level is not None:+ environment = SandboxEnvironment.objects.create(+ team=self.team,+ name="Writer env",+ created_by=self.user,+ network_access_level=SandboxEnvironment.NetworkAccessLevel.FULL+ if network_access_level == "deleted"+ else network_access_level,+ )+ state["sandbox_environment_id"] = str(environment.id)+ run = TaskRun.objects.create(+ task=task,+ team=self.team,+ status=TaskRun.Status.IN_PROGRESS,+ state=state,+ created_at=(environment.updated_at if environment else django_timezone.now())+ + timedelta(minutes=run_started_minutes_after_environment),+ )+ client = {+ "agent": lambda: self._sandbox_oauth_client(task.id),+ "oauth_app": lambda: self._sandbox_oauth_client(task.id, client_id="third-party-app", bound=False),+ }.get(writer, lambda: self.client)()+ if network_access_level == "deleted":+ assert environment is not None+ environment.delete()+ uploaded = client.post(+ f"/api/projects/@current/tasks/{task.id}/runs/{run.id}/artifacts/",+ {+ "artifacts": [+ {"name": "report.html", "type": "output", "source": "agent_output", "content": "<p>Report</p>"}+ ]+ },+ format="json",+ )+ self.assertEqual(uploaded.status_code, status.HTTP_200_OK)+ api_path = (+ f"/api/projects/@current/tasks/{task.id}/runs/{run.id}/artifacts/"+ f"{uploaded.json()['artifacts'][0]['id']}/preview/"+ )++ static = self.client.get(api_path)+ scripted = self.client.get(f"{api_path}?scripts=true")++ self.assertEqual(static.status_code, status.HTTP_200_OK)+ self.assertEqual(static.json()["scripts_available"], scripts_available)+ self.assertEqual(scripted.status_code, status.HTTP_200_OK if scripts_available else status.HTTP_403_FORBIDDEN)++ @override_settings(+ CANVAS_ARTIFACT_ORIGIN="https://usercontent.example", ALLOWED_HOSTS=["testserver", "usercontent.example"]+ )+ def test_html_living_artifact_preview_requires_analytics_scopes_of_the_whole_task(self):+ task = self.create_task()+ protected_run = TaskRun.objects.create(+ task=task, team=self.team, state={"analytics_query_context": [TASK_ANALYTICS_QUERY]}+ )+ open_run = TaskRun.objects.create(task=task, team=self.team, status=TaskRun.Status.IN_PROGRESS)+ artifact = self._create_slack_file_living_artifact(task, protected_run)+ artifact.name = "report.html"+ versions = artifact.versions+ versions[1]["content_type"] = "text/html"+ artifact.versions = versions+ artifact.save(update_fields=["name", "versions"])+ raw_key = generate_random_token_personal()+ PersonalAPIKey.objects.create(+ label="Preview reader", user=self.user, secure_value=hash_key_value(raw_key), scopes=["task:read"]+ )+ self.client.logout()+ self.client.credentials(HTTP_AUTHORIZATION=f"Bearer {raw_key}")++ response = self.client.get(+ f"/api/projects/@current/tasks/{task.id}/runs/{open_run.id}/artifacts/{artifact.id}/preview/?version=2"+ )++ self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN)++ @parameterized.expand(+ [+ ("own_run", "own"),+ ("sibling_run_without_environment", "sibling"),+ ("run_of_another_task", "other_task"),+ ("own_run_after_removing_the_restriction", "removed"),+ ("own_run_after_pointing_at_an_open_environment", "repointed"),+ ]+ )+ @override_settings(+ CANVAS_ARTIFACT_ORIGIN="https://usercontent.example", ALLOWED_HOSTS=["testserver", "usercontent.example"]+ )+ @patch("posthog.storage.object_storage.write")+ @patch("posthog.storage.object_storage.tag")+ @patch("products.tasks.backend.models.TaskRun.publish_stream_state_event")+ def test_html_artifact_from_a_restricted_agent_never_runs_scripts(self, _name, target, *_mocks):+ open_environment = SandboxEnvironment.objects.create(+ team=self.team,+ name="Open env",+ created_by=self.user,+ network_access_level=SandboxEnvironment.NetworkAccessLevel.FULL,+ )+ restricted_environment = SandboxEnvironment.objects.create(+ team=self.team,+ name="Restricted env",+ created_by=self.user,+ network_access_level=SandboxEnvironment.NetworkAccessLevel.TRUSTED,+ )+ task = self.create_task()+ other_task = self.create_task()+ sibling_run = TaskRun.objects.create(task=task, team=self.team, status=TaskRun.Status.COMPLETED)+ other_run = TaskRun.objects.create(task=other_task, team=self.team, status=TaskRun.Status.IN_PROGRESS)+ restricted_run = TaskRun.objects.create(+ task=task,+ team=self.team,+ status=TaskRun.Status.IN_PROGRESS,+ state={"sandbox_environment_id": str(restricted_environment.id)},+ )+ agent = self._sandbox_oauth_client(task.id)+ run_path = f"/api/projects/@current/tasks/{task.id}/runs/{restricted_run.id}/"+ state_change = {+ "removed": {"state_remove_keys": ["sandbox_environment_id"]},+ "repointed": {"state": {"sandbox_environment_id": str(open_environment.id)}},+ }.get(target)+ if state_change is not None:+ patched = agent.patch(run_path, state_change, format="json")+ self.assertEqual(patched.status_code, status.HTTP_200_OK, patched.content)+ target_task, target_run = {+ "sibling": (task, sibling_run),+ "other_task": (other_task, other_run),+ }.get(target, (task, restricted_run))+ uploaded = agent.post(+ f"/api/projects/@current/tasks/{target_task.id}/runs/{target_run.id}/artifacts/",+ {+ "artifacts": [+ {"name": "report.html", "type": "output", "source": "agent_output", "content": "<p>Report</p>"}+ ]+ },+ format="json",+ )+ self.assertEqual(uploaded.status_code, status.HTTP_200_OK)+ api_path = (+ f"/api/projects/@current/tasks/{target_task.id}/runs/{target_run.id}/artifacts/"+ f"{uploaded.json()['artifacts'][0]['id']}/preview/"+ )++ static = self.client.get(api_path)+ scripted = self.client.get(f"{api_path}?scripts=true")++ self.assertEqual(static.status_code, status.HTTP_200_OK)+ self.assertFalse(static.json()["scripts_available"])+ self.assertEqual(scripted.status_code, status.HTTP_403_FORBIDDEN)+def test_download_artifact_not_found(self):task = self.create_task()run = TaskRun.objects.create(task=task, team=self.team, status=TaskRun.Status.IN_PROGRESS, artifacts=[])diff --git a/products/tasks/frontend/generated/api.schemas.ts b/products/tasks/frontend/generated/api.schemas.tsindex 35b65c82cf77..fd1fd44134c2 100644--- a/products/tasks/frontend/generated/api.schemas.ts+++ b/products/tasks/frontend/generated/api.schemas.ts@@ -3504,6 +3504,13 @@ export interface TaskRunArtifactsUploadResponseApi {artifacts: TaskRunArtifactResponseApi[]}+export interface TaskRunArtifactPreviewResponseApi {+ /** Short-lived URL for the isolated HTML preview */+ url: string+ /** Whether the caller can request a preview that runs scripts. False when whoever wrote this artifact version had limited network access, or when the version has no record of it. */+ scripts_available: boolean+}+export interface TaskRunArtifactsDismissRequestApi {/*** Manifest ids of the artifacts to update. Pass every version of a file together so the whole file is dismissed rather than a single upload of it.@@ -3564,6 +3571,11 @@ export interface TaskRunArtifactFinalizeUploadApi {content_type?: string/** Skill bundle metadata, required when the artifact type is skill_bundle. */metadata?: TaskRunSkillBundleMetadataApi+ /**+ * ID of the artifact in the same run that this file edits. An HTML edit can run scripts only when its base artifact can.+ * @maxLength 255+ */+ base_artifact_id?: string}export interface TaskRunArtifactsFinalizeUploadRequestApi {@@ -5601,6 +5613,17 @@ export type TasksRunsListParams = {offset?: number}+export type TasksRunsArtifactsPreviewRetrieveParams = {+ /**+ * Return a URL whose page runs its scripts. Without it the page renders with scripts off. Refused when scripts_available is false.+ */+ scripts?: boolean+ /**+ * Living artifact version+ */+ version?: number+}+export type TasksRunsSessionLogsRetrieveParams = {/*** Only return events after this ISO8601 timestampdiff --git a/products/tasks/frontend/generated/api.ts b/products/tasks/frontend/generated/api.tsindex 676eef567d48..0499f3f9fddc 100644--- a/products/tasks/frontend/generated/api.ts+++ b/products/tasks/frontend/generated/api.ts@@ -89,6 +89,7 @@ import type {TaskRunAppendLogRequestApi,TaskRunArtifactPresignRequestApi,TaskRunArtifactPresignResponseApi,+ TaskRunArtifactPreviewResponseApi,TaskRunArtifactsDismissRequestApi,TaskRunArtifactsDismissResponseApi,TaskRunArtifactsFinalizeUploadRequestApi,@@ -142,6 +143,7 @@ import type {TasksListParams,TasksRepositoryReadinessRetrieveParams,TasksReviewRetrieveParams,+ TasksRunsArtifactsPreviewRetrieveParams,TasksRunsListParams,TasksRunsLivingArtifactsVersionContentParams,TasksRunsSessionLogsRetrieveParams,@@ -1733,6 +1735,49 @@ export const tasksRunsArtifactsDownloadRetrieve = async (})}+export const getTasksRunsArtifactsPreviewRetrieveUrl = (+ projectId: string,+ taskId: string,+ id: string,+ artifactId: string,+ params?: TasksRunsArtifactsPreviewRetrieveParams+) => {+ const normalizedParams = new URLSearchParams()++ Object.entries(params || {}).forEach(([key, value]) => {+ if (value !== undefined) {+ normalizedParams.append(key, value === null ? 'null' : String(value))+ }+ })++ const stringifiedParams = normalizedParams.toString()++ return stringifiedParams.length > 0+ ? `/api/projects/${projectId}/tasks/${taskId}/runs/${id}/artifacts/${artifactId}/preview/?${stringifiedParams}`+ : `/api/projects/${projectId}/tasks/${taskId}/runs/${id}/artifacts/${artifactId}/preview/`+}++/**+ * Returns a short-lived URL for one HTML artifact version on the artifact origin. The page runs its scripts only when scripts=true.+ * @summary Open an isolated HTML artifact preview+ */+export const tasksRunsArtifactsPreviewRetrieve = async (+ projectId: string,+ taskId: string,+ id: string,+ artifactId: string,+ params?: TasksRunsArtifactsPreviewRetrieveParams,+ options?: RequestInit+): Promise<TaskRunArtifactPreviewResponseApi> => {+ return apiMutator<TaskRunArtifactPreviewResponseApi>(+ getTasksRunsArtifactsPreviewRetrieveUrl(projectId, taskId, id, artifactId, params),+ {+ ...options,+ method: 'GET',+ }+ )+}+export const getTasksRunsArtifactsDismissCreateUrl = (projectId: string, taskId: string, id: string) => {return `/api/projects/${projectId}/tasks/${taskId}/runs/${id}/artifacts/dismiss/`}diff --git a/products/tasks/frontend/generated/api.zod.ts b/products/tasks/frontend/generated/api.zod.tsindex 45be53f28479..b9da1c367053 100644--- a/products/tasks/frontend/generated/api.zod.ts+++ b/products/tasks/frontend/generated/api.zod.ts@@ -2369,6 +2369,8 @@ export const tasksRunsArtifactsFinalizeUploadCreateBodyArtifactsItemMetadataOneC'^[a-f0-9]{64}$')+export const tasksRunsArtifactsFinalizeUploadCreateBodyArtifactsItemBaseArtifactIdMax = 255+export const TasksRunsArtifactsFinalizeUploadCreateBody = /* @__PURE__ */ zod.object({artifacts: zod.array(@@ -2440,6 +2442,13 @@ export const TasksRunsArtifactsFinalizeUploadCreateBody = /* @__PURE__ */ zod.ob}).optional().describe('Skill bundle metadata, required when the artifact type is skill_bundle.'),+ base_artifact_id: zod+ .string()+ .max(tasksRunsArtifactsFinalizeUploadCreateBodyArtifactsItemBaseArtifactIdMax)+ .optional()+ .describe(+ 'ID of the artifact in the same run that this file edits. An HTML edit can run scripts only when its base artifact can.'+ ),})).describe('Array of uploaded artifacts to finalize'),diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.tsindex b665726bdf27..4d7c750c76bd 100644--- a/services/mcp/src/api/generated.ts+++ b/services/mcp/src/api/generated.ts@@ -109517,6 +109517,11 @@ export namespace Schemas {content_type?: string;/** Skill bundle metadata, required when the artifact type is skill_bundle. */metadata?: TaskRunSkillBundleMetadata;+ /**+ * ID of the artifact in the same run that this file edits. An HTML edit can run scripts only when its base artifact can.+ * @maxLength 255+ */+ base_artifact_id?: string;}export interface TaskRunArtifactPrepareUpload {@@ -109594,6 +109599,13 @@ export namespace Schemas {expires_in: number;}+ export interface TaskRunArtifactPreviewResponse {+ /** Short-lived URL for the isolated HTML preview */+ url: string;+ /** Whether the caller can request a preview that runs scripts. False when whoever wrote this artifact version had limited network access, or when the version has no record of it. */+ scripts_available: boolean;+ }+export interface TaskRunArtifactUpload {/*** File name to associate with the artifact@@ -130365,6 +130377,17 @@ export namespace Schemas {offset?: number;};+ export type TasksRunsArtifactsPreviewRetrieveParams = {+ /**+ * Return a URL whose page runs its scripts. Without it the page renders with scripts off. Refused when scripts_available is false.+ */+ scripts?: boolean;+ /**+ * Living artifact version+ */+ version?: number;+ };+export type TasksRunsSessionLogsRetrieveParams = {/*** Only return events after this ISO8601 timestamp