: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(desktop): render local task images (#101233)
Mikayla Thompson9e220219d18f
diff --git a/products/desktop/apps/code/src/main/index.ts b/products/desktop/apps/code/src/main/index.tsindex f44c3bc237bc..8ff38dd84b9f 100644--- a/products/desktop/apps/code/src/main/index.ts+++ b/products/desktop/apps/code/src/main/index.ts@@ -41,6 +41,10 @@ import type { UpdatesService } from "@posthog/core/updates/updates";import { ENVIRONMENT_CLIENT } from "@posthog/host-router/ports/environment-client";import { FILE_WATCHER_CONTROL } from "@posthog/host-router/ports/file-watcher-control";import { DISK_CACHE_SERVICE } from "@posthog/platform/disk-cache";+import {+ type IImageProcessor,+ IMAGE_PROCESSOR_SERVICE,+} from "@posthog/platform/image-processor";import { ANALYTICS_EVENTS } from "@posthog/shared/analytics-events";import type { DatabaseService } from "@posthog/workspace-server/db/service";import type { ExternalAppsService } from "@posthog/workspace-server/services/external-apps/external-apps";@@ -407,6 +411,9 @@ async function boot(): Promise<void> {container.bind(FOCUS_SESSION_STORE).toConstantValue(focusSessionStore);container.bind(FOCUS_WORKTREE_PATHS).toConstantValue(focusWorktreePaths);container.load(focusHostModule);+ const imageProcessor = container.get<IImageProcessor>(+ IMAGE_PROCESSOR_SERVICE,+ );const fsCapability: FsCapability = {listRepoFiles: (repoPath, query, limit) =>workspaceClient.fs.listRepoFiles.query({ repoPath, query, limit }),@@ -430,6 +437,32 @@ async function boot(): Promise<void> {workspaceClient.fs.readAbsoluteFile.query({ filePath }),readFileAsBase64: (filePath) =>workspaceClient.fs.readFileAsBase64.query({ filePath }),+ readWorkspaceImageDataUrl: async (workspaceRoot, filePath) => {+ const base64 = await workspaceClient.fs.readWorkspaceFileAsBase64.query({+ workspaceRoot,+ filePath,+ });+ if (!base64) return null;+ const extension = filePath.match(/\.([A-Za-z0-9]+)$/)?.[1]?.toLowerCase();+ const mimeType = extension+ ? {+ avif: "image/avif",+ gif: "image/gif",+ jpeg: "image/jpeg",+ jpg: "image/jpeg",+ png: "image/png",+ webp: "image/webp",+ }[extension]+ : undefined;+ if (!mimeType) return null;+ const image = imageProcessor.downscale(+ Buffer.from(base64, "base64"),+ mimeType,+ { maxDimension: 1568, jpegQuality: 85 },+ );+ const resizedBase64 = Buffer.from(image.buffer).toString("base64");+ return `data:${image.mimeType};base64,${resizedBase64}`;+ },writeRepoFile: async (repoPath, filePath, content) => {await workspaceClient.fs.writeRepoFile.mutate({repoPath,diff --git a/products/desktop/docs/TROUBLESHOOTING.md b/products/desktop/docs/TROUBLESHOOTING.mdindex 1b5a38c65457..d378b8bdb518 100644--- a/products/desktop/docs/TROUBLESHOOTING.md+++ b/products/desktop/docs/TROUBLESHOOTING.md@@ -1,5 +1,11 @@# Troubleshooting+## An image in a local task does not load++Local task messages can show PNG, JPEG, GIF, WebP, and AVIF files that are inside the task workspace. Use an absolute workspace path or a path relative to the workspace. Images outside the workspace and remote image URLs stay blocked.++Cloud task files are not on your computer. Upload those files as task artifacts before you link to them.+## Conversation is too large to continueA request can exceed the size limit when a conversation contains large images or tool output.diff --git a/products/desktop/packages/host-router/src/routers/fs.router.ts b/products/desktop/packages/host-router/src/routers/fs.router.tsindex 1f1fc731a047..77fa97acce5c 100644--- a/products/desktop/packages/host-router/src/routers/fs.router.ts+++ b/products/desktop/packages/host-router/src/routers/fs.router.ts@@ -15,6 +15,7 @@ import {readRepoFilesBoundedOutput,readRepoFilesInput,readRepoFilesOutput,+ readWorkspaceFileInput,writeRepoFileInput,} from "@posthog/workspace-server/services/fs/schemas";@@ -82,6 +83,15 @@ export const fsRouter = router({.readFileAsBase64(input.filePath),),+ readWorkspaceFileAsBase64: publicProcedure+ .input(readWorkspaceFileInput)+ .output(readRepoFileOutput)+ .query(({ ctx, input }) =>+ ctx.container+ .get<FsCapability>(FS_SERVICE)+ .readWorkspaceImageDataUrl(input.workspaceRoot, input.filePath),+ ),+writeRepoFile: publicProcedure.input(writeRepoFileInput).mutation(({ ctx, input }) =>diff --git a/products/desktop/packages/ui/src/features/code-editor/hooks/useFileContent.ts b/products/desktop/packages/ui/src/features/code-editor/hooks/useFileContent.tsindex 37f598b06777..da20f7f58c96 100644--- a/products/desktop/packages/ui/src/features/code-editor/hooks/useFileContent.ts+++ b/products/desktop/packages/ui/src/features/code-editor/hooks/useFileContent.ts@@ -52,3 +52,21 @@ export function useFileAsBase64(filePath: string, enabled: boolean) {),);}++export function useWorkspaceFileAsBase64(+ workspaceRoot: string,+ filePath: string,+ enabled: boolean,+) {+ const trpc = useHostTRPC();+ return useQuery(+ trpc.fs.readWorkspaceFileAsBase64.queryOptions(+ { workspaceRoot, filePath },+ {+ enabled,+ staleTime: Number.POSITIVE_INFINITY,+ gcTime: FILE_CONTENT_GC_MS,+ },+ ),+ );+}diff --git a/products/desktop/packages/ui/src/features/sessions/components/chat-thread/ChatMarkdown.test.tsx b/products/desktop/packages/ui/src/features/sessions/components/chat-thread/ChatMarkdown.test.tsxindex 4c47417afd02..38506f733a08 100644--- a/products/desktop/packages/ui/src/features/sessions/components/chat-thread/ChatMarkdown.test.tsx+++ b/products/desktop/packages/ui/src/features/sessions/components/chat-thread/ChatMarkdown.test.tsx@@ -63,8 +63,28 @@ vi.mock("@posthog/ui/features/sidebar/useCwd", () => ({useCwd: () => "/repo",}));+const { useWorkspaceFileAsBase64 } = vi.hoisted(() => ({+ useWorkspaceFileAsBase64: vi.fn<+ (+ workspaceRoot: string,+ filePath: string,+ enabled: boolean,+ ) => {+ data: string | null;+ isPending: boolean;+ }+ >(() => ({ data: null, isPending: false })),+}));+vi.mock("@posthog/ui/features/code-editor/hooks/useFileContent", () => ({+ useWorkspaceFileAsBase64,+}));+import { SessionTaskIdProvider } from "@posthog/ui/features/sessions/useSessionTaskId";-import { ChatMarkdown, ChatStreamingMarkdown } from "./ChatMarkdown";+import {+ ChatMarkdown,+ ChatStreamingMarkdown,+ resolveLocalImage,+} from "./ChatMarkdown";const MERMAID_FENCE = "```mermaid\ngraph TD; A-->B\n```";@@ -103,6 +123,27 @@ Verdict: valid.expect(html).not.toContain("http://127.0.0.1/action");});+ it("renders local workspace images from the filesystem", () => {+ useWorkspaceFileAsBase64.mockReturnValue({+ data: "aGVsbG8=",+ isPending: false,+ });++ const html = renderStatic(+ <SessionTaskIdProvider taskId="task-1">+ <ChatMarkdown content="" />+ </SessionTaskIdProvider>,+ );++ expect(html).toContain('src="data:image/png;base64,aGVsbG8="');+ expect(html).toContain('alt="Agent list"');+ expect(useWorkspaceFileAsBase64).toHaveBeenCalledWith(+ "/repo",+ "/repo/.qa/agent-list.png",+ true,+ );+ });+it("renders a GitHub pull request with its live status chip", () => {const html = renderStatic(<ChatMarkdown content="Review https://github.com/PostHog/posthog/pull/23985" />,@@ -127,6 +168,28 @@ Verdict: valid.});});+describe("resolveLocalImage", () => {+ it("resolves relative and absolute images inside the workspace", () => {+ expect(resolveLocalImage("screenshots/result.webp", "/repo")).toEqual({+ path: "/repo/screenshots/result.webp",+ mimeType: "image/webp",+ });+ expect(resolveLocalImage("/repo/result.png", "/repo")).toEqual({+ path: "/repo/result.png",+ mimeType: "image/png",+ });+ });++ it("rejects paths outside the workspace and unsupported image types", () => {+ expect(resolveLocalImage("../secret.png", "/repo")).toBeNull();+ expect(resolveLocalImage("/other/secret.png", "/repo")).toBeNull();+ expect(resolveLocalImage("diagram.svg", "/repo")).toBeNull();+ expect(+ resolveLocalImage("https://example.com/image.png", "/repo"),+ ).toBeNull();+ });+});+describe("ChatMarkdown object tags", () => {// The chat thread has its own sanitized renderer, which silently dropped// object tags while the session view rendered them; these lock the threaddiff --git a/products/desktop/packages/ui/src/features/sessions/components/chat-thread/ChatMarkdown.tsx b/products/desktop/packages/ui/src/features/sessions/components/chat-thread/ChatMarkdown.tsxindex 87d418889c74..5d8335d62f55 100644--- a/products/desktop/packages/ui/src/features/sessions/components/chat-thread/ChatMarkdown.tsx+++ b/products/desktop/packages/ui/src/features/sessions/components/chat-thread/ChatMarkdown.tsx@@ -10,6 +10,8 @@ import {TableRow,Text,} from "@posthog/quill";+import { buildImageDataUrl } from "@posthog/shared";+import { useWorkspaceFileAsBase64 } from "@posthog/ui/features/code-editor/hooks/useFileContent";import { ArtifactRefChip } from "@posthog/ui/features/editor/components/ArtifactRefChip";import { EvidenceRefChip } from "@posthog/ui/features/editor/components/EvidenceRefChip";import { githubRefChipFor } from "@posthog/ui/features/editor/components/githubRefChipFor";@@ -25,6 +27,8 @@ import {InlineFileLink,looksLikeBareFilename,} from "@posthog/ui/features/sessions/components/session-update/fileLinkChips";+import { useSessionTaskId } from "@posthog/ui/features/sessions/useSessionTaskId";+import { useCwd } from "@posthog/ui/features/sidebar/useCwd";import { useThrottledValue } from "@posthog/ui/hooks/useThrottledValue";import { HighlightedCode } from "@posthog/ui/primitives/HighlightedCode";import { MermaidDiagram } from "@posthog/ui/primitives/MermaidDiagram";@@ -49,6 +53,108 @@ import type { PluggableList } from "unified";const PENDING_LINK_DESTINATION = "#posthog-streaming-link";+const LOCAL_IMAGE_MIME_TYPES: Record<string, string> = {+ avif: "image/avif",+ gif: "image/gif",+ jpeg: "image/jpeg",+ jpg: "image/jpeg",+ png: "image/png",+ webp: "image/webp",+};++function normalizeLocalPath(value: string): string | null {+ let decoded: string;+ try {+ decoded = decodeURIComponent(value);+ } catch {+ return null;+ }+ const normalized = decoded.replaceAll("\\\\", "/");+ const prefix = normalized.match(/^(?:[A-Za-z]:|\/)/)?.[0];+ if (!prefix) return null;++ const parts: string[] = [];+ for (const part of normalized.slice(prefix.length).split("/")) {+ if (!part || part === ".") continue;+ if (part === "..") {+ if (!parts.pop()) return null;+ } else {+ parts.push(part);+ }+ }+ return `${prefix}${prefix === "/" ? "" : "/"}${parts.join("/")}`;+}++export function resolveLocalImage(+ source: string | undefined,+ cwd: string | undefined,+): { path: string; mimeType: string } | null {+ if (!source || !cwd) return null;+ if (+ /^[A-Za-z][A-Za-z0-9+.-]*:/.test(source) &&+ !/^[A-Za-z]:[\\/]/.test(source)+ ) {+ return null;+ }+ const normalizedCwd = normalizeLocalPath(cwd);+ if (!normalizedCwd) return null;+ const sourceWithRoot = /^(?:[A-Za-z]:[\\/]|\/)/.test(source)+ ? source+ : `${normalizedCwd}/${source}`;+ const path = normalizeLocalPath(sourceWithRoot);+ if (+ !path ||+ (path !== normalizedCwd && !path.startsWith(`${normalizedCwd}/`))+ ) {+ return null;+ }+ const extension = path.match(/\.([A-Za-z0-9]+)$/)?.[1]?.toLowerCase();+ const mimeType = extension ? LOCAL_IMAGE_MIME_TYPES[extension] : undefined;+ return mimeType ? { path, mimeType } : null;+}++function LocalMarkdownImage({+ src,+ alt,+}: {+ src: string | undefined;+ alt: string | undefined;+}) {+ const taskId = useSessionTaskId();+ const cwd = useCwd(taskId ?? "");+ const localImage = resolveLocalImage(src, cwd);+ const image = useWorkspaceFileAsBase64(+ cwd ?? "",+ localImage?.path ?? "",+ Boolean(taskId && localImage),+ );++ if (!localImage) {+ return (+ <Text className="text-muted-foreground text-sm">+ Remote image blocked{alt ? `: ${alt}` : ""}+ </Text>+ );+ }+ if (image.isPending) {+ return <Spinner size="sm" aria-label={alt || "Loading image"} />;+ }+ if (!image.data) {+ return (+ <Text className="text-muted-foreground text-sm">+ Failed to load image{alt ? `: ${alt}` : ""}+ </Text>+ );+ }+ return (+ <img+ src={buildImageDataUrl(localImage.mimeType, image.data)}+ alt={alt ?? ""}+ className="max-h-[32rem] max-w-full rounded-md border border-border object-contain"+ />+ );+}+function ChatCodeBlock({code,children,@@ -125,11 +231,7 @@ const components: Components = {</ArtifactRefChip>);},- img: ({ alt }) => (- <Text className="text-muted-foreground text-sm">- Remote image blocked{alt ? `: ${alt}` : ""}- </Text>- ),+ img: ({ alt, src }) => <LocalMarkdownImage src={src} alt={alt} />,ul: ({ children }) => (<ul className="list-disc space-y-0.5 ps-4">{children}</ul>),diff --git a/products/desktop/packages/workspace-server/src/services/archive/archive.integration.test.ts b/products/desktop/packages/workspace-server/src/services/archive/archive.integration.test.tsindex 9ad47b7bd6c3..ecad4e2d1891 100644--- a/products/desktop/packages/workspace-server/src/services/archive/archive.integration.test.ts+++ b/products/desktop/packages/workspace-server/src/services/archive/archive.integration.test.ts@@ -1,4 +1,4 @@-import { execSync } from "node:child_process";+import { execFileSync, execSync } from "node:child_process";import { writeFileSync } from "node:fs";import fs from "node:fs/promises";import os from "node:os";@@ -51,19 +51,17 @@ async function createTempRepo(): Promise<string> {}function initializeGitRepo(dir: string): void {- execSync("git init", { cwd: dir, stdio: "pipe" });- execSync("git config user.email '[email protected]'", {- cwd: dir,- stdio: "pipe",- });- execSync("git config user.name 'Test'", { cwd: dir, stdio: "pipe" });- execSync("git config commit.gpgsign false", { cwd: dir, stdio: "pipe" });- execSync("git config tag.gpgsign false", { cwd: dir, stdio: "pipe" });+ const git = (args: string[]): void => {+ execFileSync("git", args, { cwd: dir, stdio: "pipe" });+ };+ git(["init"]);+ git(["config", "user.email", "[email protected]"]);+ git(["config", "user.name", "Test"]);+ git(["config", "commit.gpgsign", "false"]);+ git(["config", "tag.gpgsign", "false"]);writeFileSync(path.join(dir, "README.md"), "# Test Repo");- execSync("git add . && git commit -m 'Initial commit'", {- cwd: dir,- stdio: "pipe",- });+ git(["add", "."]);+ git(["commit", "-m", "Initial commit"]);}async function pathExists(p: string): Promise<boolean> {@@ -396,8 +394,7 @@ describe("ArchiveService integration", () => {it("archive and unarchive preserves branch name", () =>withTestContext({}, async (ctx) => {const branchName = "feature/my-branch";- ctx.git(`checkout -b ${branchName}`);- ctx.git("checkout -");+ ctx.git(`branch ${branchName}`);const { worktreePath } = await ctx.setupWorktree("branch", branchName);@@ -414,8 +411,7 @@ describe("ArchiveService integration", () => {it("unarchive with recreateBranch creates new branch", () =>withTestContext({}, async (ctx) => {const branchName = "feature/old-branch";- ctx.git(`checkout -b ${branchName}`);- ctx.git("checkout -");+ ctx.git(`branch ${branchName}`);const { worktreePath } = await ctx.setupWorktree("branch", branchName);await fs.writeFile(path.join(worktreePath, "work.txt"), "my work");diff --git a/products/desktop/packages/workspace-server/src/services/fs/identifiers.ts b/products/desktop/packages/workspace-server/src/services/fs/identifiers.tsindex a5ff95b891a1..f7edcf505f4e 100644--- a/products/desktop/packages/workspace-server/src/services/fs/identifiers.ts+++ b/products/desktop/packages/workspace-server/src/services/fs/identifiers.ts@@ -25,6 +25,10 @@ export interface FsCapability {): Promise<Record<string, BoundedReadResult>>;readAbsoluteFile(filePath: string): Promise<string | null>;readFileAsBase64(filePath: string): Promise<string | null>;+ readWorkspaceImageDataUrl(+ workspaceRoot: string,+ filePath: string,+ ): Promise<string | null>;writeRepoFile(repoPath: string,filePath: string,diff --git a/products/desktop/packages/workspace-server/src/services/fs/schemas.ts b/products/desktop/packages/workspace-server/src/services/fs/schemas.tsindex 116fbe017053..78c857dbf153 100644--- a/products/desktop/packages/workspace-server/src/services/fs/schemas.ts+++ b/products/desktop/packages/workspace-server/src/services/fs/schemas.ts@@ -54,6 +54,11 @@ export const readAbsoluteFileInput = z.object({filePath: z.string(),});+export const readWorkspaceFileInput = z.object({+ workspaceRoot: z.string(),+ filePath: z.string(),+});+export const writeRepoFileInput = z.object({repoPath: z.string(),filePath: z.string(),diff --git a/products/desktop/packages/workspace-server/src/services/fs/service.test.ts b/products/desktop/packages/workspace-server/src/services/fs/service.test.tsindex 0309c3ca4ffe..f463915e9445 100644--- a/products/desktop/packages/workspace-server/src/services/fs/service.test.ts+++ b/products/desktop/packages/workspace-server/src/services/fs/service.test.ts@@ -1,4 +1,4 @@-import { mkdtemp, readFile, rm } from "node:fs/promises";+import { mkdtemp, readFile, rm, symlink, writeFile } from "node:fs/promises";import { tmpdir } from "node:os";import path from "node:path";import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";@@ -111,6 +111,32 @@ describe("FsService repo file IO", () => {).rejects.toThrow(/Access denied/);});+ it("refuses workspace image reads through an external symlink", async () => {+ const external = await mkdtemp(path.join(tmpdir(), "fs-service-external-"));+ const externalImage = path.join(external, "secret.png");+ const linkedImage = path.join(repo, "linked.png");+ await writeFile(externalImage, "secret");+ await symlink(externalImage, linkedImage);++ await expect(+ service.readWorkspaceFileAsBase64(repo, linkedImage),+ ).resolves.toBeNull();+ await expect(+ service.readWorkspaceFileAsBase64(repo, externalImage),+ ).resolves.toBeNull();++ await rm(external, { recursive: true, force: true });+ });++ it("refuses workspace image reads larger than 5 MB", async () => {+ const oversizedImage = path.join(repo, "oversized.png");+ await writeFile(oversizedImage, Buffer.alloc(5 * 1024 * 1024 + 1));++ await expect(+ service.readWorkspaceFileAsBase64(repo, oversizedImage),+ ).resolves.toBeNull();+ });+it("bounds reads by line count", async () => {await service.writeRepoFile(repo, "small.txt", "a\nb\nc");await service.writeRepoFile(repo, "big.txt", "a\nb\nc\nd\ne");diff --git a/products/desktop/packages/workspace-server/src/services/fs/service.ts b/products/desktop/packages/workspace-server/src/services/fs/service.tsindex 64e53589af64..c7fe4cf71844 100644--- a/products/desktop/packages/workspace-server/src/services/fs/service.ts+++ b/products/desktop/packages/workspace-server/src/services/fs/service.ts@@ -6,6 +6,7 @@ import type { BoundedReadResult, DirectoryEntry, FileEntry } from "./schemas";@injectable()export class FsService {+ private static readonly MAX_WORKSPACE_IMAGE_BYTES = 5 * 1024 * 1024;private static readonly CACHE_TTL = 30000;private static readonly READ_REPO_FILES_CONCURRENCY = 24;private static readonly MAX_REPO_FILES = 50_000;@@ -185,6 +186,32 @@ export class FsService {}}+ async readWorkspaceFileAsBase64(+ workspaceRoot: string,+ filePath: string,+ ): Promise<string | null> {+ try {+ const [canonicalRoot, canonicalFile] = await Promise.all([+ fs.realpath(workspaceRoot),+ fs.realpath(filePath),+ ]);+ const relativePath = path.relative(canonicalRoot, canonicalFile);+ if (+ relativePath === ".." ||+ relativePath.startsWith(`..${path.sep}`) ||+ path.isAbsolute(relativePath)+ ) {+ return null;+ }+ const stat = await fs.stat(canonicalFile);+ if (stat.size > FsService.MAX_WORKSPACE_IMAGE_BYTES) return null;+ const buffer = await fs.readFile(canonicalFile);+ return buffer.toString("base64");+ } catch {+ return null;+ }+ }+async writeRepoFile(repoPath: string,filePath: string,diff --git a/products/desktop/packages/workspace-server/src/trpc.ts b/products/desktop/packages/workspace-server/src/trpc.tsindex 959f1d566bda..256c270d668f 100644--- a/products/desktop/packages/workspace-server/src/trpc.ts+++ b/products/desktop/packages/workspace-server/src/trpc.ts@@ -39,6 +39,7 @@ import {readRepoFilesBoundedOutput,readRepoFilesInput,readRepoFilesOutput,+ readWorkspaceFileInput,writeRepoFileInput,} from "./services/fs/schemas";import type { FsService } from "./services/fs/service";@@ -816,6 +817,16 @@ export function createAppRouter({.output(readRepoFileOutput).query(({ input }) => fsService().readFileAsBase64(input.filePath)),+ readWorkspaceFileAsBase64: t.procedure+ .input(readWorkspaceFileInput)+ .output(readRepoFileOutput)+ .query(({ input }) =>+ fsService().readWorkspaceFileAsBase64(+ input.workspaceRoot,+ input.filePath,+ ),+ ),+writeRepoFile: t.procedure.input(writeRepoFileInput).mutation(({ input }) =>