From 42637458c9420c01fad709822a7383878adeb701 Mon Sep 17 00:00:00 2001 From: lemonknowsall Date: Thu, 13 Nov 2025 23:10:11 -0800 Subject: [PATCH 1/6] pass image to agent, render image in chat --- package-lock.json | 42 ++++++++---- src/components/AIMessageItem.tsx | 87 +++++++++++++++++++++++-- src/components/Shakespeare/ChatPane.tsx | 39 +---------- src/hooks/useAIChat.ts | 5 +- src/lib/SessionManager.ts | 15 +++-- src/lib/buildMessageContent.ts | 67 +++++++++++++++++++ src/lib/parseImageUrls.ts | 79 ++++++++++++++++++++++ src/pages/Index.tsx | 41 ++---------- 8 files changed, 279 insertions(+), 96 deletions(-) create mode 100644 src/lib/buildMessageContent.ts create mode 100644 src/lib/parseImageUrls.ts diff --git a/package-lock.json b/package-lock.json index 3cb66e79..8f2729dd 100644 --- a/package-lock.json +++ b/package-lock.json @@ -195,6 +195,7 @@ "integrity": "sha512-e7jT4DxYvIDLk1ZHmU/m/mB19rex9sv0c2ftBtjSBv+kVM/902eh0fINUzD7UwLLNR+jU585GxUJ8/EBfAM5fw==", "dev": true, "license": "MIT", + "peer": true, "dependencies": { "@babel/code-frame": "^7.27.1", "@babel/generator": "^7.28.5", @@ -1830,6 +1831,7 @@ } ], "license": "MIT", + "peer": true, "engines": { "node": ">=18" }, @@ -1853,6 +1855,7 @@ } ], "license": "MIT", + "peer": true, "engines": { "node": ">=18" } @@ -1874,6 +1877,7 @@ "resolved": "https://registry.npmjs.org/@dnd-kit/core/-/core-6.3.1.tgz", "integrity": "sha512-xkGBRQQab4RLwgXxoqETICr6S5JlogafbhNsidmrkVv2YRs5MLwpjoF2qpiGjQt8S9AoxtIV603s0GIUpY5eYQ==", "license": "MIT", + "peer": true, "dependencies": { "@dnd-kit/accessibility": "^3.1.1", "@dnd-kit/utilities": "^3.2.2", @@ -5404,8 +5408,7 @@ "resolved": "https://registry.npmjs.org/@types/aria-query/-/aria-query-5.0.4.tgz", "integrity": "sha512-rfT93uj5s0PRL7EzccGMs3brplhcrghnDoV26NqKhCAS1hVo+WdNsPvE/yb6ilfr5hi2MEk6d5EWJTKdxg8jVw==", "dev": true, - "license": "MIT", - "peer": true + "license": "MIT" }, "node_modules/@types/cacheable-request": { "version": "6.0.3", @@ -5647,6 +5650,7 @@ "resolved": "https://registry.npmjs.org/@types/react/-/react-18.3.20.tgz", "integrity": "sha512-IPaCZN7PShZK/3t6Q87pfTkRm6oLTd4vztyoj+cbHUF1g3FfVb2tFIL79uCRKEfv16AhqDMBywP2VW3KIZUvcg==", "license": "MIT", + "peer": true, "dependencies": { "@types/prop-types": "*", "csstype": "^3.0.2" @@ -5658,6 +5662,7 @@ "integrity": "sha512-MEe3UeoENYVFXzoXEWsvcpg6ZvlrFNlOQ7EOsvhI3CfAXwzPfO8Qwuxd40nepsYKqyyVQnTdEfv68q91yLcKrQ==", "devOptional": true, "license": "MIT", + "peer": true, "peerDependencies": { "@types/react": "^18.0.0" } @@ -5762,6 +5767,7 @@ "integrity": "sha512-oU/OtYVydhXnumd0BobL9rkJg7wFJ9bFFPmSmB/bf/XWN85hlViji59ko6bSKBXyseT9V8l+CN1nwmlbiN0G7Q==", "dev": true, "license": "MIT", + "peer": true, "dependencies": { "@typescript-eslint/scope-manager": "8.31.1", "@typescript-eslint/types": "8.31.1", @@ -6108,6 +6114,7 @@ "resolved": "https://registry.npmjs.org/acorn/-/acorn-8.15.0.tgz", "integrity": "sha512-NZyJarBfL7nWwIq+FDL6Zp/yHEhePMNnnJ0y3qfieCrmNvYct8uvtiV41UvlSe6apAfk0fY1FbWx+NwfmpvtTg==", "license": "MIT", + "peer": true, "bin": { "acorn": "bin/acorn" }, @@ -6552,6 +6559,7 @@ } ], "license": "MIT", + "peer": true, "dependencies": { "baseline-browser-mapping": "^2.8.19", "caniuse-lite": "^1.0.30001751", @@ -6811,6 +6819,7 @@ "resolved": "https://registry.npmjs.org/chokidar/-/chokidar-3.6.0.tgz", "integrity": "sha512-7VT13fmjotKpGipCW9JEQAusEPE+Ei8nl6/g4FBAmIm0GOOLMua9NDDo/DWp0ZAxCr3cPq5ZpBqmPAQgDda2Pw==", "license": "MIT", + "peer": true, "dependencies": { "anymatch": "~3.1.2", "braces": "~3.0.2", @@ -7549,8 +7558,7 @@ "resolved": "https://registry.npmjs.org/dom-accessibility-api/-/dom-accessibility-api-0.5.16.tgz", "integrity": "sha512-X7BJ2yElsnOJ30pZF4uIIDfBEVgF4XEBxL9Bxhy6dnrm5hkzqmsWHGTiHqRiITNhMyFLyAiWndIJP7Z1NTteDg==", "dev": true, - "license": "MIT", - "peer": true + "license": "MIT" }, "node_modules/dom-helpers": { "version": "5.2.1", @@ -7628,7 +7636,8 @@ "version": "8.6.0", "resolved": "https://registry.npmjs.org/embla-carousel/-/embla-carousel-8.6.0.tgz", "integrity": "sha512-SjWyZBHJPbqxHOzckOfo8lHisEaJWmwd23XppYFYVh10bU66/Pn5tkVkbkCMZVdbUE5eTCI2nD8OyIP4Z+uwkA==", - "license": "MIT" + "license": "MIT", + "peer": true }, "node_modules/embla-carousel-react": { "version": "8.6.0", @@ -7927,6 +7936,7 @@ "integrity": "sha512-QldCVh/ztyKJJZLr4jXNUByx3gR+TDYZCRXEktiZoUR3PGy4qCmSbkxcIle8GEwGpb5JBZazlaJ/CxLidXdEbQ==", "dev": true, "license": "MIT", + "peer": true, "dependencies": { "@eslint-community/eslint-utils": "^4.2.0", "@eslint-community/regexpp": "^4.12.1", @@ -9274,6 +9284,7 @@ } ], "license": "MIT", + "peer": true, "dependencies": { "@babel/runtime": "^7.27.6" }, @@ -10043,6 +10054,7 @@ "integrity": "sha512-Cvc9WUhxSMEo4McES3P7oK3QaXldCfNWp7pl2NNeiIFlCoLr3kfq9kb1fxftiwk1FLV7CvpvDfonxtzUDeSOPg==", "dev": true, "license": "MIT", + "peer": true, "dependencies": { "cssstyle": "^4.2.1", "data-urls": "^5.0.0", @@ -10439,7 +10451,6 @@ "integrity": "sha512-h5bgJWpxJNswbU7qCrV0tIKQCaS3blPDrqKWx+QxzuzL1zGUzij9XCWLrSLsJPu5t+eWA/ycetzYAO5IOMcWAQ==", "dev": true, "license": "MIT", - "peer": true, "bin": { "lz-string": "bin/bin.js" } @@ -12143,6 +12154,7 @@ } ], "license": "MIT", + "peer": true, "dependencies": { "nanoid": "^3.3.8", "picocolors": "^1.1.1", @@ -12310,7 +12322,6 @@ "integrity": "sha512-Qb1gy5OrP5+zDf2Bvnzdl3jsTf1qXVMazbvCoKhtKqVs4/YK4ozX4gKQJJVyNe+cajNPn0KoC0MC3FUmaHWEmQ==", "dev": true, "license": "MIT", - "peer": true, "dependencies": { "ansi-regex": "^5.0.1", "ansi-styles": "^5.0.0", @@ -12326,7 +12337,6 @@ "integrity": "sha512-quJQXlTSUGL2LH9SUXo8VwsY4soanhgo6LNSm84E1LBcE8s3O0wpdiRzyR9z/ZZJMlMWv37qOOb9pdJlMUEKFQ==", "dev": true, "license": "MIT", - "peer": true, "engines": { "node": ">=8" } @@ -12337,7 +12347,6 @@ "integrity": "sha512-Cxwpt2SfTzTtXcfOlzGEee8O+c+MmUgGrNiBcXnuWxuFJHe6a5Hz7qwhwe5OgaSYI0IJvkLqWX1ASG+cJOkEiA==", "dev": true, "license": "MIT", - "peer": true, "engines": { "node": ">=10" }, @@ -12350,8 +12359,7 @@ "resolved": "https://registry.npmjs.org/react-is/-/react-is-17.0.2.tgz", "integrity": "sha512-w2GsyukL62IJnlaff/nRegPQR94C/XXamvMWmSHRJ4y7Ts/4ocGRmTHvOs8PSE6pB3dWOrD/nueuU5sduBsQ4w==", "dev": true, - "license": "MIT", - "peer": true + "license": "MIT" }, "node_modules/prismjs": { "version": "1.30.0", @@ -12491,6 +12499,7 @@ "resolved": "https://registry.npmjs.org/react/-/react-18.3.1.tgz", "integrity": "sha512-wS+hAgJShR0KhEvPJArfuPVN1+Hz1t0Y6n5jLrGQbkb4urgPE/0Rve+1kMB1v/oWgHgm4WIcV+i7F2pTVj+2iQ==", "license": "MIT", + "peer": true, "dependencies": { "loose-envify": "^1.1.0" }, @@ -12517,6 +12526,7 @@ "resolved": "https://registry.npmjs.org/react-dom/-/react-dom-18.3.1.tgz", "integrity": "sha512-5m4nQKp+rZRb09LNH59GM4BxTh9251/ylbKIbpe7TpGxfJ+9kv6BLkLBXIjjspbgbnIBNqlI23tRnTWT0snUIw==", "license": "MIT", + "peer": true, "dependencies": { "loose-envify": "^1.1.0", "scheduler": "^0.23.2" @@ -12542,6 +12552,7 @@ "resolved": "https://registry.npmjs.org/react-hook-form/-/react-hook-form-7.56.1.tgz", "integrity": "sha512-qWAVokhSpshhcEuQDSANHx3jiAEFzu2HAaaQIzi/r9FNPm1ioAvuJSD4EuZzWd7Al7nTRKcKPnBKO7sRn+zavQ==", "license": "MIT", + "peer": true, "engines": { "node": ">=18.0.0" }, @@ -12590,6 +12601,7 @@ "resolved": "https://registry.npmjs.org/react-markdown/-/react-markdown-10.1.0.tgz", "integrity": "sha512-qKxVopLT/TyA6BX3Ue5NwabOsAzm0Q7kAPwq6L+wWDwisYs7R8vZ0nRXqq6rkueboxpkjvLGU9fWifiX/ZZFxQ==", "license": "MIT", + "peer": true, "dependencies": { "@types/hast": "^3.0.0", "@types/mdast": "^4.0.0", @@ -13172,6 +13184,7 @@ "integrity": "sha512-C5VvvgCCyfyotVITIAv+4efVytl5F7wt+/I2i9q9GZcEXW9BP52YYOXC58igUi+LFZVHukErIIqQSWwv/M3WRw==", "devOptional": true, "license": "MIT", + "peer": true, "dependencies": { "@types/estree": "1.0.7" }, @@ -14223,6 +14236,7 @@ "resolved": "https://registry.npmjs.org/tailwindcss/-/tailwindcss-3.4.17.tgz", "integrity": "sha512-w33E2aCvSDP0tW9RZuNXadXlkHXqFzSkQew/aIa2i/Sj8fThxwovwlXHSPXTbAHwEIhBFXAedUhP2tueAKP8Og==", "license": "MIT", + "peer": true, "dependencies": { "@alloc/quick-lru": "^5.2.0", "arg": "^5.0.2", @@ -14426,6 +14440,7 @@ "integrity": "sha512-M7BAV6Rlcy5u+m6oPhAPFgJTzAioX/6B0DxyvDlo9l8+T3nLKbrczg2WLUyzd45L8RqfUMyGPzekbMvX2Ldkwg==", "dev": true, "license": "MIT", + "peer": true, "engines": { "node": ">=12" }, @@ -14698,6 +14713,7 @@ "integrity": "sha512-p1diW6TqL9L07nNxvRMM7hMMw4c5XOo/1ibL4aAIGmSAt9slTE1Xgw5KWuof2uTOvCg9BY7ZRi+GaF+7sfgPeQ==", "devOptional": true, "license": "Apache-2.0", + "peer": true, "bin": { "tsc": "bin/tsc", "tsserver": "bin/tsserver" @@ -15207,6 +15223,7 @@ "integrity": "sha512-cZn6NDFE7wdTpINgs++ZJ4N49W2vRp8LCKrn3Ob1kYNtOo21vfDoaV5GzBfLU4MovSAB8uNRm4jgzVQZ+mBzPQ==", "dev": true, "license": "MIT", + "peer": true, "dependencies": { "esbuild": "^0.25.0", "fdir": "^6.4.4", @@ -15351,6 +15368,7 @@ "integrity": "sha512-M7BAV6Rlcy5u+m6oPhAPFgJTzAioX/6B0DxyvDlo9l8+T3nLKbrczg2WLUyzd45L8RqfUMyGPzekbMvX2Ldkwg==", "dev": true, "license": "MIT", + "peer": true, "engines": { "node": ">=12" }, @@ -15821,6 +15839,7 @@ "integrity": "sha512-B/gBuNg5SiMTrPkC+A2+cW0RszwxYmn6VYxB/inlBStS5nx6xHIt/ehKRhIMhqusl7a8LjQoZnjCs5vhwxOQ1g==", "dev": true, "license": "MIT", + "peer": true, "dependencies": { "fast-deep-equal": "^3.1.3", "fast-uri": "^3.0.1", @@ -15897,6 +15916,7 @@ "integrity": "sha512-fS6iqSPZDs3dr/y7Od6y5nha8dW1YnbgtsyotCVvoFGKbERG++CVRFv1meyGDE1SNItQA8BrnCw7ScdAhRJ3XQ==", "dev": true, "license": "MIT", + "peer": true, "bin": { "rollup": "dist/bin/rollup" }, diff --git a/src/components/AIMessageItem.tsx b/src/components/AIMessageItem.tsx index aaf2bcad..0a845336 100644 --- a/src/components/AIMessageItem.tsx +++ b/src/components/AIMessageItem.tsx @@ -7,6 +7,8 @@ import { UserMessage } from '@/components/UserMessage'; import OpenAI from 'openai'; import { useTheme } from '@/hooks/useTheme'; import { isEmptyMessage } from '@/lib/isEmptyMessage'; +import { Dialog, DialogPortal, DialogOverlay } from '@/components/ui/dialog'; +import * as DialogPrimitive from '@radix-ui/react-dialog'; // Type guard to check if message has reasoning content function hasReasoningContent(message: AIMessage): message is AIMessage & { reasoning_content: string } { @@ -26,6 +28,7 @@ export const AIMessageItem = memo(({ }: AIMessageItemProps) => { const [isToolExpanded, setIsToolExpanded] = useState(false); const [isReasoningExpanded, setIsReasoningExpanded] = useState(false); + const [expandedImageUrl, setExpandedImageUrl] = useState(null); const { displayTheme } = useTheme(); // Get content to display @@ -295,20 +298,90 @@ export const AIMessageItem = memo(({ // Regular rendering for non-tool messages if (message.role === 'user') { // User messages: right-aligned bubble without avatar/name + // Extract text and image parts from message content + const contentArray = Array.isArray(message.content) ? message.content : null; + const textParts = contentArray + ? contentArray.filter(part => part.type === 'text') as OpenAI.Chat.Completions.ChatCompletionContentPartText[] + : []; const userContent = typeof message.content === 'string' ? message.content - : Array.isArray(message.content) - ? message.content.filter(part => part.type === 'text') as OpenAI.Chat.Completions.ChatCompletionContentPartText[] + : textParts.length > 0 + ? textParts.map(part => part.text).join('\n') : ''; + // Extract image URLs from content array + const imageUrls = contentArray + ? contentArray + .filter(part => part.type === 'image_url') + .map(part => (part as OpenAI.Chat.Completions.ChatCompletionContentPartImage).image_url.url) + : []; + return ( -
-
-
- + <> +
+
+
+ {/* Render images first */} + {imageUrls.length > 0 && ( +
+ {imageUrls.map((url, index) => ( +
setExpandedImageUrl(url)} + > + {`User { + // Fallback if image fails to load + const target = e.target as HTMLImageElement; + target.style.display = 'none'; + const fallback = document.createElement('div'); + fallback.className = 'p-2 text-xs text-muted-foreground bg-muted rounded'; + fallback.textContent = `Image failed to load: ${url}`; + target.parentElement?.appendChild(fallback); + }} + /> +
+ ))} +
+ )} + {/* Render text content */} + {userContent && } +
-
+ + {/* Image expansion dialog */} + !open && setExpandedImageUrl(null)}> + + + setExpandedImageUrl(null)} + onEscapeKeyDown={() => setExpandedImageUrl(null)} + > + {expandedImageUrl && ( +
+ Expanded image +
+ )} +
+
+
+ ); } diff --git a/src/components/Shakespeare/ChatPane.tsx b/src/components/Shakespeare/ChatPane.tsx index 72fe5752..c8a33142 100644 --- a/src/components/Shakespeare/ChatPane.tsx +++ b/src/components/Shakespeare/ChatPane.tsx @@ -39,11 +39,11 @@ import { ProjectPreviewConsoleError } from '@/lib/consoleMessages'; import { toolToOpenAI } from '@/lib/tools/openai-adapter'; import { Tool } from '@/lib/tools/Tool'; import OpenAI from 'openai'; -import { saveFileToTmp } from '@/lib/fileUtils'; import { useGit } from '@/hooks/useGit'; import { Quilly } from '@/components/Quilly'; import { ShakespeareLogo } from '@/components/ShakespeareLogo'; import { ChatInput } from '@/components/Shakespeare/ChatInput'; +import { buildMessageContent } from '@/lib/buildMessageContent'; // Clean interfaces now handled by proper hooks @@ -438,45 +438,12 @@ export const ChatPane = forwardRef(({ const modelToUse = providerModel.trim(); - // Build message content as text parts - const contentParts: Array = []; - - // Add user input as text part if present - if (input.trim()) { - contentParts.push({ - type: 'text', - text: input.trim() - }); - } - - // Process attached files and add as separate text parts - if (attachedFiles.length > 0) { - const filePromises = attachedFiles.map(async (file) => { - try { - const savedPath = await saveFileToTmp(fs, file, tmpPath); - return `Added file: ${savedPath}`; - } catch (error) { - console.error('Failed to save file:', error); - return `Failed to save file: ${file.name}`; - } - }); - - const fileResults = await Promise.all(filePromises); - - // Add each file as a separate text part - fileResults.forEach(fileResult => { - contentParts.push({ - type: 'text', - text: fileResult - }); - }); - } + // Build message content from input and attached files + const messageContent = await buildMessageContent(input, attachedFiles, fs, tmpPath); // Add model to recently used when sending a message addRecentlyUsedModel(modelToUse); - // Send as text parts if we have multiple parts, otherwise send as string for simplicity - const messageContent = contentParts.length === 1 ? contentParts[0].text : contentParts; await sendMessage(messageContent, modelToUse); }, [addRecentlyUsedModel, fs, isConfigured, isLoading, providerModel, sendMessage, tmpPath]); diff --git a/src/hooks/useAIChat.ts b/src/hooks/useAIChat.ts index a6c1418f..5a2d3ac5 100644 --- a/src/hooks/useAIChat.ts +++ b/src/hooks/useAIChat.ts @@ -114,7 +114,10 @@ export function useAIChat({ }, [projectId]); // Actions - const sendMessage = useCallback(async (content: string | Array, providerModel: string) => { + const sendMessage = useCallback(async ( + content: string | Array, + providerModel: string + ) => { try { await initSession(); await sessionManager.sendMessage(projectId, content, providerModel); diff --git a/src/lib/SessionManager.ts b/src/lib/SessionManager.ts index f32a8d4b..89f4e36e 100644 --- a/src/lib/SessionManager.ts +++ b/src/lib/SessionManager.ts @@ -187,7 +187,11 @@ export class SessionManager { /** * Send a message and start AI generation */ - async sendMessage(projectId: string, content: string | Array, providerModel: string): Promise { + async sendMessage( + projectId: string, + content: string | Array, + providerModel: string + ): Promise { const session = this.sessions.get(projectId); if (!session || session.isLoading) return; @@ -275,9 +279,11 @@ export class SessionManager { }); // Prepare messages for AI - const messages: OpenAI.Chat.Completions.ChatCompletionMessageParam[] = systemPrompt + // Note: User messages with image_url content parts are valid ChatCompletionMessageParam types + // The AIMessage type includes ChatCompletionMessageParam, so this cast is safe + const messages: OpenAI.Chat.Completions.ChatCompletionMessageParam[] = (systemPrompt ? [{ role: 'system', content: systemPrompt }, ...session.messages] - : session.messages; + : session.messages) as OpenAI.Chat.Completions.ChatCompletionMessageParam[]; // Prepare completion options const completionOptions: OpenAI.Chat.Completions.ChatCompletionCreateParams = { @@ -609,7 +615,8 @@ export class SessionManager { try { const config = this.getConfig(); const dotAI = new DotAI(this.fs, `${config.fsPathProjects}/${session.projectId}`); - await dotAI.setHistory(session.sessionName, session.messages); + // Cast to ChatCompletionMessageParam[] - user messages with image arrays are valid + await dotAI.setHistory(session.sessionName, session.messages as OpenAI.Chat.Completions.ChatCompletionMessageParam[]); } catch (error) { console.warn('Failed to save session history:', error); } diff --git a/src/lib/buildMessageContent.ts b/src/lib/buildMessageContent.ts new file mode 100644 index 00000000..e3f17ced --- /dev/null +++ b/src/lib/buildMessageContent.ts @@ -0,0 +1,67 @@ +import type OpenAI from 'openai'; +import type { JSRuntimeFS } from '@/lib/JSRuntime'; +import { parseImageUrls } from './parseImageUrls'; +import { saveFileToTmp } from './fileUtils'; + +type ContentPart = OpenAI.Chat.Completions.ChatCompletionContentPartText | OpenAI.Chat.Completions.ChatCompletionContentPartImage; + +/** + * Builds message content from text input, image URLs, and attached files. + * Returns content as either a string (for simple text) or an array of content parts. + * + * @param input - User text input that may contain image URLs + * @param attachedFiles - Array of files to attach + * @param fs - Filesystem instance for saving files + * @param tmpPath - Temporary directory path for file storage + * @returns Promise resolving to message content (string or array of content parts) + */ +export async function buildMessageContent( + input: string, + attachedFiles: File[], + fs: JSRuntimeFS, + tmpPath = '/tmp' +): Promise { + const contentParts: ContentPart[] = []; + + // Parse user input to detect image URLs and split into content parts + if (input.trim()) { + const parsedParts = parseImageUrls(input.trim()); + contentParts.push(...parsedParts); + } + + // Process attached files and add as separate text parts + if (attachedFiles.length > 0) { + const filePromises = attachedFiles.map(async (file) => { + try { + const savedPath = await saveFileToTmp(fs, file, tmpPath); + return `Added file: ${savedPath}`; + } catch (error) { + console.error('Failed to save file:', error); + return `Failed to save file: ${file.name}`; + } + }); + + const fileResults = await Promise.all(filePromises); + + // Add each file as a separate text part + fileResults.forEach(fileResult => { + contentParts.push({ + type: 'text', + text: fileResult + }); + }); + } + + // Return as string if single text part, otherwise return array + const hasImageUrls = contentParts.some(part => part.type === 'image_url'); + if (contentParts.length > 1 || hasImageUrls) { + return contentParts; + } + + if (contentParts.length === 1 && contentParts[0].type === 'text') { + return contentParts[0].text; + } + + return contentParts; +} + diff --git a/src/lib/parseImageUrls.ts b/src/lib/parseImageUrls.ts new file mode 100644 index 00000000..68ec22c0 --- /dev/null +++ b/src/lib/parseImageUrls.ts @@ -0,0 +1,79 @@ +import type OpenAI from 'openai'; + +/** + * Detects image URLs in text and splits the text into content parts. + * Image URLs are identified by common image file extensions or data URLs. + * + * @param text - The input text that may contain image URLs + * @returns Array of content parts (text and image_url types) + */ +export function parseImageUrls( + text: string +): Array { + const trimmedText = text.trim(); + + // Return empty array if input is empty + if (!trimmedText) { + return []; + } + + // Regex to match URLs (http/https) that end with image extensions or are data URLs + // Matches: + // - http:// or https:// URLs ending with image extensions (jpg, jpeg, png, gif, webp, svg, bmp, ico) + // - URLs with optional query parameters + // - Data URLs (data:image/...;base64,...) + const imageUrlRegex = /(https?:\/\/[^\s<>"']+\.(jpg|jpeg|png|gif|webp|svg|bmp|ico)(\?[^\s<>"']*)?|data:image\/[^;]+;base64,[^\s<>"']+)/gi; + + const parts: Array = []; + let lastIndex = 0; + let match: RegExpExecArray | null; + + // Reset regex lastIndex + imageUrlRegex.lastIndex = 0; + + while ((match = imageUrlRegex.exec(trimmedText)) !== null) { + // Add text before the URL + if (match.index > lastIndex) { + const textBefore = trimmedText.substring(lastIndex, match.index).trim(); + if (textBefore) { + parts.push({ + type: 'text', + text: textBefore + }); + } + } + + // Add the image URL + const imageUrl = match[0]; + parts.push({ + type: 'image_url', + image_url: { + url: imageUrl + } + }); + + lastIndex = match.index + match[0].length; + } + + // Add remaining text after the last URL + if (lastIndex < trimmedText.length) { + const textAfter = trimmedText.substring(lastIndex).trim(); + if (textAfter) { + parts.push({ + type: 'text', + text: textAfter + }); + } + } + + // If no URLs were found, return the original text as a single text part + if (parts.length === 0) { + return [{ + type: 'text', + text: trimmedText + }]; + } + + return parts; +} + diff --git a/src/pages/Index.tsx b/src/pages/Index.tsx index cc093ad7..8dc6f3cc 100644 --- a/src/pages/Index.tsx +++ b/src/pages/Index.tsx @@ -15,8 +15,7 @@ import { GiftCardRedeemDialog } from '@/components/GiftCardRedeemDialog'; import { Quilly } from '@/components/Quilly'; import { DotAI } from '@/lib/DotAI'; import type { AIMessage } from '@/lib/SessionManager'; -import { saveFileToTmp } from '@/lib/fileUtils'; -import type OpenAI from 'openai'; +import { buildMessageContent } from '@/lib/buildMessageContent'; import { Button } from '@/components/ui/button'; import { Textarea } from '@/components/ui/textarea'; import { ModelSelector } from '@/components/ModelSelector'; @@ -231,48 +230,16 @@ export default function Index() { // Create project with AI-generated ID const project = await projectsManager.createProject(prompt.trim(), config.projectTemplate, projectId); - // Build message content as text parts (same as ChatPane) - const contentParts: Array = []; - - // Add user input as text part if present - if (prompt.trim()) { - contentParts.push({ - type: 'text', - text: prompt.trim() - }); - } - - // Process attached files and add as separate text parts - if (attachedFiles.length > 0) { - const filePromises = attachedFiles.map(async (file) => { - try { - const savedPath = await saveFileToTmp(fs, file); - return `Added file: ${savedPath}`; - } catch (error) { - console.error('Failed to save file:', error); - return `Failed to save file: ${file.name}`; - } - }); - - const fileResults = await Promise.all(filePromises); - - // Add each file as a separate text part - fileResults.forEach(fileResult => { - contentParts.push({ - type: 'text', - text: fileResult - }); - }); - } + // Build message content from input and attached files + const messageContent = await buildMessageContent(prompt.trim(), attachedFiles, fs); // Store the initial message in chat history using DotAI const dotAI = new DotAI(fs, `${config.fsPathProjects}/${project.id}`); const sessionName = DotAI.generateSessionName(); - // Create initial message with content parts (same format as ChatPane) const initialMessage: AIMessage = { role: 'user', - content: contentParts.length === 1 ? contentParts[0].text : contentParts + content: messageContent }; await dotAI.setHistory(sessionName, [initialMessage]); From 653a7c0f0c0b1068a21266f1b5ef32442b666f28 Mon Sep 17 00:00:00 2001 From: lemonknowsall Date: Sat, 15 Nov 2025 20:38:56 -0800 Subject: [PATCH 2/6] add images to both VFS and API, update ChatPane UI --- src/components/AIMessageItem.tsx | 10 +- src/components/Shakespeare/ChatPane.tsx | 13 ++- src/components/UserMessage.test.tsx | 7 +- src/components/UserMessage.tsx | 83 +++++++++---- src/lib/SessionManager.ts | 33 +++++- src/lib/buildMessageContent.ts | 85 +++++++++++--- src/lib/imageUtils.ts | 149 ++++++++++++++++++++++++ src/pages/Index.tsx | 13 ++- 8 files changed, 339 insertions(+), 54 deletions(-) create mode 100644 src/lib/imageUtils.ts diff --git a/src/components/AIMessageItem.tsx b/src/components/AIMessageItem.tsx index 0a845336..f2c6294b 100644 --- a/src/components/AIMessageItem.tsx +++ b/src/components/AIMessageItem.tsx @@ -312,8 +312,8 @@ export const AIMessageItem = memo(({ // Extract image URLs from content array const imageUrls = contentArray ? contentArray - .filter(part => part.type === 'image_url') - .map(part => (part as OpenAI.Chat.Completions.ChatCompletionContentPartImage).image_url.url) + .filter(part => part.type === 'image_url') + .map(part => (part as OpenAI.Chat.Completions.ChatCompletionContentPartImage).image_url.url) : []; return ( @@ -321,7 +321,9 @@ export const AIMessageItem = memo(({
- {/* Render images first */} + {/* Render text content and attachments first */} + {userContent && } + {/* Render images after text and attachments */} {imageUrls.length > 0 && (
{imageUrls.map((url, index) => ( @@ -349,8 +351,6 @@ export const AIMessageItem = memo(({ ))}
)} - {/* Render text content */} - {userContent && }
diff --git a/src/components/Shakespeare/ChatPane.tsx b/src/components/Shakespeare/ChatPane.tsx index c8a33142..9d52f9e7 100644 --- a/src/components/Shakespeare/ChatPane.tsx +++ b/src/components/Shakespeare/ChatPane.tsx @@ -44,6 +44,7 @@ import { Quilly } from '@/components/Quilly'; import { ShakespeareLogo } from '@/components/ShakespeareLogo'; import { ChatInput } from '@/components/Shakespeare/ChatInput'; import { buildMessageContent } from '@/lib/buildMessageContent'; +import { useUploadFile } from '@/hooks/useUploadFile'; // Clean interfaces now handled by proper hooks @@ -77,6 +78,7 @@ export const ChatPane = forwardRef(({ const { fs } = useFS(); const { git } = useGit(); const { user } = useCurrentUser(); + const { mutateAsync: uploadFile } = useUploadFile(); const { models } = useProviderModels(); const { config } = useAppContext(); const { projectsPath, tmpPath, pluginsPath } = useFSPaths(); @@ -439,13 +441,20 @@ export const ChatPane = forwardRef(({ const modelToUse = providerModel.trim(); // Build message content from input and attached files - const messageContent = await buildMessageContent(input, attachedFiles, fs, tmpPath); + // Pass uploadFile function if user is logged in + const messageContent = await buildMessageContent( + input, + attachedFiles, + fs, + tmpPath, + user ? uploadFile : undefined + ); // Add model to recently used when sending a message addRecentlyUsedModel(modelToUse); await sendMessage(messageContent, modelToUse); - }, [addRecentlyUsedModel, fs, isConfigured, isLoading, providerModel, sendMessage, tmpPath]); + }, [addRecentlyUsedModel, fs, isConfigured, isLoading, providerModel, sendMessage, tmpPath, uploadFile, user]); // Handle textarea focus - show onboarding if not configured const handleTextareaFocus = useCallback(() => { diff --git a/src/components/UserMessage.test.tsx b/src/components/UserMessage.test.tsx index c27ec8f6..bc9d4510 100644 --- a/src/components/UserMessage.test.tsx +++ b/src/components/UserMessage.test.tsx @@ -16,8 +16,11 @@ describe('UserMessage', () => { render(); - // When using string content, it should still work but won't separate file attachments - expect(screen.getByText(content)).toBeInTheDocument(); + // When using string content, it should parse and separate file attachments + expect(screen.getByText('Here is my file:')).toBeInTheDocument(); + expect(screen.getByText('test.txt')).toBeInTheDocument(); + // Full path should not be displayed + expect(screen.queryByText('/tmp/test.txt')).not.toBeInTheDocument(); }); it('renders file attachment badges for single file with text parts', () => { diff --git a/src/components/UserMessage.tsx b/src/components/UserMessage.tsx index 56285baf..fd6f4876 100644 --- a/src/components/UserMessage.tsx +++ b/src/components/UserMessage.tsx @@ -1,4 +1,4 @@ -import { FileText, File } from 'lucide-react'; +import { Paperclip } from 'lucide-react'; import { Badge } from '@/components/ui/badge'; import type OpenAI from 'openai'; @@ -18,21 +18,60 @@ export function UserMessage({ content }: UserMessageProps) { : content.filter(part => part.type === 'text') as Array<{ type: 'text'; text: string }>; // Regular expression to match "Added file: /tmp/" patterns - const filePattern = /^Added file: (\/tmp\/[^\s\n]+)$/; + // Matches the pattern anywhere in the text + const filePattern = /Added file:\s*(\/tmp\/[^\s\n]+)/g; // Process each content part and categorize as text or file const processedParts: Array<{ type: 'text' | 'file'; content: string; filepath?: string }> = []; contentParts.forEach(part => { const text = part.text.trim(); - const match = text.match(filePattern); + + // Find all file patterns in this text part + const fileMatches: Array<{ filepath: string; index: number; length: number }> = []; + let match; + filePattern.lastIndex = 0; // Reset regex + + while ((match = filePattern.exec(text)) !== null) { + fileMatches.push({ + filepath: match[1], // "/tmp/filename.txt" + index: match.index, + length: match[0].length + }); + } - if (match) { - // This is a file attachment - const filepath = match[1]; // "/tmp/filename.txt" - processedParts.push({ type: 'file', content: text, filepath }); + if (fileMatches.length > 0) { + // Split text around file patterns and process each segment + let lastIndex = 0; + + fileMatches.forEach((fileMatch) => { + // Add text before the file pattern + if (fileMatch.index > lastIndex) { + const textBefore = text.substring(lastIndex, fileMatch.index).trim(); + if (textBefore) { + processedParts.push({ type: 'text', content: textBefore }); + } + } + + // Add the file attachment badge (without showing "Added file:" text) + processedParts.push({ + type: 'file', + content: '', // Empty - badge will show filename only + filepath: fileMatch.filepath + }); + + lastIndex = fileMatch.index + fileMatch.length; + }); + + // Add remaining text after the last file pattern + if (lastIndex < text.length) { + const textAfter = text.substring(lastIndex).trim(); + if (textAfter) { + processedParts.push({ type: 'text', content: textAfter }); + } + } } else if (text) { - // This is regular text content + // No file patterns found, treat as regular text processedParts.push({ type: 'text', content: text }); } }); @@ -42,19 +81,6 @@ export function UserMessage({ content }: UserMessageProps) { return null; } - const getFileIcon = (filename: string) => { - const extension = filename.split('.').pop()?.toLowerCase(); - - // Return FileText icon for text-like files, File icon for others - const textExtensions = ['txt', 'md', 'json', 'js', 'ts', 'jsx', 'tsx', 'css', 'html', 'xml', 'yml', 'yaml']; - - if (extension && textExtensions.includes(extension)) { - return ; - } - - return ; - }; - const getFileName = (filepath: string) => { return filepath.split('/').pop() || filepath; }; @@ -63,18 +89,25 @@ export function UserMessage({ content }: UserMessageProps) {
{processedParts.map((part, index) => { if (part.type === 'text') { + // Only render text if it has content + if (!part.content.trim()) return null; return (
{part.content}
); } else { + // Render file attachment badge (no "Added file:" text) const filename = getFileName(part.filepath!); return ( -
- - {getFileIcon(filename)} - {filename} +
+ + + + + + {filename} +
); diff --git a/src/lib/SessionManager.ts b/src/lib/SessionManager.ts index 89f4e36e..ad47727e 100644 --- a/src/lib/SessionManager.ts +++ b/src/lib/SessionManager.ts @@ -278,13 +278,44 @@ export class SessionManager { template: config.systemPrompt, }); + // Helper function to filter out unsupported image formats (keep only JPG/JPEG/PNG) + const filterSupportedImages = (msgs: OpenAI.Chat.Completions.ChatCompletionMessageParam[]): OpenAI.Chat.Completions.ChatCompletionMessageParam[] => { + return msgs.map(msg => { + if (msg.role === 'user' && typeof msg.content !== 'string' && Array.isArray(msg.content)) { + const filteredContent = msg.content.filter(part => { + if (part.type !== 'image_url') return true; + + const imagePart = part as OpenAI.Chat.Completions.ChatCompletionContentPartImage; + const url = imagePart.image_url.url.toLowerCase(); + + // Keep only JPG/JPEG/PNG images + // Check file extension or data URL MIME type + return /\.(jpg|jpeg|png)(\?|$)/.test(url) || + url.startsWith('data:image/jpeg') || + url.startsWith('data:image/png') || + url.startsWith('data:image/jpg'); + }); + + return { + ...msg, + content: filteredContent + }; + } + return msg; + }); + }; + // Prepare messages for AI // Note: User messages with image_url content parts are valid ChatCompletionMessageParam types // The AIMessage type includes ChatCompletionMessageParam, so this cast is safe - const messages: OpenAI.Chat.Completions.ChatCompletionMessageParam[] = (systemPrompt + let messages: OpenAI.Chat.Completions.ChatCompletionMessageParam[] = (systemPrompt ? [{ role: 'system', content: systemPrompt }, ...session.messages] : session.messages) as OpenAI.Chat.Completions.ChatCompletionMessageParam[]; + // Filter out unsupported image formats (keep only JPG/JPEG/PNG for API) + // This ensures the UI shows all image types, but API only receives supported formats + messages = filterSupportedImages(messages); + // Prepare completion options const completionOptions: OpenAI.Chat.Completions.ChatCompletionCreateParams = { model, diff --git a/src/lib/buildMessageContent.ts b/src/lib/buildMessageContent.ts index e3f17ced..53d3ac79 100644 --- a/src/lib/buildMessageContent.ts +++ b/src/lib/buildMessageContent.ts @@ -2,66 +2,115 @@ import type OpenAI from 'openai'; import type { JSRuntimeFS } from '@/lib/JSRuntime'; import { parseImageUrls } from './parseImageUrls'; import { saveFileToTmp } from './fileUtils'; +import { fileToUrl, urlToFile } from './imageUtils'; type ContentPart = OpenAI.Chat.Completions.ChatCompletionContentPartText | OpenAI.Chat.Completions.ChatCompletionContentPartImage; /** * Builds message content from text input, image URLs, and attached files. + * Downloads image URLs to VFS and processes uploaded files. + * + * - All image formats are included in the message content for UI display + * - SessionManager filters to only pass JPG/JPEG/PNG to the OpenAI API + * - All files are saved to VFS and get a text part with the path + * * Returns content as either a string (for simple text) or an array of content parts. * * @param input - User text input that may contain image URLs * @param attachedFiles - Array of files to attach * @param fs - Filesystem instance for saving files * @param tmpPath - Temporary directory path for file storage + * @param uploadFile - Optional upload function from useUploadFile hook for converting files to URLs * @returns Promise resolving to message content (string or array of content parts) */ export async function buildMessageContent( input: string, attachedFiles: File[], fs: JSRuntimeFS, - tmpPath = '/tmp' + tmpPath = '/tmp', + uploadFile?: (file: File) => Promise> ): Promise { const contentParts: ContentPart[] = []; // Parse user input to detect image URLs and split into content parts if (input.trim()) { const parsedParts = parseImageUrls(input.trim()); - contentParts.push(...parsedParts); + + // Process each part: download image URLs to VFS and add text parts with VFS paths + for (const part of parsedParts) { + if (part.type === 'image_url') { + // Download image to VFS and get the path + const result = await urlToFile(part.image_url.url, fs, tmpPath); + + // Always add image_url part for UI display (all formats) + contentParts.push(part); + + // Always add text part with VFS path so AI knows where the file is (can manipulate it) + if (result?.vfsPath) { + contentParts.push({ + type: 'text', + text: `Added file: ${result.vfsPath}` + }); + } + } else { + contentParts.push(part); + } + } } - // Process attached files and add as separate text parts + // Process attached files: save to VFS and add image_url for UI display (all image types) if (attachedFiles.length > 0) { const filePromises = attachedFiles.map(async (file) => { try { + // Save file to VFS (always do this) const savedPath = await saveFileToTmp(fs, file, tmpPath); - return `Added file: ${savedPath}`; + + // Always add text part with VFS path + const textPart: ContentPart = { + type: 'text', + text: `Added file: ${savedPath}` + }; + + // For all image types, also add as image_url for UI display (if uploadFile available) + const isImage = file.type.startsWith('image/'); + if (isImage && uploadFile) { + try { + const imageUrl = await fileToUrl(file, uploadFile); + // Return both parts: image_url for UI display and text for VFS path + return [textPart, { + type: 'image_url' as const, + image_url: { url: imageUrl } + }]; + } catch (error) { + // If URL conversion fails, just use text part + console.warn('Failed to convert image to URL, using text part only:', error); + } + } + + return [textPart]; } catch (error) { console.error('Failed to save file:', error); - return `Failed to save file: ${file.name}`; + return [{ + type: 'text' as const, + text: `Failed to save file: ${file.name}` + }]; } }); const fileResults = await Promise.all(filePromises); - - // Add each file as a separate text part - fileResults.forEach(fileResult => { - contentParts.push({ - type: 'text', - text: fileResult - }); - }); + + // Flatten the results (each file can return multiple parts) + for (const parts of fileResults) { + contentParts.push(...parts); + } } // Return as string if single text part, otherwise return array - const hasImageUrls = contentParts.some(part => part.type === 'image_url'); - if (contentParts.length > 1 || hasImageUrls) { - return contentParts; - } - if (contentParts.length === 1 && contentParts[0].type === 'text') { return contentParts[0].text; } + // Return array for multiple parts or if contains image URLs return contentParts; } diff --git a/src/lib/imageUtils.ts b/src/lib/imageUtils.ts new file mode 100644 index 00000000..8dc67376 --- /dev/null +++ b/src/lib/imageUtils.ts @@ -0,0 +1,149 @@ +import type { JSRuntimeFS } from '@/lib/JSRuntime'; +import { generateUniqueFilename } from './fileUtils'; + +/** + * Converts a File to a URL string for API consumption. + * Tries useUploadFile first if available, otherwise falls back to data URL. + * + * @param file - The file to convert + * @param uploadFile - Optional upload function from useUploadFile hook + * @returns Promise resolving to URL string + */ +export async function fileToUrl( + file: File, + uploadFile?: (file: File) => Promise> +): Promise { + // Try useUploadFile first if available + if (uploadFile) { + try { + const tags = await uploadFile(file); + // Extract URL from NIP-94 compatible tags + // The first tag contains the URL + if (tags && tags.length > 0 && tags[0]) { + const firstTag = tags[0]; + // Handle both tuple [string, string] and array string[] formats + if (Array.isArray(firstTag) && firstTag.length > 1) { + return firstTag[1] as string; + } + } + } catch (error) { + console.warn('Failed to upload file via useUploadFile, falling back to data URL:', error); + // Fall through to data URL fallback + } + } + + // Fallback to data URL + return new Promise((resolve, reject) => { + const reader = new FileReader(); + reader.onload = () => { + if (typeof reader.result === 'string') { + resolve(reader.result); + } else { + reject(new Error('Failed to read file as data URL')); + } + }; + reader.onerror = () => { + reject(new Error('Failed to read file')); + }; + reader.readAsDataURL(file); + }); +} + +/** + * Converts a URL to a file saved in the VFS. + * Downloads an image from a URL and saves it to the VFS. + * Returns both the original URL (for API calls) and the VFS path (for reference). + * + * @param imageUrl - The image URL to download + * @param fs - Filesystem instance for saving files + * @param tmpPath - Temporary directory path for file storage + * @returns Promise resolving to object with originalUrl and vfsPath, or null if download fails + */ +export async function urlToFile( + imageUrl: string, + fs: JSRuntimeFS, + tmpPath = '/tmp' +): Promise<{ originalUrl: string; vfsPath: string } | null> { + try { + // Handle data URLs - extract and save them + if (imageUrl.startsWith('data:image/')) { + const [header, base64Data] = imageUrl.split(','); + if (!base64Data) { + console.warn('Invalid data URL format:', imageUrl); + return null; + } + + // Extract MIME type and extension from header + const mimeMatch = header.match(/data:image\/([^;]+)/); + const mimeType = mimeMatch ? mimeMatch[1] : 'png'; + const extension = mimeType === 'jpeg' ? 'jpg' : mimeType; + + // Generate filename + const filename = `downloaded_image_${Date.now()}.${extension}`; + const uniqueFilename = await generateUniqueFilename(fs, tmpPath, filename); + const vfsPath = `${tmpPath}/${uniqueFilename}`; + + // Convert base64 to Uint8Array + const binaryString = atob(base64Data); + const bytes = new Uint8Array(binaryString.length); + for (let i = 0; i < binaryString.length; i++) { + bytes[i] = binaryString.charCodeAt(i); + } + + // Write to VFS + await fs.writeFile(vfsPath, bytes); + + return { originalUrl: imageUrl, vfsPath }; + } + + // Handle HTTP/HTTPS URLs + const response = await fetch(imageUrl, { + method: 'GET', + headers: { + 'Accept': 'image/*', + }, + }); + + if (!response.ok) { + console.warn(`Failed to download image from ${imageUrl}: ${response.status} ${response.statusText}`); + return null; + } + + // Determine filename from URL or Content-Type + let filename = 'downloaded_image'; + const urlPath = new URL(imageUrl).pathname; + const urlFilename = urlPath.split('/').pop(); + + if (urlFilename && /\.(jpg|jpeg|png|gif|webp|svg|bmp|ico)$/i.test(urlFilename)) { + filename = urlFilename; + } else { + // Try to get extension from Content-Type + const contentType = response.headers.get('Content-Type'); + if (contentType?.startsWith('image/')) { + const mimeType = contentType.split('/')[1]; + const extension = mimeType === 'jpeg' ? 'jpg' : mimeType; + filename = `downloaded_image_${Date.now()}.${extension}`; + } else { + filename = `downloaded_image_${Date.now()}.png`; + } + } + + // Sanitize filename + const sanitizedFilename = filename.replace(/\s+/g, '_'); + const uniqueFilename = await generateUniqueFilename(fs, tmpPath, sanitizedFilename); + const vfsPath = `${tmpPath}/${uniqueFilename}`; + + // Read response as array buffer and convert to Uint8Array + const arrayBuffer = await response.arrayBuffer(); + const uint8Array = new Uint8Array(arrayBuffer); + + // Write to VFS + await fs.writeFile(vfsPath, uint8Array); + + return { originalUrl: imageUrl, vfsPath }; + } catch (error) { + console.warn(`Error downloading image from ${imageUrl}:`, error); + return null; + } +} + diff --git a/src/pages/Index.tsx b/src/pages/Index.tsx index 8dc6f3cc..3d13a497 100644 --- a/src/pages/Index.tsx +++ b/src/pages/Index.tsx @@ -24,6 +24,8 @@ import { ArrowUp } from 'lucide-react'; import { useSeoMeta } from '@unhead/react'; import { ShakespeareLogo } from '@/components/ShakespeareLogo'; import { AppShowcase } from '@/components/AppShowcase'; +import { useUploadFile } from '@/hooks/useUploadFile'; +import { useCurrentUser } from '@/hooks/useCurrentUser'; export default function Index() { const { t } = useTranslation(); @@ -48,6 +50,8 @@ export default function Index() { }); const isMobile = useIsMobile(); const [attachedFiles, setAttachedFiles] = useState([]); + const { user } = useCurrentUser(); + const { mutateAsync: uploadFile } = useUploadFile(); const [isDragOver, setIsDragOver] = useState(false); const [quillyError, setQuillyError] = useState(null); @@ -231,7 +235,14 @@ export default function Index() { const project = await projectsManager.createProject(prompt.trim(), config.projectTemplate, projectId); // Build message content from input and attached files - const messageContent = await buildMessageContent(prompt.trim(), attachedFiles, fs); + // Pass uploadFile function if user is logged in + const messageContent = await buildMessageContent( + prompt.trim(), + attachedFiles, + fs, + undefined, + user ? uploadFile : undefined + ); // Store the initial message in chat history using DotAI const dotAI = new DotAI(fs, `${config.fsPathProjects}/${project.id}`); From 766aea14b9066a0414c422c4677316e7162ce004 Mon Sep 17 00:00:00 2001 From: lemonknowsall Date: Sun, 16 Nov 2025 11:32:04 -0800 Subject: [PATCH 3/6] add VFS only retry for models that don't accept images --- src/lib/SessionManager.ts | 71 +++++++++++++++++++++++++++++++++++++-- 1 file changed, 68 insertions(+), 3 deletions(-) diff --git a/src/lib/SessionManager.ts b/src/lib/SessionManager.ts index ad47727e..b83f0130 100644 --- a/src/lib/SessionManager.ts +++ b/src/lib/SessionManager.ts @@ -305,6 +305,31 @@ export class SessionManager { }); }; + // Helper function to strip all image_url parts but keep text parts (including VFS paths) + const stripImageUrls = (msgs: OpenAI.Chat.Completions.ChatCompletionMessageParam[]): OpenAI.Chat.Completions.ChatCompletionMessageParam[] => { + return msgs.map(msg => { + if (msg.role === 'user' && typeof msg.content !== 'string' && Array.isArray(msg.content)) { + // Keep only text parts (this includes "Added file: /tmp/..." paths) + const textParts = msg.content.filter(part => part.type === 'text'); + + // If we had images, convert to string content (or empty if no text) + if (textParts.length > 0) { + return { + ...msg, + content: textParts.map(part => (part as OpenAI.Chat.Completions.ChatCompletionContentPartText).text).join('\n') + }; + } + + // If no text parts, return empty string + return { + ...msg, + content: '' + }; + } + return msg; + }); + }; + // Prepare messages for AI // Note: User messages with image_url content parts are valid ChatCompletionMessageParam types // The AIMessage type includes ChatCompletionMessageParam, so this cast is safe @@ -327,11 +352,51 @@ export class SessionManager { }, }; - // Generate streaming response - const stream = await openai.chat.completions.create(completionOptions, { - signal: session.abortController?.signal + // Check if messages contain any images (for retry logic) + const hasImages = messages.some(msg => { + if (msg.role === 'user' && typeof msg.content !== 'string' && Array.isArray(msg.content)) { + return msg.content.some(part => part.type === 'image_url'); + } + return false; }); + // Generate streaming response with retry logic for models that don't support images + let stream: AsyncIterable; + let retriedWithoutImages = false; + + try { + stream = await openai.chat.completions.create(completionOptions, { + signal: session.abortController?.signal + }); + } catch (error) { + // Check if this is likely an image-related error (400/404) and we haven't retried yet + const errorObj = error as Record; + const errorStatus = typeof errorObj?.status === 'number' ? errorObj.status : undefined; + const isImageError = errorStatus === 400 || errorStatus === 404 || errorStatus === 500; + + if (isImageError && hasImages && !retriedWithoutImages) { + console.warn('API call failed with image-related error, retrying without image_url parts (keeping VFS paths):', error); + retriedWithoutImages = true; + + // Strip image_url parts but keep text parts (including VFS paths) + const messagesWithoutImages = stripImageUrls(messages); + + // Update completion options with stripped messages + const retryOptions: OpenAI.Chat.Completions.ChatCompletionCreateParams = { + ...completionOptions, + messages: messagesWithoutImages + }; + + // Retry the API call + stream = await openai.chat.completions.create(retryOptions, { + signal: session.abortController?.signal + }); + } else { + // Re-throw if not an image error or already retried + throw error; + } + } + let accumulatedContent = ''; let accumulatedReasoningContent = ''; const accumulatedToolCalls: OpenAI.Chat.Completions.ChatCompletionMessageToolCall[] = []; From e88b8c90d9a2b538ee560032adc0d7d08d56fc9b Mon Sep 17 00:00:00 2001 From: lemonknowsall Date: Sun, 16 Nov 2025 17:44:17 -0800 Subject: [PATCH 4/6] prevent image loading and add image-off logo for code preview --- src/components/Shakespeare/FileEditor.tsx | 56 +++++++++++++--------- src/components/Shakespeare/PreviewPane.tsx | 8 ++++ src/lib/fileUtils.ts | 23 +++++++++ 3 files changed, 64 insertions(+), 23 deletions(-) diff --git a/src/components/Shakespeare/FileEditor.tsx b/src/components/Shakespeare/FileEditor.tsx index 3e79d416..a106bab5 100644 --- a/src/components/Shakespeare/FileEditor.tsx +++ b/src/components/Shakespeare/FileEditor.tsx @@ -3,9 +3,10 @@ import { useTranslation } from 'react-i18next'; import { Button } from '@/components/ui/button'; import { Textarea } from '@/components/ui/textarea'; import { CardContent, CardHeader, CardTitle } from '@/components/ui/card'; -import { Save, Loader2 } from 'lucide-react'; +import { Save, Loader2, ImageOff } from 'lucide-react'; import { cn } from '@/lib/utils'; import { useGitStatus } from '@/hooks/useGitStatus'; +import { isMediaFile } from '@/lib/fileUtils'; interface FileEditorProps { filePath: string; @@ -93,6 +94,7 @@ export function FileEditor({ filePath, content, onSave, isLoading, projectId }: // Get git status for the current file const currentFileGitStatus = getFileGitStatus(filePath); const gitStatusClasses = getGitStatusClasses(currentFileGitStatus); + const isMedia = isMediaFile(filePath); return (
@@ -100,32 +102,36 @@ export function FileEditor({ filePath, content, onSave, isLoading, projectId }:
{filePath}
- {hasChanges && ( + {hasChanges && !isMedia && ( {t('unsavedChanges')} )} - + {!isMedia && ( + + )}
-
- {t('languageLabel')}: {getLanguageFromPath(filePath)} -
+ {!isMedia && ( +
+ {t('languageLabel')}: {getLanguageFromPath(filePath)} +
+ )} @@ -133,6 +139,10 @@ export function FileEditor({ filePath, content, onSave, isLoading, projectId }:
+ ) : isMedia ? ( +
+ +
) : (