Skip to content

YC (S26) | Open Computer History | Continuously record your company computer work, map your workflows, help you find work worth automating, and power your agents' context

fix: ChatGPT Codex API compat, remove max context UI, cleaner diagnostics

Louis Beaumont71b04bdd13d5
diff --git a/apps/screenpipe-app-tauri/components/rewind/ai-presets-selector.tsx b/apps/screenpipe-app-tauri/components/rewind/ai-presets-selector.tsx
index a7144ce61..bf6fa2396 100644
--- a/apps/screenpipe-app-tauri/components/rewind/ai-presets-selector.tsx
+++ b/apps/screenpipe-app-tauri/components/rewind/ai-presets-selector.tsx
@@ -57,7 +57,6 @@ import {
SelectValue,
} from "@/components/ui/select";
import { Textarea } from "@/components/ui/textarea";
-import { Slider } from "@/components/ui/slider";
import { AIPreset, commands } from "@/lib/utils/tauri";
// Helper to detect UUID-like strings and format preset names nicely
@@ -308,6 +307,34 @@ export function AIProviderConfig({
formData.apiKey
) {
fetchOpenAIModels(formData.url, formData.apiKey);
+ } else if (selectedProvider === "openai-chatgpt") {
+ // Try fetching from API, fall back to known models
+ (async () => {
+ setIsLoadingModels(true);
+ try {
+ const tokenResult = await commands.chatgptOauthGetToken();
+ if (tokenResult.status === "ok") {
+ const resp = await fetch("https://api.openai.com/v1/models", {
+ headers: { Authorization: `Bearer ${tokenResult.data}` },
+ });
+ if (resp.ok) {
+ const data = await resp.json();
+ if (data.data?.length > 0) {
+ setOpenAIModels(data.data);
+ setIsLoadingModels(false);
+ return;
+ }
+ }
+ }
+ } catch { /* ignore */ }
+ // Fallback: Codex models available via ChatGPT subscription
+ setOpenAIModels([
+ { id: "gpt-5.1-codex-mini" }, { id: "gpt-5.1" },
+ { id: "gpt-5.1-codex-max" }, { id: "gpt-5.2-codex" },
+ { id: "gpt-5.2" },
+ ]);
+ setIsLoadingModels(false);
+ })();
}
}, [selectedProvider, formData.apiKey, formData.url]);
@@ -653,6 +680,7 @@ export function AIProviderConfig({
<Input
id="model"
type="text"
+ list="chatgpt-models"
placeholder="gpt-4o"
value={formData.model || ""}
onChange={(e) =>
@@ -660,6 +688,13 @@ export function AIProviderConfig({
}
className="h-7 text-xs"
/>
+ {openaiModels.length > 0 && (
+ <datalist id="chatgpt-models">
+ {openaiModels.map((model) => (
+ <option key={model.id} value={model.id} />
+ ))}
+ </datalist>
+ )}
</div>
</div>
)}
@@ -712,35 +747,10 @@ export function AIProviderConfig({
>
<span>{showAdvanced ? "▾" : "▸"}</span>
<span>advanced</span>
- <span className="text-muted-foreground/60">
- ({((formData.maxContextChars || 512000) / 1000).toFixed(0)}k context)
- </span>
</button>
{showAdvanced && (
<div className="space-y-1.5">
- <div className="space-y-0.5">
- <Label htmlFor="maxContextChars" className="flex items-center text-[10px]">
- max context
- </Label>
- <div className="flex items-center gap-2">
- <Slider
- id="maxContextChars"
- min={10000}
- max={1000000}
- step={10000}
- value={[formData.maxContextChars || 512000]}
- onValueChange={([value]) =>
- setFormData({ ...formData, maxContextChars: value })
- }
- className="flex-grow"
- />
- <span className="min-w-[32px] text-right text-[10px]">
- {((formData.maxContextChars || 512000) / 1000).toFixed(0)}k
- </span>
- </div>
- </div>
-
<div className="space-y-0.5">
<Label htmlFor="prompt" className="text-[10px]">prompt</Label>
<Textarea
@@ -1152,7 +1162,7 @@ export const AIPresetsSelector = ({
role="combobox"
aria-expanded={open}
className={cn(
- "w-full justify-between",
+ "w-full justify-between hover:bg-accent hover:text-accent-foreground",
compact && "h-8 text-xs",
selectedPresetRequiresLogin && "border-amber-500/50"
)}
@@ -1186,14 +1196,6 @@ export const AIPresetsSelector = ({
)?.model
}
</span>
- <span className="whitespace-nowrap">
- {(
- (aiPresets.find(
- (preset) => preset.id === selectedPreset,
- )?.maxContextChars || 0) / 1000
- ).toFixed(0)}
- k
- </span>
</div>
</div>
) : allowNone && isControlled ? (
@@ -1281,9 +1283,6 @@ export const AIPresetsSelector = ({
{preset.model}
</span>
</div>
- <span className="whitespace-nowrap">
- {(preset.maxContextChars / 1000).toFixed(0)}k
- </span>
<div className="flex items-center gap-1">
<Button
variant="ghost"
@@ -1372,9 +1371,6 @@ export const AIPresetsSelector = ({
{preset.model}
</span>
</div>
- <span className="whitespace-nowrap">
- {(preset.maxContextChars / 1000).toFixed(0)}k
- </span>
<div className="flex items-center gap-1">
<Button
variant="ghost"
diff --git a/apps/screenpipe-app-tauri/components/settings/ai-presets.tsx b/apps/screenpipe-app-tauri/components/settings/ai-presets.tsx
index 9605881fc..0976c3b6e 100644
--- a/apps/screenpipe-app-tauri/components/settings/ai-presets.tsx
+++ b/apps/screenpipe-app-tauri/components/settings/ai-presets.tsx
@@ -4,6 +4,7 @@
import { useState, useEffect, useMemo, useCallback, useRef } from "react";
import { open as openUrl } from "@tauri-apps/plugin-shell";
+import { fetch as tauriFetch } from "@tauri-apps/plugin-http";
import { Button } from "../ui/button";
import {
DEFAULT_PROMPT,
@@ -17,7 +18,6 @@ import {
ChevronsUpDown,
Eye,
EyeOff,
- HelpCircle,
Loader2,
Plus,
RefreshCw,
@@ -39,7 +39,6 @@ import {
TooltipProvider,
TooltipTrigger,
} from "../ui/tooltip";
-import { Slider } from "../ui/slider";
import { Popover, PopoverContent, PopoverTrigger } from "../ui/popover";
import {
Command,
@@ -70,7 +69,6 @@ import {
validatePresetName,
validateUrl,
validateApiKey,
- validateContextLength,
debounce,
FieldValidationResult
} from "@/lib/utils/validation";
@@ -234,14 +232,6 @@ const AISection = ({
}
}
- // Validate context length
- if (presetData.maxContextChars && presetData.model) {
- const contextValidation = validateContextLength(presetData.maxContextChars, presetData.model);
- if (!contextValidation.isValid && contextValidation.error) {
- errors.maxContextChars = contextValidation.error;
- }
- }
-
setValidationErrors(errors);
}, 300),
[settings.aiPresets, preset?.id]
@@ -378,10 +368,6 @@ const AISection = ({
updateSettingsPreset({ apiKey: value });
}, [updateSettingsPreset]);
- const handleMaxContextCharsChange = useCallback((value: number[]) => {
- updateSettingsPreset({ maxContextChars: value[0] });
- }, [updateSettingsPreset]);
-
const handleCustomPromptChange = useCallback((value: string, isValid: boolean) => {
updateSettingsPreset({ prompt: value });
}, [updateSettingsPreset]);
@@ -406,7 +392,7 @@ const AISection = ({
break;
case "openai-chatgpt":
newUrl = "https://api.openai.com/v1";
- newModel = "gpt-5.3-codex";
+ newModel = "gpt-5.1-codex-mini";
break;
case "pi":
newUrl = ""; // Pi uses RPC mode, not HTTP
@@ -425,7 +411,7 @@ const AISection = ({
const [isLoadingModels, setIsLoadingModels] = useState(false);
const runDiagnostics = useCallback(async () => {
- if (settingsPreset?.provider === "pi" || settingsPreset?.provider === "openai-chatgpt") return;
+ if (settingsPreset?.provider === "pi") return;
// Abort any previous run
diagnosticsAbortRef.current?.abort();
@@ -456,14 +442,28 @@ const AISection = ({
let modelsUrl: string;
if (settingsPreset?.provider === "native-ollama") {
modelsUrl = "http://localhost:11434/api/tags";
- } else if (settingsPreset?.provider === "openai") {
+ } else if (settingsPreset?.provider === "openai" || settingsPreset?.provider === "openai-chatgpt") {
modelsUrl = "https://api.openai.com/v1/models";
} else {
modelsUrl = `${settingsPreset?.url}/models`;
}
const headers: Record<string, string> = {};
- if (settingsPreset?.apiKey) {
+ if (settingsPreset?.provider === "openai-chatgpt") {
+ // Get OAuth token for ChatGPT provider
+ try {
+ const tokenResult = await commands.chatgptOauthGetToken();
+ if (tokenResult.status === "ok") {
+ headers["Authorization"] = `Bearer ${tokenResult.data}`;
+ } else {
+ skipRemaining("auth", "Could not get ChatGPT token. Try signing out and back in.");
+ return;
+ }
+ } catch (err) {
+ skipRemaining("auth", `Could not get ChatGPT token: ${err}. You may need to rebuild the app.`);
+ return;
+ }
+ } else if (settingsPreset?.apiKey) {
headers["Authorization"] = `Bearer ${settingsPreset.apiKey}`;
}
@@ -496,89 +496,117 @@ const AISection = ({
// Step 1 pass
setTestResults((prev) => ({
...prev,
- endpoint: { status: "pass", message: `GET ${modelsResponse.status}` },
+ endpoint: { status: "pass", message: isChatGpt ? "Reachable (OAuth)" : `GET ${modelsResponse.status}` },
auth: { status: "running", message: "Checking..." },
}));
// Step 2: Auth check
- if (modelsResponse.status === 401 || modelsResponse.status === 403) {
+ // ChatGPT OAuth tokens lack model.read scope so /v1/models returns 403 — skip to chat test
+ if (settingsPreset?.provider === "openai-chatgpt" && (modelsResponse.status === 403 || modelsResponse.status === 401)) {
+ setTestResults((prev) => ({
+ ...prev,
+ auth: { status: "pass", message: "OAuth token present" },
+ models: { status: "pass", message: "Using known models (API scope limited)" },
+ chat: { status: "running", message: "Sending test message..." },
+ }));
+ } else if (modelsResponse.status === 401 || modelsResponse.status === 403) {
const hint =
settingsPreset?.provider === "openai"
? "Check your API key at platform.openai.com"
: "Check your API key is valid and has credits";
skipRemaining("auth", `${modelsResponse.status} Unauthorized. ${hint}`);
return;
- }
-
- if (!modelsResponse.ok) {
+ } else if (!modelsResponse.ok) {
skipRemaining("auth", `Unexpected status ${modelsResponse.status}`);
return;
+ } else {
+ setTestResults((prev) => ({
+ ...prev,
+ auth: { status: "pass", message: "API key accepted" },
+ models: { status: "running", message: "Loading..." },
+ }));
}
- setTestResults((prev) => ({
- ...prev,
- auth: { status: "pass", message: "API key accepted" },
- models: { status: "running", message: "Loading..." },
- }));
-
- // Step 3: Parse models
- let modelCount = 0;
- try {
- const data = await modelsResponse.json();
- if (settingsPreset?.provider === "native-ollama") {
- const ollamaModels = (data.models || []).map((m: any) => ({
- id: m.name,
- name: m.name,
- provider: "ollama",
- }));
- modelCount = ollamaModels.length;
- setModels(ollamaModels);
- } else {
- const apiModels = (data.data || []).map((m: any) => ({
- id: m.id,
- name: m.id,
- provider: settingsPreset?.provider || "custom",
- }));
- modelCount = apiModels.length;
- setModels(apiModels);
+ // Step 3: Parse models (skip for openai-chatgpt when /v1/models returned 403)
+ if (modelsResponse.ok) {
+ let modelCount = 0;
+ try {
+ const data = await modelsResponse.json();
+ if (settingsPreset?.provider === "native-ollama") {
+ const ollamaModels = (data.models || []).map((m: any) => ({
+ id: m.name,
+ name: m.name,
+ provider: "ollama",
+ }));
+ modelCount = ollamaModels.length;
+ setModels(ollamaModels);
+ } else {
+ const apiModels = (data.data || []).map((m: any) => ({
+ id: m.id,
+ name: m.id,
+ provider: settingsPreset?.provider || "custom",
+ }));
+ modelCount = apiModels.length;
+ setModels(apiModels);
+ }
+ } catch {
+ if (abort.signal.aborted) return;
+ skipRemaining("models", "Failed to parse models response");
+ return;
}
- } catch {
- if (abort.signal.aborted) return;
- skipRemaining("models", "Failed to parse models response");
- return;
- }
- if (abort.signal.aborted) return;
+ if (abort.signal.aborted) return;
- setTestResults((prev) => ({
- ...prev,
- models: { status: "pass", message: `${modelCount} model${modelCount !== 1 ? "s" : ""} loaded` },
- chat: { status: "running", message: "Sending test message..." },
- }));
+ setTestResults((prev) => ({
+ ...prev,
+ models: { status: "pass", message: `${modelCount} model${modelCount !== 1 ? "s" : ""} loaded` },
+ chat: { status: "running", message: "Sending test message..." },
+ }));
+ }
- // Step 4: Test chat completion
+ // Step 4: Test chat completion (or Codex Responses API for ChatGPT OAuth)
+ const isChatGpt = settingsPreset?.provider === "openai-chatgpt";
let chatUrl: string;
if (settingsPreset?.provider === "native-ollama") {
chatUrl = "http://localhost:11434/v1/chat/completions";
} else if (settingsPreset?.provider === "openai") {
chatUrl = "https://api.openai.com/v1/chat/completions";
+ } else if (isChatGpt) {
+ chatUrl = "https://chatgpt.com/backend-api/codex/responses";
} else {
chatUrl = `${settingsPreset?.url}/chat/completions`;
}
+ const chatBody = isChatGpt
+ ? { model: settingsPreset?.model || "", instructions: "reply briefly", input: [{ role: "user", content: "say hi" }], store: false, stream: true }
+ : { model: settingsPreset?.model || "", messages: [{ role: "user", content: "say hi" }], max_tokens: 50 };
+
+ // For ChatGPT Codex endpoint, extract account ID from JWT and add required headers
+ const chatHeaders: Record<string, string> = {
+ "Content-Type": "application/json",
+ ...headers,
+ };
+ if (isChatGpt && headers["Authorization"]) {
+ try {
+ const token = headers["Authorization"].replace("Bearer ", "");
+ const payload = JSON.parse(atob(token.split(".")[1]));
+ const accountId = payload?.["https://api.openai.com/auth"]?.chatgpt_account_id;
+ if (accountId) {
+ chatHeaders["chatgpt-account-id"] = accountId;
+ }
+ } catch { /* ignore JWT parse errors */ }
+ chatHeaders["OpenAI-Beta"] = "responses=experimental";
+ }
+
+ // Use tauriFetch for chatgpt.com to bypass CORS
+ const fetchFn = isChatGpt ? tauriFetch : fetch;
+
const chatStart = performance.now();
try {
- const chatResponse = await fetch(chatUrl, {
+ const chatResponse = await fetchFn(chatUrl, {
method: "POST",
- headers: {
- "Content-Type": "application/json",
- ...headers,
- },
- body: JSON.stringify({
- model: settingsPreset?.model || "",
- messages: [{ role: "user", content: "say hi" }],
- max_tokens: 50,
- }),
+ headers: chatHeaders,
+ body: JSON.stringify(chatBody),
signal: abort.signal,
});
@@ -598,9 +626,14 @@ const AISection = ({
return;
}
- const chatData = await chatResponse.json();
- const reply =
- chatData.choices?.[0]?.message?.content?.slice(0, 100) || "No response";
+ let reply: string;
+ if (isChatGpt) {
+ // Streaming SSE — just confirm we got a 200 response
+ reply = "Stream started OK";
+ } else {
+ const chatData = await chatResponse.json();
+ reply = chatData.choices?.[0]?.message?.content?.slice(0, 100) || "No response";
+ }
if (abort.signal.aborted) return;
@@ -742,11 +775,10 @@ const AISection = ({
console.error("[chatgpt] model fetch error:", err);
}
if (!loaded) {
- // Known models available via ChatGPT Plus/Pro OAuth
- // (user can also type any model name in the field)
+ // Codex models available via ChatGPT Plus/Pro subscription
setModels([
- "gpt-5.3-codex", "gpt-5.2-codex", "gpt-5.2",
- "gpt-5.1", "gpt-5-codex-mini", "o4-mini",
+ "gpt-5.1-codex-mini", "gpt-5.1", "gpt-5.1-codex-max",
+ "gpt-5.2-codex", "gpt-5.2",
].map((id) => ({ id, name: id, provider: "openai-chatgpt" })));
}
break;
@@ -797,20 +829,20 @@ const AISection = ({
// Auto-trigger diagnostics when provider + url + apiKey are set (debounced)
useEffect(() => {
- if (settingsPreset?.provider === "pi" || settingsPreset?.provider === "openai-chatgpt") return;
+ if (settingsPreset?.provider === "pi") return;
if (!settingsPreset?.provider) return;
const needsApiKey =
settingsPreset.provider === "openai" || settingsPreset.provider === "custom";
if (needsApiKey && !settingsPreset.apiKey) return;
- if (settingsPreset.provider === "native-ollama" || settingsPreset.url) {
+ if (settingsPreset.provider === "openai-chatgpt" || settingsPreset.provider === "native-ollama" || settingsPreset.url) {
const timer = setTimeout(() => {
runDiagnostics();
}, 1000);
return () => clearTimeout(timer);
}
- }, [settingsPreset?.provider, settingsPreset?.url, settingsPreset?.apiKey, runDiagnostics]);
+ }, [settingsPreset?.provider, settingsPreset?.url, settingsPreset?.apiKey, runDiagnostics, chatgptLoggedIn]);
// Cleanup abort controller on unmount
useEffect(() => {
@@ -1114,56 +1146,7 @@ const AISection = ({
helperText="This prompt will be used to guide the AI's responses"
/>
- <div className="w-full">
- <div className="flex flex-col gap-4 mb-4 w-full">
- <Label htmlFor="aiMaxContextChars" className="flex items-center">
- Max Context Characters{" "}
- <TooltipProvider>
- <Tooltip>
- <TooltipTrigger asChild>
- <HelpCircle className="ml-2 h-4 w-4 cursor-default" />
- </TooltipTrigger>
- <TooltipContent side="left">
- <p>
- Maximum number of characters (think 4 characters per token)
- to send to the AI model. <br />
- Usually, OpenAI models support up to 200k tokens, which is
- roughly 1M characters. <br />
- We&apos;ll use this for UI purposes to show you how much you
- can send.
- </p>
- </TooltipContent>
- </Tooltip>
- </TooltipProvider>
- {validationErrors.maxContextChars && (
- <AlertCircle className="h-4 w-4 text-destructive ml-1" />
- )}
- </Label>
- <div className="flex-grow flex items-center">
- <Slider
- id="aiMaxContextChars"
- min={1000}
- max={2000000}
- step={10000}
- value={
- settingsPreset?.maxContextChars
- ? [settingsPreset?.maxContextChars]
- : [512000]
- }
- onValueChange={handleMaxContextCharsChange}
- className="flex-grow"
- />
- <span className="ml-2 min-w-[80px] text-right">
- {(settingsPreset?.maxContextChars ?? 512000).toLocaleString()}
- </span>
- </div>
- {validationErrors.maxContextChars && (
- <p className="text-sm text-destructive">{validationErrors.maxContextChars}</p>
- )}
- </div>
- </div>
-
- {settingsPreset?.provider !== "pi" && settingsPreset?.provider !== "openai-chatgpt" && (
+ {settingsPreset?.provider !== "pi" && (
<div className="w-full border rounded-lg">
<button
type="button"
@@ -1431,7 +1414,6 @@ export const AIPresets = () => {
aiModel: selectedPreset.model,
aiProviderType: selectedPreset.provider,
customPrompt: selectedPreset.prompt,
- aiMaxContextChars: selectedPreset.maxContextChars,
aiUrl: selectedPreset.url,
};
@@ -1577,12 +1559,6 @@ export const AIPresets = () => {
{preset.model || 'Not set'}
</span>
</div>
- <div className="flex items-center gap-2">
- <span className="font-medium">Context:</span>
- <span>
- {preset.maxContextChars?.toLocaleString() || '512,000'} chars
- </span>
- </div>
</div>
</div>
diff --git a/apps/screenpipe-app-tauri/components/standalone-chat.tsx b/apps/screenpipe-app-tauri/components/standalone-chat.tsx
index 297c1736a..190df254f 100644
--- a/apps/screenpipe-app-tauri/components/standalone-chat.tsx
+++ b/apps/screenpipe-app-tauri/components/standalone-chat.tsx
@@ -166,7 +166,7 @@ interface Message {
role: "user" | "assistant";
content: string; // full text for copy/history
displayContent?: string; // short label shown in chat (e.g. template name)
- image?: string; // base64 data URL of attached image
+ images?: string[]; // base64 data URLs of attached images
timestamp: number;
contentBlocks?: ContentBlock[];
}
@@ -608,25 +608,29 @@ function MessageContent({ message }: { message: Message }) {
);
}
+ // Render attached image thumbnails for user messages
+ const imageThumbs = isUser && message.images && message.images.length > 0 ? (
+ <div className="flex gap-1.5 flex-wrap">
+ {message.images.map((img, i) => (
+ // eslint-disable-next-line @next/next/no-img-element
+ <img key={i} src={img} alt={`Attached ${i + 1}`} className="max-w-[120px] max-h-[80px] rounded border border-background/20 object-cover" />
+ ))}
+ </div>
+ ) : null;
+
// Fallback: plain text message (user messages, non-Pi assistant messages)
// For user messages with a display label, show the short label with expand toggle
if (isUser && message.displayContent) {
return (
<div className="space-y-2">
- {message.image && (
- // eslint-disable-next-line @next/next/no-img-element
- <img src={message.image} alt="Attached" className="max-w-[120px] max-h-[80px] rounded border border-background/20 object-cover" />
- )}
+ {imageThumbs}
<CollapsibleUserMessage label={message.displayContent} fullContent={message.content} />
</div>
);
}
return (
<div className="space-y-2">
- {isUser && message.image && (
- // eslint-disable-next-line @next/next/no-img-element
- <img src={message.image} alt="Attached" className="max-w-[120px] max-h-[80px] rounded border border-background/20 object-cover" />
- )}
+ {imageThumbs}
<MarkdownBlock text={message.content} isUser={isUser} />
</div>
);
@@ -712,7 +716,7 @@ export function StandaloneChat({ className }: { className?: string } = {}) {
const [prefillContext, setPrefillContext] = useState<string | null>(null);
const [prefillSource, setPrefillSource] = useState<string>("search");
const [prefillFrameId, setPrefillFrameId] = useState<number | null>(null);
- const [pastedImage, setPastedImage] = useState<string | null>(null); // Base64 data URL
+ const [pastedImages, setPastedImages] = useState<string[]>([]); // Base64 data URLs
const [isDragging, setIsDragging] = useState(false);
const isEmbedded = !!className; // embedded in settings vs overlay panel
@@ -781,7 +785,7 @@ export function StandaloneChat({ className }: { className?: string } = {}) {
reader.onload = async (event) => {
const base64 = event.target?.result as string;
const resized = await resizeImage(base64);
- setPastedImage(resized);
+ setPastedImages(prev => [...prev, resized]);
};
reader.readAsDataURL(file);
}, [resizeImage]);
@@ -848,7 +852,7 @@ export function StandaloneChat({ className }: { className?: string } = {}) {
content,
timestamp: m.timestamp,
...(blocks?.length ? { contentBlocks: blocks } : {}),
- ...(m.image ? { image: m.image } : {}),
+ ...(m.images?.length ? { images: m.images } : {}),
};
}),
createdAt: existingIndex >= 0 ? history.conversations[existingIndex].createdAt : Date.now(),
@@ -942,7 +946,7 @@ export function StandaloneChat({ className }: { className?: string } = {}) {
content: m.content,
timestamp: m.timestamp,
...(m.contentBlocks?.length ? { contentBlocks: m.contentBlocks } : {}),
- ...((m as any).image ? { image: (m as any).image } : {}),
+ ...((m as any).images?.length ? { images: (m as any).images } : (m as any).image ? { images: [(m as any).image] } : {}),
})));
setConversationId(conv.id);
setShowHistory(false);
@@ -992,7 +996,7 @@ export function StandaloneChat({ className }: { className?: string } = {}) {
setInput("");
if (inputRef.current) inputRef.current.style.height = "auto";
setShowHistory(false);
- setPastedImage(null);
+ setPastedImages([]);
piSessionSyncedRef.current = true;
};
@@ -1042,7 +1046,7 @@ export function StandaloneChat({ className }: { className?: string } = {}) {
return groups;
}, [filteredConversations]);
- // Read an image file by path and set it as pastedImage (base64 data URL)
+ // Read an image file by path and append it to pastedImages (base64 data URL)
const loadImageFromPath = useCallback(async (filePath: string) => {
const ext = filePath.split(".").pop()?.toLowerCase() || "";
const imageExts = ["png", "jpg", "jpeg", "gif", "webp", "bmp", "svg"];
@@ -1064,7 +1068,7 @@ export function StandaloneChat({ className }: { className?: string } = {}) {
const b64 = btoa(binary);
const dataUrl = `data:${mime};base64,${b64}`;
const resized = await resizeImage(dataUrl);
- setPastedImage(resized);
+ setPastedImages(prev => [...prev, resized]);
} catch (err) {
console.error("failed to read dropped image:", err);
}
@@ -1433,7 +1437,7 @@ export function StandaloneChat({ className }: { className?: string } = {}) {
// Enter without shift submits the form
if (e.key === "Enter" && !e.shiftKey && !showMentionDropdown) {
e.preventDefault();
- if (input.trim() && !isLoading) {
+ if ((input.trim() || pastedImages.length > 0) && !isLoading) {
sendMessage(input.trim());
}
return;
@@ -2088,6 +2092,13 @@ export function StandaloneChat({ className }: { className?: string } = {}) {
prev.map((m) => m.id === msgId ? { ...m, content: "Rate limited — try again in a moment or switch to a different model." } : m)
);
}
+ } else if (line.includes("content must be a string") || line.includes("does not support images") || line.includes("image_url is not supported")) {
+ const msgId = piMessageIdRef.current;
+ if (msgId) {
+ setMessages((prev) =>
+ prev.map((m) => m.id === msgId ? { ...m, content: "This model doesn't support images — try a vision-capable model (e.g. llama-4-scout on Groq, gpt-4o on OpenAI)." } : m)
+ );
+ }
} else if (line.includes("not found") || line.includes("ECONNREFUSED") || line.includes("connection refused")) {
let hint = line;
if (line.includes("not found")) {
@@ -2376,7 +2387,7 @@ export function StandaloneChat({ className }: { className?: string } = {}) {
role: "user",
content: userMessage,
...(displayLabel ? { displayContent: displayLabel } : {}),
- ...(pastedImage ? { image: pastedImage } : {}),
+ ...(pastedImages.length > 0 ? { images: [...pastedImages] } : {}),
timestamp: Date.now(),
};
@@ -2451,9 +2462,8 @@ export function StandaloneChat({ className }: { className?: string } = {}) {
setPrefillContext(null);
}
- if (pastedImage) {
- // pastedImage is a data URL like "data:image/png;base64,..."
- const match = pastedImage.match(/^data:(image\/[^;]+);base64,(.+)$/);
+ for (const img of pastedImages) {
+ const match = img.match(/^data:(image\/[^;]+);base64,(.+)$/);
if (match) {
piImages.push({
type: "image",
@@ -2461,8 +2471,8 @@ export function StandaloneChat({ className }: { className?: string } = {}) {
data: match[2],
});
}
- setPastedImage(null);
}
+ if (pastedImages.length > 0) setPastedImages([]);
setMessages((prev) => [
...prev,
@@ -2661,7 +2671,7 @@ export function StandaloneChat({ className }: { className?: string } = {}) {
const handleSubmit = (e: React.FormEvent) => {
e.preventDefault();
- if (!input.trim() || isLoading) return;
+ if ((!input.trim() && pastedImages.length === 0) || isLoading) return;
sendMessage(input.trim());
};
@@ -3279,29 +3289,31 @@ export function StandaloneChat({ className }: { className?: string } = {}) {
"flex w-full border border-border bg-input px-3 py-2 text-sm font-mono ring-offset-background placeholder:text-muted-foreground focus-visible:outline-none focus-visible:border-foreground disabled:cursor-not-allowed disabled:opacity-50 caret-foreground resize-none overflow-y-auto",
"flex-1 bg-background/50 border-border/50 focus:border-foreground/30 focus:ring-foreground/10 transition-colors",
disabledReason && "border-muted-foreground/30",
- pastedImage && "pr-14" // Make room for image preview
+ pastedImages.length > 0 && "pb-12" // Make room for image previews below
)}
style={{ maxHeight: "150px" }}
/>
- {/* Pasted image preview inside input */}
- {pastedImage && (
- <div className="absolute right-2 top-2 flex items-center gap-1">
- <div className="relative group">
- {/* eslint-disable-next-line @next/next/no-img-element */}
- <img
- src={pastedImage}
- alt="Pasted"
- className="h-7 w-7 object-cover rounded border border-border/50"
- />
- <button
- type="button"
- onClick={() => setPastedImage(null)}
- className="absolute -top-1.5 -right-1.5 w-4 h-4 bg-destructive text-destructive-foreground rounded-full flex items-center justify-center opacity-0 group-hover:opacity-100 transition-opacity"
- >
- <X className="w-2.5 h-2.5" />
- </button>
- </div>
+ {/* Attached image previews below textarea */}
+ {pastedImages.length > 0 && (
+ <div className="absolute bottom-1 left-2 right-2 flex items-center gap-1.5 overflow-x-auto py-1">
+ {pastedImages.map((img, i) => (
+ <div key={i} className="relative group shrink-0">
+ {/* eslint-disable-next-line @next/next/no-img-element */}
+ <img
+ src={img}
+ alt={`Attached ${i + 1}`}
+ className="h-8 w-8 object-cover rounded border border-border/50"
+ />
+ <button
+ type="button"
+ onClick={() => setPastedImages(prev => prev.filter((_, idx) => idx !== i))}
+ className="absolute -top-1.5 -right-1.5 w-4 h-4 bg-destructive text-destructive-foreground rounded-full flex items-center justify-center opacity-0 group-hover:opacity-100 transition-opacity"
+ >
+ <X className="w-2.5 h-2.5" />
+ </button>
+ </div>
+ ))}
</div>
)}
@@ -3369,7 +3381,7 @@ export function StandaloneChat({ className }: { className?: string } = {}) {
<Button
type={isStreaming ? "button" : "submit"}
size="icon"
- disabled={(!input.trim() && !isStreaming) || !canChat}
+ disabled={(!input.trim() && !isStreaming && pastedImages.length === 0) || !canChat}
onClick={isStreaming ? handleStop : undefined}
className={cn(
"shrink-0 transition-all duration-200",
diff --git a/apps/screenpipe-app-tauri/src-tauri/src/main.rs b/apps/screenpipe-app-tauri/src-tauri/src/main.rs
index 06930c7dc..c0dd6241c 100755
--- a/apps/screenpipe-app-tauri/src-tauri/src/main.rs
+++ b/apps/screenpipe-app-tauri/src-tauri/src/main.rs
@@ -1501,6 +1501,7 @@ async fn main() {
// ChatGPT OAuth commands
chatgpt_oauth::chatgpt_oauth_login,
chatgpt_oauth::chatgpt_oauth_status,
+ chatgpt_oauth::chatgpt_oauth_get_token,
chatgpt_oauth::chatgpt_oauth_logout,
chatgpt_oauth::chatgpt_oauth_models,
// Reminders commands
diff --git a/apps/screenpipe-app-tauri/src-tauri/src/pi.rs b/apps/screenpipe-app-tauri/src-tauri/src/pi.rs
index 534d5a51b..ee1789ea4 100644
--- a/apps/screenpipe-app-tauri/src-tauri/src/pi.rs
+++ b/apps/screenpipe-app-tauri/src-tauri/src/pi.rs
@@ -517,15 +517,21 @@ fn ensure_pi_config(
_ => "".to_string(),
};
+ let wire_api = if config.provider == "openai-chatgpt" {
+ "openai-codex-responses"
+ } else {
+ "openai-completions"
+ };
+
let user_provider = json!({
"baseUrl": base_url,
- "api": "openai-completions",
+ "api": wire_api,
"apiKey": api_key,
"models": [
{
"id": config.model,
"name": config.model,
- "input": ["text"],
+ "input": ["text", "image"],
"contextWindow": 128000,
"maxTokens": 16384,
"cost": {"input": 0, "output": 0, "cacheRead": 0, "cacheWrite": 0}
diff --git a/crates/screenpipe-core/src/agents/pi.rs b/crates/screenpipe-core/src/agents/pi.rs
index ce955f001..eb4fe7606 100644
--- a/crates/screenpipe-core/src/agents/pi.rs
+++ b/crates/screenpipe-core/src/agents/pi.rs
@@ -231,7 +231,7 @@ impl PiExecutor {
"models": [{
"id": mdl,
"name": mdl,
- "input": ["text"],
+ "input": ["text", "image"],
"contextWindow": 128000,
"maxTokens": 16384,
"cost": {"input": 0, "output": 0, "cacheRead": 0, "cacheWrite": 0}