Skip to content

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

feat(desktop): show sent images above user messages (#99397)

Adam Leithdc3b0e6da13a
diff --git a/products/desktop/packages/core/src/editor/cloud-prompt.ts b/products/desktop/packages/core/src/editor/cloud-prompt.ts
index 3d9349e4244f..13e63ccd018b 100644
--- a/products/desktop/packages/core/src/editor/cloud-prompt.ts
+++ b/products/desktop/packages/core/src/editor/cloud-prompt.ts
@@ -52,7 +52,7 @@ export function hasProseBeyondAttachments(content: EditorContent): boolean {
);
}
-const ABSOLUTE_FILE_TAG_REGEX = /<file\s+path="([^"]+)"\s*\/>/g;
+export const ABSOLUTE_FILE_TAG_REGEX = /<file\s+path="([^"]+)"\s*\/>/g;
const FOLDER_TAG_REGEX = /<folder\s+path="[^"]+"\s*\/>/g;
const FOLDER_TAG_PATH_REGEX = /<folder\s+path="([^"]+)"\s*\/>/g;
const TEXT_EXTENSIONS = new Set([
@@ -134,7 +134,7 @@ function unique<T>(values: T[]): T[] {
return Array.from(new Set(values));
}
-function normalizePromptText(prompt: string): string {
+export function normalizePromptText(prompt: string): string {
return prompt.replace(/\n{3,}/g, "\n\n").trim();
}
@@ -181,6 +181,22 @@ export function stripTrailingAttachmentSummary(text: string): string {
return text.replace(TRAILING_ATTACHMENT_SUMMARY_REGEX, "").trim();
}
+/** Strips the trailing attachment summary only when every file it names is in `labels`. */
+export function stripAttachmentSummaryOf(
+ text: string,
+ labels: ReadonlySet<string>,
+): string {
+ const summary = text.match(TRAILING_ATTACHMENT_SUMMARY_REGEX)?.[0];
+ if (!summary) return text;
+ const names = summary
+ .trim()
+ .slice(ATTACHMENT_SUMMARY_PREFIX.length)
+ .split(", ");
+ return names.every((name) => labels.has(name))
+ ? stripTrailingAttachmentSummary(text)
+ : text;
+}
+
export function buildCloudTaskDescription(
prompt: string,
filePaths: string[] = [],
diff --git a/products/desktop/packages/core/src/sessions/promptContent.test.ts b/products/desktop/packages/core/src/sessions/promptContent.test.ts
index 6ab8eebc3144..2c0d53012c42 100644
--- a/products/desktop/packages/core/src/sessions/promptContent.test.ts
+++ b/products/desktop/packages/core/src/sessions/promptContent.test.ts
@@ -3,6 +3,7 @@ import {
extractPromptDisplayContent,
makeAttachmentUri,
parseAttachmentUri,
+ resolveMessageAttachments,
} from "./promptContent";
describe("promptContent", () => {
@@ -105,4 +106,62 @@ describe("promptContent", () => {
{ id: fileUri, label: "screenshot.png" },
]);
});
+
+ const clipboardImage = {
+ id: "file:///tmp/posthog-code-clipboard/attachment-abc/clipboard.png",
+ label: "clipboard.png",
+ };
+
+ it.each([
+ {
+ name: "lifts a composer image tag out of the text",
+ text: 'look at this <file path="/tmp/posthog-code-clipboard/attachment-abc/clipboard.png" />',
+ given: [],
+ expected: { text: "look at this", attachments: [clipboardImage] },
+ },
+ {
+ name: "keeps images outside the composer folder inline",
+ text: 'see <file path="/Users/me/Pictures/secret.png" />',
+ given: [],
+ expected: {
+ text: 'see <file path="/Users/me/Pictures/secret.png" />',
+ attachments: [],
+ },
+ },
+ {
+ name: "keeps network share paths inline",
+ text: 'see <file path="\\\\host\\share\\posthog-code-clipboard\\attachment-a\\x.png" />',
+ given: [],
+ expected: {
+ text: 'see <file path="\\\\host\\share\\posthog-code-clipboard\\attachment-a\\x.png" />',
+ attachments: [],
+ },
+ },
+ {
+ name: "keeps non-image composer files inline",
+ text: 'see <file path="/tmp/posthog-code-clipboard/attachment-abc/notes.md" />',
+ given: [],
+ expected: {
+ text: 'see <file path="/tmp/posthog-code-clipboard/attachment-abc/notes.md" />',
+ attachments: [],
+ },
+ },
+ {
+ name: "drops a summary that names only the shown files",
+ text: "Attached files: clipboard.png",
+ given: [clipboardImage],
+ expected: { text: "", attachments: [clipboardImage] },
+ },
+ {
+ name: "keeps a summary that names a file it does not show",
+ text: "hello\n\nAttached files: other.png",
+ given: [clipboardImage],
+ expected: {
+ text: "hello\n\nAttached files: other.png",
+ attachments: [clipboardImage],
+ },
+ },
+ ])("resolveMessageAttachments $name", ({ text, given, expected }) => {
+ expect(resolveMessageAttachments(text, given)).toEqual(expected);
+ });
});
diff --git a/products/desktop/packages/core/src/sessions/promptContent.ts b/products/desktop/packages/core/src/sessions/promptContent.ts
index ad331423ca0d..11117bb6e17e 100644
--- a/products/desktop/packages/core/src/sessions/promptContent.ts
+++ b/products/desktop/packages/core/src/sessions/promptContent.ts
@@ -1,5 +1,16 @@
import type { ContentBlock } from "@agentclientprotocol/sdk";
-import { getFileName } from "@posthog/shared";
+import {
+ getFileName,
+ isClipboardAttachmentPath,
+ isRasterImageFile,
+ pathToFileUri,
+ unescapeXmlAttr,
+} from "@posthog/shared";
+import {
+ ABSOLUTE_FILE_TAG_REGEX,
+ normalizePromptText,
+ stripAttachmentSummaryOf,
+} from "../editor/cloud-prompt";
const ATTACHMENT_URI_PREFIX = "attachment://";
@@ -172,3 +183,57 @@ export function extractPromptDisplayContent(
return { text: textParts.join(""), attachments };
}
+
+const MENTION_TAG_TEST =
+ /<(?:file\s+path|folder\s+path|github_issue\s+number|github_pr\s+number|error_context\s+label)="[^"]+"/;
+export const SLASH_COMMAND_START = /^\/([a-zA-Z][\w-]*)(?=\s|$)/;
+
+export function hasMentionTags(content: string): boolean {
+ return MENTION_TAG_TEST.test(content) || SLASH_COMMAND_START.test(content);
+}
+
+export function resolveMessageAttachments(
+ text: string,
+ attachments: AttachmentRef[],
+): PromptDisplayContent {
+ const lifted = extractImageFileTags(text);
+ // contentToXml folds every attachment into a <file /> mention, so text that
+ // still carries one already lists the message's attachments inline.
+ const visible = hasMentionTags(lifted.text)
+ ? lifted.attachments
+ : [
+ ...attachments,
+ ...lifted.attachments.filter(
+ (image) => !attachments.some(({ id }) => id === image.id),
+ ),
+ ];
+ return {
+ text: stripAttachmentSummaryOf(
+ lifted.text,
+ new Set(visible.map(({ label }) => label)),
+ ),
+ attachments: visible,
+ };
+}
+
+function extractImageFileTags(text: string): PromptDisplayContent {
+ const attachments: AttachmentRef[] = [];
+ const stripped = text.replace(
+ ABSOLUTE_FILE_TAG_REGEX,
+ (tag, rawPath: string) => {
+ const filePath = unescapeXmlAttr(rawPath);
+ const label = getFileName(filePath);
+ // Message text is not trusted: only files the composer saved may be read from disk.
+ if (!isClipboardAttachmentPath(filePath) || !isRasterImageFile(label)) {
+ return tag;
+ }
+ const id = pathToFileUri(filePath);
+ if (!attachments.some((attachment) => attachment.id === id)) {
+ attachments.push({ id, label });
+ }
+ return "";
+ },
+ );
+ if (attachments.length === 0) return { text, attachments };
+ return { text: normalizePromptText(stripped), attachments };
+}
diff --git a/products/desktop/packages/shared/src/index.ts b/products/desktop/packages/shared/src/index.ts
index f6ceb2d0a87f..d5e7e7cb9657 100644
--- a/products/desktop/packages/shared/src/index.ts
+++ b/products/desktop/packages/shared/src/index.ts
@@ -253,11 +253,14 @@ export {
workflowAgentStateSchema,
} from "./orchestration";
export {
+ CLIPBOARD_ATTACHMENT_DIR_NAME,
+ CLIPBOARD_ATTACHMENT_PREFIX,
compactHomePath,
expandTildePath,
getFileExtension,
getFileName,
isAbsolutePath,
+ isClipboardAttachmentPath,
pathToFileUri,
toRelativePath,
} from "./path";
diff --git a/products/desktop/packages/shared/src/path.ts b/products/desktop/packages/shared/src/path.ts
index 875ae2a12097..29d37ca48219 100644
--- a/products/desktop/packages/shared/src/path.ts
+++ b/products/desktop/packages/shared/src/path.ts
@@ -55,6 +55,25 @@ export function getFileExtension(filePath: string): string {
return lastDot >= 0 ? name.slice(lastDot + 1).toLowerCase() : "";
}
+export const CLIPBOARD_ATTACHMENT_DIR_NAME = "posthog-code-clipboard";
+export const CLIPBOARD_ATTACHMENT_PREFIX = "attachment-";
+
+/** True for a path shaped like a composer-saved file: `<dir>/posthog-code-clipboard/attachment-*\/<name>`. */
+export function isClipboardAttachmentPath(filePath: string): boolean {
+ const normalized = filePath.replaceAll("\\", "/");
+ if (!isAbsolutePath(filePath) || normalized.startsWith("//")) return false;
+ const segments = normalized.split("/");
+ const [dir, folder, name] = segments.slice(-3);
+ return (
+ dir === CLIPBOARD_ATTACHMENT_DIR_NAME &&
+ folder !== undefined &&
+ folder.length > CLIPBOARD_ATTACHMENT_PREFIX.length &&
+ folder.startsWith(CLIPBOARD_ATTACHMENT_PREFIX) &&
+ !!name &&
+ !segments.includes("..")
+ );
+}
+
/**
* Convert a local file path to a `file://` URI.
* Renderer-safe (no `node:*` imports) and supports Windows drive and UNC paths.
diff --git a/products/desktop/packages/ui/src/features/sessions/components/UserMessageAttachments.tsx b/products/desktop/packages/ui/src/features/sessions/components/UserMessageAttachments.tsx
index 72900e654f5f..f2657dd3e30d 100644
--- a/products/desktop/packages/ui/src/features/sessions/components/UserMessageAttachments.tsx
+++ b/products/desktop/packages/ui/src/features/sessions/components/UserMessageAttachments.tsx
@@ -81,13 +81,13 @@ function ImageAttachment({
<Dialog.Trigger>
<button
type="button"
- className="group relative h-16 w-20 overflow-hidden rounded-md border border-gray-6 bg-gray-3"
+ className="group relative block max-w-full overflow-hidden rounded-md border border-gray-6 bg-gray-3"
aria-label={`Preview ${attachment.label}`}
>
<img
src={previewUrl}
alt={attachment.label}
- className="size-full object-cover transition-transform group-hover:scale-105"
+ className="block h-auto max-h-48 w-auto max-w-64 transition-transform group-hover:scale-105"
/>
<span className="absolute inset-x-0 bottom-0 truncate bg-black/60 px-1.5 py-0.5 text-left text-[10px] text-white">
{attachment.label}
diff --git a/products/desktop/packages/ui/src/features/sessions/components/chat-thread/ChatThread.tsx b/products/desktop/packages/ui/src/features/sessions/components/chat-thread/ChatThread.tsx
index 3238b525aba5..746fcfbffd3f 100644
--- a/products/desktop/packages/ui/src/features/sessions/components/chat-thread/ChatThread.tsx
+++ b/products/desktop/packages/ui/src/features/sessions/components/chat-thread/ChatThread.tsx
@@ -100,6 +100,7 @@ import { isShowActionsItem } from "@posthog/ui/features/sessions/components/sess
import { UserShellExecuteView } from "@posthog/ui/features/sessions/components/session-update/UserShellExecuteView";
import { splitUserMessage } from "@posthog/ui/features/sessions/components/session-update/userMessageDisplay";
import { useVisibleInjectedBlocks } from "@posthog/ui/features/sessions/components/session-update/useVisibleInjectedBlocks";
+import { UserMessageAttachments } from "@posthog/ui/features/sessions/components/UserMessageAttachments";
import {
CHAT_CONTENT_MAX_WIDTH,
CHAT_CONTENT_PADDING_INLINE,
@@ -117,7 +118,10 @@ import {
useTurnFeedback,
} from "@posthog/ui/features/sessions/sessionViewStore";
import { useThreadScrollRequest } from "@posthog/ui/features/sessions/threadNavigationStore";
-import type { UserMessageAttachment } from "@posthog/ui/features/sessions/userMessageTypes";
+import {
+ NO_ATTACHMENTS,
+ type UserMessageAttachment,
+} from "@posthog/ui/features/sessions/userMessageTypes";
import {
SessionTaskIdProvider,
useSessionTaskId,
@@ -520,7 +524,7 @@ function CopyButton({ value, label }: { value: string; label: string }) {
function UserBubble({
content,
timestamp,
- attachments = [],
+ attachments = NO_ATTACHMENTS,
keyboardFocused = false,
}: {
content: string;
@@ -532,9 +536,14 @@ function UserBubble({
// message (start-aligned, outlined, provenance chip) instead of masquerading
// as something this run's user typed. The envelope boilerplate never renders;
// only the sender-authored body flows into the normal pipeline below.
- const { peerAgentMessage, blocks, displayContent } = useMemo(
- () => splitUserMessage(content),
- [content],
+ const {
+ peerAgentMessage,
+ blocks,
+ displayContent,
+ attachments: visibleAttachments,
+ } = useMemo(
+ () => splitUserMessage(content, attachments),
+ [content, attachments],
);
const visibleBlocks = useVisibleInjectedBlocks(blocks);
// Provenance is never flag-gated: a peer message must not read as the user's.
@@ -548,7 +557,7 @@ function UserBubble({
<ChatMessage align={peerAgentMessage ? "start" : "end"} className="group">
<ChatMessageContent className="gap-1">
{showHeaderChips && (
- <ChatMessageHeader className="flex-wrap gap-1">
+ <ChatMessageHeader className="flex-wrap gap-1 px-0">
{peerAgentMessage && (
<MentionChip
icon={<Robot size={12} />}
@@ -558,8 +567,13 @@ function UserBubble({
<InjectedBlockChips blocks={visibleBlocks} taskId={taskId} />
</ChatMessageHeader>
)}
+ {visibleAttachments.length > 0 && (
+ <div className={peerAgentMessage ? "self-start" : "self-end"}>
+ <UserMessageAttachments attachments={visibleAttachments} />
+ </div>
+ )}
{/* The brief is the whole message, so stripping it leaves nothing to put in a bubble. */}
- {(!!displayContent || attachments.length > 0) && (
+ {!!displayContent && (
<ChatBubble
align={peerAgentMessage ? "start" : "end"}
variant={peerAgentMessage ? "outline" : "default"}
@@ -569,10 +583,7 @@ function UserBubble({
)}
>
<ChatBubbleContent>
- <UserMessageBody
- content={displayContent}
- attachments={attachments}
- />
+ <UserMessageBody content={displayContent} />
</ChatBubbleContent>
</ChatBubble>
)}
diff --git a/products/desktop/packages/ui/src/features/sessions/components/chat-thread/UserMessageBody.tsx b/products/desktop/packages/ui/src/features/sessions/components/chat-thread/UserMessageBody.tsx
index ba9e45942317..88f51950eedd 100644
--- a/products/desktop/packages/ui/src/features/sessions/components/chat-thread/UserMessageBody.tsx
+++ b/products/desktop/packages/ui/src/features/sessions/components/chat-thread/UserMessageBody.tsx
@@ -5,8 +5,6 @@ import {
hasFileMentions,
parseFileMentions,
} from "@posthog/ui/features/sessions/components/session-update/parseFileMentions";
-import { UserMessageAttachments } from "@posthog/ui/features/sessions/components/UserMessageAttachments";
-import type { UserMessageAttachment } from "@posthog/ui/features/sessions/userMessageTypes";
import { useEffect, useRef, useState } from "react";
/**
@@ -15,19 +13,10 @@ import { useEffect, useRef, useState } from "react";
* identically in the live transcript and in views that precede it. Plain
* content renders as markdown.
*
- * Attachments hide when the content carries file mentions: contentToXml folds
- * every attachment into a <file /> tag, so showing both would list it twice.
- *
* Long content clamps to five lines with a Show more toggle, so a bubble in a
* pre-transcript view never grows past what the live bubble would show.
*/
-export function UserMessageBody({
- content,
- attachments = [],
-}: {
- content: string;
- attachments?: UserMessageAttachment[];
-}) {
+export function UserMessageBody({ content }: { content: string }) {
const containsFileMentions = hasFileMentions(content);
const [isExpanded, setIsExpanded] = useState(false);
@@ -71,11 +60,6 @@ export function UserMessageBody({
<ChatMarkdown content={content} />
)}
</div>
- {attachments.length > 0 && !containsFileMentions && (
- <div className="mt-1.5">
- <UserMessageAttachments attachments={attachments} />
- </div>
- )}
{isOverflowing && (
<button
type="button"
diff --git a/products/desktop/packages/ui/src/features/sessions/components/session-update/UserMessage.tsx b/products/desktop/packages/ui/src/features/sessions/components/session-update/UserMessage.tsx
index 2afe28f2397e..f9bf8610d88a 100644
--- a/products/desktop/packages/ui/src/features/sessions/components/session-update/UserMessage.tsx
+++ b/products/desktop/packages/ui/src/features/sessions/components/session-update/UserMessage.tsx
@@ -4,7 +4,10 @@ import { motion } from "framer-motion";
import { memo, useCallback, useEffect, useMemo, useRef, useState } from "react";
import { Tooltip } from "../../../../primitives/Tooltip";
import { MarkdownRenderer } from "../../../editor/components/MarkdownRenderer";
-import type { UserMessageAttachment } from "../../userMessageTypes";
+import {
+ NO_ATTACHMENTS,
+ type UserMessageAttachment,
+} from "../../userMessageTypes";
import { UserMessageAttachments } from "../UserMessageAttachments";
import { CollapsibleMessageContent } from "./CollapsibleMessageContent";
import { InjectedBlockChips } from "./InjectedBlockChips";
@@ -47,7 +50,7 @@ export const UserMessage = memo(function UserMessage({
content,
timestamp,
sourceUrl,
- attachments = [],
+ attachments = NO_ATTACHMENTS,
animate = true,
taskId,
keyboardFocused = false,
@@ -55,14 +58,18 @@ export const UserMessage = memo(function UserMessage({
// A message relayed from another agent run renders with a provenance chip and
// neutral accent instead of masquerading as this run's user. The envelope
// boilerplate never renders; only the sender-authored body flows on.
- const { peerAgentMessage, blocks, displayContent } = useMemo(
- () => splitUserMessage(content),
- [content],
+ const {
+ peerAgentMessage,
+ blocks,
+ displayContent,
+ attachments: visibleAttachments,
+ } = useMemo(
+ () => splitUserMessage(content, attachments),
+ [content, attachments],
);
const visibleBlocks = useVisibleInjectedBlocks(blocks);
const containsFileMentions = hasFileMentions(displayContent);
- const showAttachmentChips = attachments.length > 0 && !containsFileMentions;
const [copied, setCopied] = useState(false);
const copiedTimerRef = useRef<ReturnType<typeof setTimeout>>(undefined);
@@ -91,6 +98,11 @@ export const UserMessage = memo(function UserMessage({
}}
>
<CollapsibleMessageContent contentClassName="font-medium text-[13px] [&_p]:leading-[1.9]">
+ {visibleAttachments.length > 0 && (
+ <div className={displayContent ? "mb-1.5" : ""}>
+ <UserMessageAttachments attachments={visibleAttachments} />
+ </div>
+ )}
{containsFileMentions ? (
parseFileMentions(displayContent)
) : (
@@ -109,11 +121,6 @@ export const UserMessage = memo(function UserMessage({
<InjectedBlockChips blocks={visibleBlocks} taskId={taskId} />
</div>
)}
- {showAttachmentChips && (
- <div className={content.trim() ? "mt-1.5" : ""}>
- <UserMessageAttachments attachments={attachments} />
- </div>
- )}
</CollapsibleMessageContent>
{sourceUrl && (
<a
diff --git a/products/desktop/packages/ui/src/features/sessions/components/session-update/parseFileMentions.tsx b/products/desktop/packages/ui/src/features/sessions/components/session-update/parseFileMentions.tsx
index 4704b80985a1..cf03f27ee382 100644
--- a/products/desktop/packages/ui/src/features/sessions/components/session-update/parseFileMentions.tsx
+++ b/products/desktop/packages/ui/src/features/sessions/components/session-update/parseFileMentions.tsx
@@ -1,4 +1,8 @@
import { File, Folder, Warning } from "@phosphor-icons/react";
+import {
+ hasMentionTags,
+ SLASH_COMMAND_START,
+} from "@posthog/core/sessions/promptContent";
import { Tooltip, TooltipContent, TooltipTrigger } from "@posthog/quill";
import { unescapeXmlAttr } from "@posthog/shared";
import { Text } from "@radix-ui/themes";
@@ -14,9 +18,6 @@ import {
const MENTION_TAG_REGEX =
/<file\s+path="([^"]+)"\s*\/>|<(github_issue|github_pr)\s+number="([^"]+)"(?:\s+title="([^"]*)")?(?:\s+url="([^"]*)")?\s*\/>|<error_context\s+label="([^"]*)">[\s\S]*?<\/error_context>|<folder\s+path="([^"]+)"\s*\/>/g;
-const MENTION_TAG_TEST =
- /<(?:file\s+path|folder\s+path|github_issue\s+number|github_pr\s+number|error_context\s+label)="[^"]+"/;
-const SLASH_COMMAND_START = /^\/([a-zA-Z][\w-]*)(?=\s|$)/;
const inlineComponents: Components = {
...baseComponents,
@@ -42,10 +43,6 @@ const InlineMarkdown = memo(function InlineMarkdown({
);
});
-function hasMentionTags(content: string): boolean {
- return MENTION_TAG_TEST.test(content) || SLASH_COMMAND_START.test(content);
-}
-
export const hasFileMentions = hasMentionTags;
const chipClass =
diff --git a/products/desktop/packages/ui/src/features/sessions/components/session-update/userMessageDisplay.ts b/products/desktop/packages/ui/src/features/sessions/components/session-update/userMessageDisplay.ts
index 0104e3acbd2b..b983e115ccf5 100644
--- a/products/desktop/packages/ui/src/features/sessions/components/session-update/userMessageDisplay.ts
+++ b/products/desktop/packages/ui/src/features/sessions/components/session-update/userMessageDisplay.ts
@@ -2,6 +2,8 @@ import {
type InjectedBlock,
splitInjectedBlocks,
} from "@posthog/core/editor/injectedBlocks";
+import { resolveMessageAttachments } from "@posthog/core/sessions/promptContent";
+import type { UserMessageAttachment } from "@posthog/ui/features/sessions/userMessageTypes";
import {
extractPeerAgentMessage,
type PeerAgentMessage,
@@ -12,17 +14,26 @@ export interface UserMessageParts {
peerAgentMessage: PeerAgentMessage | null;
blocks: InjectedBlock[];
displayContent: string;
+ attachments: UserMessageAttachment[];
}
-export function splitUserMessage(content: string): UserMessageParts {
+export function splitUserMessage(
+ content: string,
+ attachments: UserMessageAttachment[] = [],
+): UserMessageParts {
const peerAgentMessage = extractPeerAgentMessage(content);
const { blocks, text } = splitInjectedBlocks(
peerAgentMessage ? peerAgentMessage.body : content,
);
+ const resolved = resolveMessageAttachments(
+ collapsePiSkillInvocation(text),
+ attachments,
+ );
return {
peerAgentMessage,
blocks,
- displayContent: collapsePiSkillInvocation(text),
+ displayContent: resolved.text,
+ attachments: resolved.attachments,
};
}
diff --git a/products/desktop/packages/ui/src/features/sessions/userMessageTypes.ts b/products/desktop/packages/ui/src/features/sessions/userMessageTypes.ts
index 339c78810621..d7d11a6a2a49 100644
--- a/products/desktop/packages/ui/src/features/sessions/userMessageTypes.ts
+++ b/products/desktop/packages/ui/src/features/sessions/userMessageTypes.ts
@@ -1,3 +1,5 @@
import type { AttachmentRef } from "@posthog/core/sessions/promptContent";
export type UserMessageAttachment = AttachmentRef;
+
+export const NO_ATTACHMENTS: UserMessageAttachment[] = [];
diff --git a/products/desktop/packages/workspace-server/src/services/os/os.test.ts b/products/desktop/packages/workspace-server/src/services/os/os.test.ts
index 9ab0d2b5ec54..2c188e77875a 100644
--- a/products/desktop/packages/workspace-server/src/services/os/os.test.ts
+++ b/products/desktop/packages/workspace-server/src/services/os/os.test.ts
@@ -625,3 +625,44 @@ describe("OsService.getClaudePermissions", () => {
});
});
});
+
+describe("OsService.readFileAsDataUrl", () => {
+ const clipboardFile = path.join(
+ os.tmpdir(),
+ "posthog-code-clipboard",
+ "attachment-a",
+ "shot.png",
+ );
+ const lookAlike = "/work/repo/posthog-code-clipboard/attachment-a/shot.png";
+
+ it.each([
+ {
+ name: "reads an image the composer saved",
+ requested: clipboardFile,
+ resolvesTo: clipboardFile,
+ expected: "data:image/png;base64,aW1n",
+ },
+ {
+ name: "rejects a look-alike folder outside the temp dir",
+ requested: lookAlike,
+ resolvesTo: lookAlike,
+ expected: null,
+ },
+ {
+ name: "rejects a clipboard file that links elsewhere",
+ requested: clipboardFile,
+ resolvesTo: "/Users/me/secret.png",
+ expected: null,
+ },
+ ])("$name", async ({ requested, resolvesTo, expected }) => {
+ mockRealpath.mockImplementation(async (p: string) =>
+ p === requested ? resolvesTo : p,
+ );
+ mockStat.mockResolvedValue({ size: 3 });
+ mockReadFile.mockResolvedValue(Buffer.from("img"));
+ const { service } = createService();
+
+ expect(await service.readFileAsDataUrl(requested, 1024)).toBe(expected);
+ expect(mockReadFile).toHaveBeenCalledTimes(expected ? 1 : 0);
+ });
+});
diff --git a/products/desktop/packages/workspace-server/src/services/os/os.ts b/products/desktop/packages/workspace-server/src/services/os/os.ts
index a4f0a8b682a1..56f394cbb1db 100644
--- a/products/desktop/packages/workspace-server/src/services/os/os.ts
+++ b/products/desktop/packages/workspace-server/src/services/os/os.ts
@@ -26,7 +26,10 @@ import {
} from "@posthog/platform/workspace-settings";
import {
ALLOWED_IMAGE_MIME_TYPES,
+ CLIPBOARD_ATTACHMENT_DIR_NAME,
+ CLIPBOARD_ATTACHMENT_PREFIX,
IMAGE_MIME_TYPES,
+ isClipboardAttachmentPath,
isRasterImageFile,
} from "@posthog/shared";
import { inject, injectable } from "inversify";
@@ -47,9 +50,23 @@ const fsPromises = fs.promises;
const MAX_IMAGE_DIMENSION = 1568;
const JPEG_QUALITY = 85;
const MAX_FILE_SIZE = 50 * 1024 * 1024;
-const CLIPBOARD_TEMP_DIR = path.join(os.tmpdir(), "posthog-code-clipboard");
+const CLIPBOARD_TEMP_DIR = path.join(
+ os.tmpdir(),
+ CLIPBOARD_ATTACHMENT_DIR_NAME,
+);
const claudeSettingsPath = path.join(os.homedir(), ".claude", "settings.json");
+async function isInsideClipboardTempDir(filePath: string): Promise<boolean> {
+ const [realFile, realDir] = await Promise.all([
+ fsPromises.realpath(filePath),
+ fsPromises.realpath(CLIPBOARD_TEMP_DIR),
+ ]);
+ const relative = path.relative(realDir, realFile);
+ return (
+ relative !== "" && !relative.startsWith("..") && !path.isAbsolute(relative)
+ );
+}
+
// User-level agent instruction files as path segments under the home
// directory, most-preferred first: AGENTS.md (the cross-agent convention) from
// any of its conventional homes wins over Claude Code's CLAUDE.md, and a
@@ -488,6 +505,13 @@ export class OsService {
maxSizeBytes: number,
): Promise<string | null> {
try {
+ // Message text can name a clipboard-shaped path, so it must resolve inside the real folder.
+ if (
+ isClipboardAttachmentPath(filePath) &&
+ !(await isInsideClipboardTempDir(filePath))
+ ) {
+ return null;
+ }
const stat = await fsPromises.stat(filePath);
if (stat.size > maxSizeBytes) return null;
@@ -565,7 +589,7 @@ export class OsService {
const safeName = path.basename(displayName) || "attachment";
await fsPromises.mkdir(CLIPBOARD_TEMP_DIR, { recursive: true });
const tempDir = await fsPromises.mkdtemp(
- path.join(CLIPBOARD_TEMP_DIR, "attachment-"),
+ path.join(CLIPBOARD_TEMP_DIR, CLIPBOARD_ATTACHMENT_PREFIX),
);
return path.join(tempDir, safeName);
}