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
Rust agentsagiaiai-memoryaudio-recordingcomputer-visionhermeshermes-agentllmlocal-ailocal-firstmachine-learningmcpmultimodalopenclawprivacyrewindscreen-recordingspeech-to-textycombinator
feat(app): add opencode sidecar support as AI provider (#2114)
Louis Beaumont3955e173ed00
diff --git a/screenpipe-app-tauri/bun.lock b/screenpipe-app-tauri/bun.lockindex a69275e25..a8b49a85e 100644--- a/screenpipe-app-tauri/bun.lock+++ b/screenpipe-app-tauri/bun.lock@@ -5,6 +5,7 @@"": {"name": "screenpipe-app","dependencies": {+ "@opencode-ai/sdk": "^1.1.44","@patternfly/react-core": "^6.1.0","@patternfly/react-log-viewer": "^6.1.0","@radix-ui/react-accordion": "^1.2.0",@@ -360,6 +361,8 @@"@nodelib/fs.walk": ["@nodelib/[email protected]", "", { "dependencies": { "@nodelib/fs.scandir": "2.1.5", "fastq": "^1.6.0" } }, ""],+ "@opencode-ai/sdk": ["@opencode-ai/[email protected]", "", {}, "sha512-coQgtSSCbY46/GY+M5zG0rChiLSJWSjPERRt5L1hbjvDWvErelVV0ILPbd1+3CwJLFTedBYgotby2TcO8U0IfQ=="],+"@opentelemetry/api": ["@opentelemetry/[email protected]", "", {}, ""],"@opentelemetry/api-logs": ["@opentelemetry/[email protected]", "", { "dependencies": { "@opentelemetry/api": "^1.3.0" } }, "sha512-CjruKY9V6NMssL/T1kAFgzosF1v9o6oeN+aX5JB/C/xPNtmgIJqcXHG7fA82Ou1zCpWGl4lROQUKwUNE1pMCyg=="],diff --git a/screenpipe-app-tauri/components/global-chat.tsx b/screenpipe-app-tauri/components/global-chat.tsxindex 36c24794c..6686cef72 100644--- a/screenpipe-app-tauri/components/global-chat.tsx+++ b/screenpipe-app-tauri/components/global-chat.tsx@@ -10,7 +10,7 @@ import { Button } from "@/components/ui/button";import { CustomDialogContent } from "@/components/rewind/custom-dialog-content";import { useSettings, ChatMessage, ChatConversation } from "@/lib/hooks/use-settings";import { cn } from "@/lib/utils";-import { Loader2, Send, Square, User, X, Settings, ExternalLink, Video, Plus, Zap, History, Search, Trash2, ChevronLeft, Copy, Check } from "lucide-react";+import { Loader2, Send, Square, User, X, Settings, ExternalLink, Video, Plus, FolderOpen, Zap, History, Search, Trash2, ChevronLeft, Copy, Check } from "lucide-react";import { toast } from "@/components/ui/use-toast";import { parseInt } from "lodash";import { motion, AnimatePresence } from "framer-motion";@@ -23,11 +23,15 @@ import remarkGfm from "remark-gfm";import OpenAI from "openai";import { ChatCompletionTool } from "openai/resources/chat/completions";import { open as openUrl } from "@tauri-apps/plugin-shell";+import { open as openDialog } from "@tauri-apps/plugin-dialog";import { usePlatform } from "@/lib/hooks/use-platform";import { useTimelineSelection } from "@/lib/hooks/use-timeline-selection";import { useSqlAutocomplete } from "@/lib/hooks/use-sql-autocomplete";-import { commands } from "@/lib/utils/tauri";+import { commands, OpencodeInfo } from "@/lib/utils/tauri";import { UpgradeDialog } from "@/components/upgrade-dialog";+import { createOpencodeClient } from "@opencode-ai/sdk/v2/client";++type OpencodeClient = ReturnType<typeof createOpencodeClient>;const SCREENPIPE_API = "http://localhost:3030";@@ -555,6 +559,13 @@ export function GlobalChat() {const [upgradeReason, setUpgradeReason] = useState<"daily_limit" | "model_not_allowed">("daily_limit");const [upgradeResetsAt, setUpgradeResetsAt] = useState<string | undefined>();+ // OpenCode state+ const [opencodeInfo, setOpencodeInfo] = useState<OpencodeInfo | null>(null);+ const [opencodeClient, setOpencodeClient] = useState<OpencodeClient | null>(null);+ const [opencodeSessionId, setOpencodeSessionId] = useState<string | null>(null);+ const [opencodeProjectDir, setOpencodeProjectDir] = useState<string>("");+ const [opencodeStarting, setOpencodeStarting] = useState(false);+// Chat history stateconst [conversationId, setConversationId] = useState<string | null>(null);const [showHistory, setShowHistory] = useState(false);@@ -1039,9 +1050,12 @@ export function GlobalChat() {// Check if we have valid AI setupconst hasPresets = settings.aiPresets && settings.aiPresets.length > 0;- const hasValidModel = activePreset?.model && activePreset.model.trim() !== "";- const needsLogin = activePreset?.provider === "screenpipe-cloud" && !settings.user?.token;- const canChat = hasPresets && hasValidModel && !needsLogin;+ const hasValidModel = activePreset?.provider === "opencode" || (activePreset?.model && activePreset.model.trim() !== "");+ const needsLogin = (activePreset?.provider === "screenpipe-cloud" || activePreset?.provider === "opencode") && !settings.user?.token;+ const isOpencode = activePreset?.provider === "opencode";+ const needsProjectDir = isOpencode && !opencodeProjectDir;+ const opencodeReady = isOpencode ? (opencodeInfo?.running && opencodeClient && opencodeSessionId && !needsProjectDir) : true;+ const canChat = hasPresets && hasValidModel && !needsLogin && opencodeReady;// Debug: log why chat might be disableduseEffect(() => {@@ -1058,16 +1072,111 @@ export function GlobalChat() {}}, [open, activePreset, hasValidModel, needsLogin, canChat]);+ // Load saved project directory on mount+ useEffect(() => {+ const saved = localStorage.getItem("opencode_project_dir");+ if (saved) setOpencodeProjectDir(saved);+ }, []);++ // Save project directory when changed+ useEffect(() => {+ if (opencodeProjectDir) {+ localStorage.setItem("opencode_project_dir", opencodeProjectDir);+ }+ }, [opencodeProjectDir]);++ // Start OpenCode when preset is selected, dialog is open, and project dir is set+ useEffect(() => {+ if (!isOpencode || !open || needsLogin || !opencodeProjectDir || opencodeStarting) return;++ const initOpencode = async () => {+ setOpencodeStarting(true);++ try {+ // Check current status+ const infoResult = await commands.opencodeInfo();+ if (infoResult.status === "ok") {+ setOpencodeInfo(infoResult.data);++ // Check if already running with same project+ if (infoResult.data.running && infoResult.data.baseUrl && infoResult.data.projectDir === opencodeProjectDir) {+ // Already running with correct project, set up client+ const client = createOpencodeClient({ baseUrl: infoResult.data.baseUrl });+ setOpencodeClient(client);++ // Get or create a session+ try {+ const sessions = await client.session.list();+ if (sessions.data && sessions.data.length > 0) {+ setOpencodeSessionId(sessions.data[0].id);+ } else {+ const newSession = await client.session.create({ directory: opencodeProjectDir });+ if (newSession.data) {+ setOpencodeSessionId(newSession.data.id);+ }+ }+ } catch (e) {+ console.error("Failed to get/create opencode session:", e);+ }+ } else {+ // Not running or different project, start with selected directory+ const startResult = await commands.opencodeStart(opencodeProjectDir, settings.user?.token || undefined);+ if (startResult.status === "ok" && startResult.data.running && startResult.data.baseUrl) {+ setOpencodeInfo(startResult.data);+ const client = createOpencodeClient({ baseUrl: startResult.data.baseUrl });+ setOpencodeClient(client);++ // Create initial session+ try {+ const newSession = await client.session.create({ directory: opencodeProjectDir });+ if (newSession.data) {+ setOpencodeSessionId(newSession.data.id);+ }+ } catch (e) {+ console.error("Failed to create opencode session:", e);+ }+ } else if (startResult.status === "error") {+ toast({+ title: "OpenCode failed to start",+ description: startResult.error,+ variant: "destructive",+ });+ }+ }+ }+ } finally {+ setOpencodeStarting(false);+ }+ };++ initOpencode();+ }, [isOpencode, open, needsLogin, opencodeProjectDir, settings.user?.token]);+// Get error message for why chat is disabledconst getDisabledReason = (): string | null => {if (!hasPresets) return "No AI presets configured";if (!activePreset) return "No preset selected";if (!hasValidModel) return `No model selected in "${activePreset.id}" preset - click edit to add one`;- if (needsLogin) return "Login required for Screenpipe Cloud";+ if (needsLogin) return "Login required";+ if (isOpencode && needsProjectDir) return "Select a project folder";+ if (isOpencode && opencodeStarting) return "Starting OpenCode...";+ if (isOpencode && !opencodeReady) return "Connecting to OpenCode...";return null;};const disabledReason = getDisabledReason();+ // Project directory picker for OpenCode+ const selectOpencodeProject = async () => {+ const selected = await openDialog({+ directory: true,+ multiple: false,+ title: "Select Project Folder for OpenCode",+ });+ if (selected) {+ setOpencodeProjectDir(selected as string);+ }+ };+// Listen for Rust-level open-chat event (Cmd+L / Ctrl+L global shortcut)useEffect(() => {const unlisten = listen("open-chat", () => {@@ -1252,10 +1361,137 @@ export function GlobalChat() {});}+ // Send message using OpenCode SDK+ async function sendOpencodeMessage(userMessage: string) {+ if (!opencodeClient || !opencodeSessionId) return;++ const newUserMessage: Message = {+ id: Date.now().toString(),+ role: "user",+ content: userMessage,+ };++ const assistantMessageId = (Date.now() + 1).toString();+ setMessages((prev) => [...prev, newUserMessage]);+ setInput("");+ setIsLoading(true);+ setIsStreaming(true);++ try {+ // Add placeholder for streaming response+ setMessages((prev) => [+ ...prev,+ { id: assistantMessageId, role: "assistant", content: "" },+ ]);++ // Send to OpenCode+ await opencodeClient.session.promptAsync({+ sessionID: opencodeSessionId,+ parts: [{ type: "text", text: userMessage }],+ });++ // Poll for updates with smart completion detection+ let accumulatedText = "";+ let stableCount = 0;+ let lastMessageCount = 0;+ const maxStablePolls = 5; // Stop if no changes for 5 polls+ const maxPolls = 120; // Max 2 minutes at 1s intervals+ let pollCount = 0;++ const poll = async (): Promise<void> => {+ if (!opencodeClient || !opencodeSessionId || pollCount >= maxPolls) {+ setIsLoading(false);+ setIsStreaming(false);+ return;+ }++ pollCount++;++ try {+ const msgs = await opencodeClient.session.messages({ sessionID: opencodeSessionId });+ if (msgs.data && msgs.data.length > 0) {+ const assistantMsgs = msgs.data.filter((m: any) => m.info.role === "assistant");+ const lastAssistantMsg = assistantMsgs[assistantMsgs.length - 1];++ if (lastAssistantMsg) {+ const textParts = lastAssistantMsg.parts+ .filter((p: any) => p.type === "text")+ .map((p: any) => p.text)+ .join("\n");++ // Also show tool usage+ const toolParts = lastAssistantMsg.parts+ .filter((p: any) => p.type === "tool")+ .map((p: any) => `\n\`${p.tool}\``)+ .join("");++ const fullText = textParts + toolParts;++ if (fullText !== accumulatedText) {+ accumulatedText = fullText;+ stableCount = 0;+ setMessages((prev) =>+ prev.map((m) =>+ m.id === assistantMessageId+ ? { ...m, content: accumulatedText }+ : m+ )+ );+ } else {+ stableCount++;+ }++ // Check if we have more messages than before (response complete)+ if (assistantMsgs.length > lastMessageCount && stableCount >= 2) {+ // New message appeared and stabilized - likely complete+ setIsLoading(false);+ setIsStreaming(false);+ return;+ }+ lastMessageCount = assistantMsgs.length;++ // Stop if content hasn't changed for maxStablePolls+ if (stableCount >= maxStablePolls && accumulatedText.length > 0) {+ setIsLoading(false);+ setIsStreaming(false);+ return;+ }+ }+ }+ } catch (e) {+ console.error("Error polling opencode messages:", e);+ }++ // Continue polling+ setTimeout(poll, 1000);+ };++ // Start polling after a brief delay+ setTimeout(poll, 500);++ } catch (error) {+ console.error("OpenCode error:", error);+ setMessages((prev) =>+ prev.map((m) =>+ m.id === assistantMessageId+ ? { ...m, content: `Error: ${error instanceof Error ? error.message : "Unknown error"}` }+ : m+ )+ );+ setIsLoading(false);+ setIsStreaming(false);+ }+ }+// Send message using OpenAI SDK with streamingasync function sendMessage(userMessage: string) {if (!canChat || !activePreset) return;+ // Use OpenCode if that's the active provider+ if (isOpencode) {+ return sendOpencodeMessage(userMessage);+ }+const openai = getOpenAIClient();if (!openai) return;@@ -1880,10 +2116,25 @@ export function GlobalChat() {<div className="relative z-10 p-1.5 rounded-lg bg-foreground/5 border border-border/50"><PipeAIIcon size={18} animated={false} className="text-foreground" /></div>- <div className="flex-1">- <h2 className="font-semibold text-sm tracking-tight">Pipe AI</h2>- <p className="text-[10px] text-muted-foreground font-mono uppercase tracking-wider">Screen Activity Assistant</p>+ <div className="flex-1 min-w-0">+ <h2 className="font-semibold text-sm tracking-tight">+ {isOpencode ? "OpenCode" : "Pipe AI"}+ </h2>+ <p className="text-[10px] text-muted-foreground font-mono uppercase tracking-wider truncate">+ {isOpencode && opencodeProjectDir+ ? opencodeProjectDir.split("/").pop() || opencodeProjectDir+ : "Screen Activity Assistant"}+ </p></div>+ {isOpencode && opencodeProjectDir && (+ <button+ onClick={selectOpencodeProject}+ className="p-1.5 rounded-lg bg-muted/30 hover:bg-muted/50 text-foreground/70 hover:text-foreground transition-colors border border-border/30"+ title="Change project folder"+ >+ <FolderOpen size={16} />+ </button>+ )}<Buttonvariant={showHistory ? "secondary" : "ghost"}size="sm"@@ -2012,7 +2263,7 @@ export function GlobalChat() {<div className="relative flex flex-col items-center justify-center py-12 space-y-4"><div className={cn("relative p-6 rounded-2xl border",- needsLogin+ needsLogin || needsProjectDir? "bg-muted/50 border-border/50": "bg-destructive/5 border-destructive/20")}>@@ -2022,21 +2273,35 @@ export function GlobalChat() {<div className="absolute bottom-0 left-0 w-4 h-4 border-l-2 border-b-2 border-current opacity-20 rounded-bl" /><div className="absolute bottom-0 right-0 w-4 h-4 border-r-2 border-b-2 border-current opacity-20 rounded-br" />- {needsLogin ? (+ {needsProjectDir ? (+ <FolderOpen className="h-12 w-12 text-muted-foreground" />+ ) : needsLogin ? (<PipeAIIconLarge size={48} className="text-muted-foreground" />+ ) : opencodeStarting ? (+ <Loader2 className="h-12 w-12 text-muted-foreground animate-spin" />) : (<Settings className="h-12 w-12 text-destructive/70" />)}</div><div className="text-center space-y-2"><h3 className="font-semibold tracking-tight">- {!hasPresets ? "No AI Presets" : !hasValidModel ? "No Model Selected" : "Login Required"}+ {needsProjectDir ? "Select Project" : !hasPresets ? "No AI Presets" : !hasValidModel ? "No Model Selected" : opencodeStarting ? "Starting OpenCode" : "Login Required"}</h3><p className="text-sm text-muted-foreground max-w-sm">- {disabledReason}+ {needsProjectDir ? "Choose a folder for OpenCode to work with" : disabledReason}</p></div>- {needsLogin && (+ {needsProjectDir && (+ <Button+ variant="default"+ onClick={selectOpencodeProject}+ className="gap-2 font-medium bg-foreground text-background hover:bg-foreground/90"+ >+ <FolderOpen className="h-4 w-4" />+ Select Folder+ </Button>+ )}+ {needsLogin && !needsProjectDir && (<Buttonvariant="default"onClick={() => openUrl("https://screenpi.pe/login")}diff --git a/screenpipe-app-tauri/components/rewind/ai-presets-selector.tsx b/screenpipe-app-tauri/components/rewind/ai-presets-selector.tsxindex 1f9366aac..17f3db980 100644--- a/screenpipe-app-tauri/components/rewind/ai-presets-selector.tsx+++ b/screenpipe-app-tauri/components/rewind/ai-presets-selector.tsx@@ -426,6 +426,7 @@ export function AIProviderConfig({<Icons.settings className="h-8 w-8" /><span>custom</span></Button>+</div>{selectedProvider === "openai" && (diff --git a/screenpipe-app-tauri/components/settings/ai-presets.tsx b/screenpipe-app-tauri/components/settings/ai-presets.tsxindex aceb4566c..7a9f23601 100644--- a/screenpipe-app-tauri/components/settings/ai-presets.tsx+++ b/screenpipe-app-tauri/components/settings/ai-presets.tsx@@ -55,7 +55,8 @@ import {AlertDialogTrigger,} from "@/components/ui/alert-dialog";import { cn } from "@/lib/utils";-import { AIPreset } from "@/lib/utils/tauri";+import { AIPreset, commands } from "@/lib/utils/tauri";+import { listen } from "@tauri-apps/api/event";import {validatePresetName,validateUrl,@@ -76,7 +77,7 @@ const formatPresetName = (name: string): string => {};export interface AIProviderCardProps {- type: "screenpipe-cloud" | "openai" | "native-ollama" | "custom" | "embedded";+ type: "screenpipe-cloud" | "openai" | "native-ollama" | "custom" | "embedded" | "opencode";title: string;description: string;imageSrc: string;@@ -147,10 +148,12 @@ const AISection = ({preset,setDialog,isDuplicating,+ opencodeAvailable,}: {preset?: AIPreset;setDialog: (value: boolean) => void;isDuplicating?: boolean;+ opencodeAvailable?: boolean;}) => {const { settings, updateSettings } = useSettings();const [settingsPreset, setSettingsPreset] = useState<@@ -368,6 +371,10 @@ const AISection = ({case "custom":newUrl = settingsPreset?.url || "";break;+ case "opencode":+ newUrl = "opencode://local";+ newModel = "claude-sonnet-4";+ break;}updateSettingsPreset({@@ -568,6 +575,20 @@ const AISection = ({selected={settingsPreset?.provider === "custom"}onClick={() => handleAiProviderChange("custom")}/>++ {opencodeAvailable && (+ <AIProviderCard+ type="opencode"+ title="OpenCode"+ description="High-intelligence AI agent powered by Claude. Requires login."+ imageSrc="/images/screenpipe.png"+ selected={settingsPreset?.provider === "opencode"}+ onClick={() => handleAiProviderChange("opencode")}+ disabled={!settings.user?.token}+ warningText={!settings.user?.token ? "Login required" : undefined}+ />+ )}+</div></div>@@ -803,6 +824,7 @@ const providerImageSrc: Record<AIPreset["provider"], string> = {"screenpipe-cloud": "/images/screenpipe.png","native-ollama": "/images/ollama.png",custom: "/images/custom.png",+ opencode: "/images/screenpipe.png",};export const AIPresets = () => {@@ -815,6 +837,36 @@ export const AIPresets = () => {null);const [isDuplicating, setIsDuplicating] = useState(false);+ const [opencodeAvailable, setOpencodeAvailable] = useState(false);+ const [opencodeInstalling, setOpencodeInstalling] = useState(false);++ // Check OpenCode availability and install if needed (background)+ useEffect(() => {+ const checkAndInstallOpencode = async () => {+ const result = await commands.opencodeCheck();+ if (result.status === "ok" && result.data.available) {+ setOpencodeAvailable(true);+ } else {+ // Try to install in background+ setOpencodeInstalling(true);+ await commands.opencodeInstall();+ }+ };++ checkAndInstallOpencode();++ // Listen for install completion+ const unlisten = listen<boolean>("opencode_installed", (event) => {+ setOpencodeInstalling(false);+ if (event.payload) {+ setOpencodeAvailable(true);+ }+ });++ return () => {+ unlisten.then((fn) => fn());+ };+ }, []);useEffect(() => {if (!createPresetsDialog) {@@ -829,6 +881,7 @@ export const AIPresets = () => {setDialog={setCreatePresentDialog}preset={selectedPreset}isDuplicating={isDuplicating}+ opencodeAvailable={opencodeAvailable}/>);diff --git a/screenpipe-app-tauri/lib/hooks/use-opencode.tsx b/screenpipe-app-tauri/lib/hooks/use-opencode.tsxnew file mode 100644index 000000000..f5a815c92--- /dev/null+++ b/screenpipe-app-tauri/lib/hooks/use-opencode.tsx@@ -0,0 +1,142 @@+import { useState, useEffect, useCallback } from "react";+import { commands, OpencodeInfo, OpencodeCheckResult } from "@/lib/utils/tauri";+import { listen } from "@tauri-apps/api/event";++export interface UseOpencodeResult {+ info: OpencodeInfo | null;+ checkResult: OpencodeCheckResult | null;+ isLoading: boolean;+ error: string | null;+ logs: string[];+ start: (projectDir: string) => Promise<OpencodeInfo | null>;+ stop: () => Promise<void>;+ refresh: () => Promise<void>;+ check: () => Promise<void>;+ clearError: () => void;+}++export function useOpencode(): UseOpencodeResult {+ const [info, setInfo] = useState<OpencodeInfo | null>(null);+ const [checkResult, setCheckResult] = useState<OpencodeCheckResult | null>(null);+ const [isLoading, setIsLoading] = useState(false);+ const [error, setError] = useState<string | null>(null);+ const [logs, setLogs] = useState<string[]>([]);++ const refresh = useCallback(async () => {+ try {+ const result = await commands.opencodeInfo();+ if (result.status === "ok") {+ setInfo(result.data);+ } else {+ setError(result.error);+ }+ } catch (e) {+ setError(e instanceof Error ? e.message : String(e));+ }+ }, []);++ const check = useCallback(async () => {+ try {+ const result = await commands.opencodeCheck();+ if (result.status === "ok") {+ setCheckResult(result.data);+ } else {+ setError(result.error);+ }+ } catch (e) {+ setError(e instanceof Error ? e.message : String(e));+ }+ }, []);++ const start = useCallback(async (projectDir: string): Promise<OpencodeInfo | null> => {+ setIsLoading(true);+ setError(null);+ setLogs([]);+ try {+ const result = await commands.opencodeStart(projectDir);+ if (result.status === "ok") {+ setInfo(result.data);+ return result.data;+ } else {+ setError(result.error);+ return null;+ }+ } catch (e) {+ const msg = e instanceof Error ? e.message : String(e);+ setError(msg);+ return null;+ } finally {+ setIsLoading(false);+ }+ }, []);++ const stop = useCallback(async () => {+ setIsLoading(true);+ setError(null);+ try {+ const result = await commands.opencodeStop();+ if (result.status === "ok") {+ setInfo(result.data);+ } else {+ setError(result.error);+ }+ } catch (e) {+ setError(e instanceof Error ? e.message : String(e));+ } finally {+ setIsLoading(false);+ }+ }, []);++ const clearError = useCallback(() => {+ setError(null);+ }, []);++ // Initial check on mount+ useEffect(() => {+ check();+ refresh();+ }, [check, refresh]);++ // Listen for OpenCode events+ useEffect(() => {+ const unlistenLog = listen<string>("opencode_log", (event) => {+ setLogs((prev) => [...prev.slice(-99), event.payload]);+ });++ const unlistenTerminated = listen<number | null>("opencode_terminated", () => {+ refresh();+ });++ const unlistenError = listen<string>("opencode_error", (event) => {+ setError(event.payload);+ refresh();+ });++ return () => {+ unlistenLog.then((fn) => fn());+ unlistenTerminated.then((fn) => fn());+ unlistenError.then((fn) => fn());+ };+ }, [refresh]);++ // Poll for status while running+ useEffect(() => {+ if (info?.running) {+ const interval = setInterval(refresh, 10000);+ return () => clearInterval(interval);+ }+ }, [info?.running, refresh]);++ return {+ info,+ checkResult,+ isLoading,+ error,+ logs,+ start,+ stop,+ refresh,+ check,+ clearError,+ };+}diff --git a/screenpipe-app-tauri/lib/utils/tauri.ts b/screenpipe-app-tauri/lib/utils/tauri.tsindex d92b9d2fa..8d11848d7 100644--- a/screenpipe-app-tauri/lib/utils/tauri.ts+++ b/screenpipe-app-tauri/lib/utils/tauri.ts@@ -273,6 +273,47 @@ async resumeGlobalShortcuts() : Promise<Result<null, string>> {if(e instanceof Error) throw e;else return { status: "error", error: e as any };}+},+// OpenCode commands+async opencodeInfo() : Promise<Result<OpencodeInfo, string>> {+ try {+ return { status: "ok", data: await TAURI_INVOKE("opencode_info") };+} catch (e) {+ if(e instanceof Error) throw e;+ else return { status: "error", error: e as any };+}+},+async opencodeStart(projectDir: string, userToken?: string) : Promise<Result<OpencodeInfo, string>> {+ try {+ return { status: "ok", data: await TAURI_INVOKE("opencode_start", { projectDir, userToken }) };+} catch (e) {+ if(e instanceof Error) throw e;+ else return { status: "error", error: e as any };+}+},+async opencodeStop() : Promise<Result<OpencodeInfo, string>> {+ try {+ return { status: "ok", data: await TAURI_INVOKE("opencode_stop") };+} catch (e) {+ if(e instanceof Error) throw e;+ else return { status: "error", error: e as any };+}+},+async opencodeCheck() : Promise<Result<OpencodeCheckResult, string>> {+ try {+ return { status: "ok", data: await TAURI_INVOKE("opencode_check") };+} catch (e) {+ if(e instanceof Error) throw e;+ else return { status: "error", error: e as any };+}+},+async opencodeInstall() : Promise<Result<null, string>> {+ try {+ return { status: "ok", data: await TAURI_INVOKE("opencode_install") };+} catch (e) {+ if(e instanceof Error) throw e;+ else return { status: "error", error: e as any };+}}}@@ -287,7 +328,7 @@ async resumeGlobalShortcuts() : Promise<Result<null, string>> {/** user-defined types **/export type AIPreset = { id: string; prompt: string; provider: AIProviderType; url?: string; model?: string; defaultPreset: boolean; apiKey: string | null; maxContextChars: number }-export type AIProviderType = "openai" | "native-ollama" | "custom" | "screenpipe-cloud"+export type AIProviderType = "openai" | "native-ollama" | "custom" | "screenpipe-cloud" | "opencode"export type Credits = { amount: number }export type EmbeddedLLM = { enabled: boolean; model: string; port: number }export type JsonValue = null | boolean | number | string | JsonValue[] | { [key in string]: JsonValue }@@ -313,6 +354,10 @@ deviceId?: string }export type ShowRewindWindow = "Main" | { Settings: { page: string | null } } | { Search: { query: string | null } } | "Onboarding" | "Chat" | "PermissionRecovery"export type User = { id: string | null; name: string | null; email: string | null; image: string | null; token: string | null; clerk_id: string | null; api_key: string | null; credits: Credits | null; stripe_connected: boolean | null; stripe_account_status: string | null; github_username: string | null; bio: string | null; website: string | null; contact: string | null; cloud_subscribed: boolean | null }+// OpenCode types+export type OpencodeInfo = { running: boolean; baseUrl: string | null; port: number | null; projectDir: string | null; pid: number | null }+export type OpencodeCheckResult = { available: boolean; sidecarAvailable: boolean; pathAvailable: boolean }+/** tauri-specta globals **/import {diff --git a/screenpipe-app-tauri/package.json b/screenpipe-app-tauri/package.jsonindex a9a252834..187b64f84 100644--- a/screenpipe-app-tauri/package.json+++ b/screenpipe-app-tauri/package.json@@ -14,6 +14,7 @@"clean": "rm -rf out && cargo clean && rm -rf src-tauri/{screenpipe-*,tesseract-*,ffmpeg*,bun*,ollama*,ui_monitor*} node_modules"},"dependencies": {+ "@opencode-ai/sdk": "^1.1.44","@patternfly/react-core": "^6.1.0","@patternfly/react-log-viewer": "^6.1.0","@radix-ui/react-accordion": "^1.2.0",diff --git a/screenpipe-app-tauri/public/images/opencode.png b/screenpipe-app-tauri/public/images/opencode.pngnew file mode 100644index 000000000..7151485d0Binary files /dev/null and b/screenpipe-app-tauri/public/images/opencode.png differdiff --git a/screenpipe-app-tauri/src-tauri/src/main.rs b/screenpipe-app-tauri/src-tauri/src/main.rsindex eb295e3d0..9df0fae36 100755--- a/screenpipe-app-tauri/src-tauri/src/main.rs+++ b/screenpipe-app-tauri/src-tauri/src/main.rs@@ -39,6 +39,7 @@ use crate::store::SettingsStore;mod commands;mod disk_usage;+mod opencode;mod permissions;mod server;mod sidecar;@@ -790,6 +791,12 @@ async fn main() {// Commands from tray.rsset_tray_unhealth_icon,set_tray_health_icon,+ // OpenCode commands+ opencode::opencode_info,+ opencode::opencode_start,+ opencode::opencode_stop,+ opencode::opencode_check,+ opencode::opencode_install,]).typ::<SettingsStore>().typ::<OnboardingStore>();@@ -804,6 +811,7 @@ async fn main() {let sidecar_state = SidecarState(Arc::new(tokio::sync::Mutex::new(None)));let sidecar_state_for_init = sidecar_state.0.clone(); // Clone for initial spawn+ let opencode_state = opencode::OpencodeState(Arc::new(tokio::sync::Mutex::new(None)));#[allow(clippy::single_match)]let app = tauri::Builder::default().plugin(tauri_plugin_opener::init())@@ -855,6 +863,7 @@ async fn main() {let app = app.plugin(tauri_nspanel::init());let app = app.manage(sidecar_state)+ .manage(opencode_state).invoke_handler(tauri::generate_handler![spawn_screenpipe,stop_screenpipe,@@ -898,7 +907,13 @@ async fn main() {update_global_shortcuts,suspend_global_shortcuts,resume_global_shortcuts,- get_env+ get_env,+ // OpenCode commands+ opencode::opencode_info,+ opencode::opencode_start,+ opencode::opencode_stop,+ opencode::opencode_check,+ opencode::opencode_install]).setup(move |app| {//deep link register_all@@ -1230,6 +1245,14 @@ async fn main() {if let Some(server_shutdown_tx) = app_handle.try_state::<mpsc::Sender<()>>() {drop(server_shutdown_tx.send(()));}++ // Cleanup OpenCode sidecar+ let app_handle_opencode = app_handle.app_handle().clone();+ tauri::async_runtime::spawn(async move {+ if let Some(opencode_state) = app_handle_opencode.try_state::<opencode::OpencodeState>() {+ opencode::cleanup_opencode(&opencode_state).await;+ }+ });}tauri::RunEvent::WindowEvent {diff --git a/screenpipe-app-tauri/src-tauri/src/opencode.rs b/screenpipe-app-tauri/src-tauri/src/opencode.rsnew file mode 100644index 000000000..3b3bc12be--- /dev/null+++ b/screenpipe-app-tauri/src-tauri/src/opencode.rs@@ -0,0 +1,529 @@+use serde::{Deserialize, Serialize};+use serde_json::json;+use specta::Type;+use std::path::PathBuf;+use std::sync::Arc;+use tauri::Emitter;+use tauri::{Manager, State};+use tauri_plugin_shell::process::{CommandChild, CommandEvent};+use tauri_plugin_shell::ShellExt;+use tokio::sync::Mutex;+use tracing::{debug, error, info, warn};++/// State for managing the OpenCode sidecar process+pub struct OpencodeState(pub Arc<Mutex<Option<OpencodeManager>>>);++#[derive(Debug, Clone, Serialize, Deserialize, Type)]+#[serde(rename_all = "camelCase")]+pub struct OpencodeInfo {+ pub running: bool,+ pub base_url: Option<String>,+ pub port: Option<u16>,+ pub project_dir: Option<String>,+ pub pid: Option<u32>,+}++impl Default for OpencodeInfo {+ fn default() -> Self {+ Self {+ running: false,+ base_url: None,+ port: None,+ project_dir: None,+ pid: None,+ }+ }+}++#[derive(Debug, Clone, Serialize, Deserialize, Type)]+#[serde(rename_all = "camelCase")]+pub struct OpencodeCheckResult {+ pub available: bool,+ pub sidecar_available: bool,+ pub path_available: bool,+}++pub struct OpencodeManager {+ child: Option<CommandChild>,+ port: Option<u16>,+ project_dir: Option<String>,+ child_exited: bool,+}++impl OpencodeManager {+ pub fn new() -> Self {+ Self {+ child: None,+ port: None,+ project_dir: None,+ child_exited: false,+ }+ }++ pub fn snapshot(&self) -> OpencodeInfo {+ let (running, pid) = match &self.child {+ None => (false, None),+ Some(_) if self.child_exited => (false, None),+ Some(child) => (true, Some(child.pid())),+ };++ OpencodeInfo {+ running,+ base_url: self.port.map(|p| format!("http://127.0.0.1:{}", p)),+ port: self.port,+ project_dir: self.project_dir.clone(),+ pid,+ }+ }++ pub fn stop(&mut self) {+ if let Some(child) = self.child.take() {+ if let Err(e) = child.kill() {+ error!("Failed to kill opencode child process: {}", e);+ }+ }+ self.child_exited = true;+ self.port = None;+ self.project_dir = None;+ }++ pub fn is_running(&self) -> bool {+ self.child.is_some() && !self.child_exited+ }+}++/// Find a free port for the OpenCode server+fn find_free_port() -> Result<u16, String> {+ let listener = std::net::TcpListener::bind(("127.0.0.1", 0)).map_err(|e| e.to_string())?;+ let port = listener.local_addr().map_err(|e| e.to_string())?.port();+ Ok(port)+}++/// Get the OpenCode config directory+fn get_opencode_config_dir() -> Result<PathBuf, String> {+ let config_dir = dirs::config_dir()+ .ok_or_else(|| "Could not find config directory".to_string())?+ .join("opencode");+ Ok(config_dir)+}++/// Ensure OpenCode is configured to use screenpipe-cloud as the AI provider+/// This creates/updates the opencode.json config file+fn ensure_opencode_config(user_token: Option<&str>) -> Result<(), String> {+ let config_dir = get_opencode_config_dir()?;+ std::fs::create_dir_all(&config_dir)+ .map_err(|e| format!("Failed to create opencode config dir: {}", e))?;++ let config_path = config_dir.join("opencode.json");++ // Create config that uses screenpipe-cloud as the provider+ // This leverages the $200k Vertex AI credits through screenpipe's proxy+ // Available models: claude-haiku-4-5 (fast), claude-opus-4-5 (powerful)+ let config = json!({+ "$schema": "https://opencode.ai/config.json",+ "provider": {+ "screenpipe": {+ "api": "anthropic",+ "baseURL": "https://api.screenpi.pe/anthropic",+ "models": {+ "claude-haiku-4-5@20251001": {+ "name": "Claude Haiku 4.5",+ "attachment": true,+ "reasoning": false+ },+ "claude-opus-4-5@20251101": {+ "name": "Claude Opus 4.5",+ "attachment": true,+ "reasoning": true+ }+ }+ }+ },+ "model": {+ "default": "screenpipe/claude-haiku-4-5@20251001",+ "reasoning": "screenpipe/claude-opus-4-5@20251101"+ }+ });++ // Write the config+ let config_str = serde_json::to_string_pretty(&config)+ .map_err(|e| format!("Failed to serialize config: {}", e))?;++ std::fs::write(&config_path, config_str)+ .map_err(|e| format!("Failed to write opencode config: {}", e))?;++ // If we have a user token, also set up auth+ if let Some(token) = user_token {+ let auth_path = config_dir.join("auth.json");+ let auth = json!({+ "screenpipe": {+ "type": "api_key",+ "key": token+ }+ });+ let auth_str = serde_json::to_string_pretty(&auth)+ .map_err(|e| format!("Failed to serialize auth: {}", e))?;+ std::fs::write(&auth_path, auth_str)+ .map_err(|e| format!("Failed to write opencode auth: {}", e))?;+ }++ info!("OpenCode configured to use screenpipe-cloud at {:?}", config_path);+ Ok(())+}++/// Kill orphaned opencode processes+pub async fn kill_orphaned_opencode_processes() {+ #[cfg(target_os = "macos")]+ {+ let _ = tokio::process::Command::new("sh")+ .arg("-c")+ .arg("pgrep -x opencode | xargs kill -9 2>/dev/null || true")+ .output()+ .await;+ }++ #[cfg(target_os = "linux")]+ {+ let _ = tokio::process::Command::new("sh")+ .arg("-c")+ .arg("pgrep -x opencode | xargs -I {} kill -15 {} 2>/dev/null || true")+ .output()+ .await;+ }++ #[cfg(target_os = "windows")]+ {+ use std::os::windows::process::CommandExt;+ const CREATE_NO_WINDOW: u32 = 0x08000000;++ let _ = tokio::process::Command::new("taskkill")+ .args(["/F", "/IM", "opencode.exe"])+ .creation_flags(CREATE_NO_WINDOW)+ .output()+ .await;+ }+}++/// Get OpenCode info+#[tauri::command]+#[specta::specta]+pub async fn opencode_info(state: State<'_, OpencodeState>) -> Result<OpencodeInfo, String> {+ let manager = state.0.lock().await;+ match manager.as_ref() {+ Some(m) => Ok(m.snapshot()),+ None => Ok(OpencodeInfo::default()),+ }+}++/// Stop the OpenCode sidecar+#[tauri::command]+#[specta::specta]+pub async fn opencode_stop(state: State<'_, OpencodeState>) -> Result<OpencodeInfo, String> {+ info!("Stopping opencode sidecar");++ let mut manager = state.0.lock().await;+ if let Some(m) = manager.as_mut() {+ m.stop();+ }++ // Also kill any orphaned opencode processes+ kill_orphaned_opencode_processes().await;++ match manager.as_ref() {+ Some(m) => Ok(m.snapshot()),+ None => Ok(OpencodeInfo::default()),+ }+}++/// Start the OpenCode sidecar+/// user_token: The user's screenpipe auth token for API access+#[tauri::command]+#[specta::specta]+pub async fn opencode_start(+ app: tauri::AppHandle,+ state: State<'_, OpencodeState>,+ project_dir: String,+ user_token: Option<String>,+) -> Result<OpencodeInfo, String> {+ let project_dir = project_dir.trim().to_string();+ if project_dir.is_empty() {+ return Err("Project directory is required".to_string());+ }++ // Create project directory if it doesn't exist+ std::fs::create_dir_all(&project_dir)+ .map_err(|e| format!("Failed to create project directory: {}", e))?;++ // Ensure OpenCode is configured to use screenpipe-cloud+ ensure_opencode_config(user_token.as_deref())?;++ let port = find_free_port()?;++ let mut manager_guard = state.0.lock().await;++ // Initialize manager if needed+ if manager_guard.is_none() {+ *manager_guard = Some(OpencodeManager::new());+ }++ // Stop any existing instance+ if let Some(m) = manager_guard.as_mut() {+ if m.is_running() {+ info!("Stopping existing opencode instance");+ m.stop();+ }+ }++ // Build opencode serve command+ let args = vec![+ "serve".to_string(),+ "--hostname".to_string(),+ "127.0.0.1".to_string(),+ "--port".to_string(),+ port.to_string(),+ "--cors".to_string(),+ "*".to_string(),+ ];++ info!("Starting opencode with args: {:?} in dir: {}", args, project_dir);++ // Try to spawn opencode - first try sidecar, then PATH+ let spawn_result = {+ let sidecar_result = app.shell().sidecar("opencode");++ match sidecar_result {+ Ok(cmd) => {+ info!("Using bundled opencode sidecar");+ let mut command = cmd.args(&args).current_dir(&project_dir);++ // Pass the API key via environment variable for the provider+ if let Some(ref token) = user_token {+ command = command.env("ANTHROPIC_API_KEY", token);+ }++ command.spawn()+ }+ Err(_) => {+ // Fallback to PATH+ info!("Sidecar not found, trying opencode from PATH");+ let mut command = app.shell()+ .command("opencode")+ .args(&args)+ .current_dir(&project_dir);++ if let Some(ref token) = user_token {+ command = command.env("ANTHROPIC_API_KEY", token);+ }++ command.spawn()+ }+ }+ };++ let (mut rx, child) = spawn_result.map_err(|e| {+ format!("Failed to start OpenCode: {}", e)+ })?;++ let pid = child.pid();+ info!("Spawned opencode with PID {} on port {}", pid, port);++ // Update manager state+ if let Some(m) = manager_guard.as_mut() {+ m.child = Some(child);+ m.port = Some(port);+ m.project_dir = Some(project_dir.clone());+ m.child_exited = false;+ }++ // Clone state for async task+ let state_arc = state.0.clone();+ let app_handle = app.app_handle().clone();++ // Spawn task to handle stdout/stderr+ tauri::async_runtime::spawn(async move {+ while let Some(event) = rx.recv().await {+ match event {+ CommandEvent::Stdout(line_bytes) => {+ let line = String::from_utf8_lossy(&line_bytes).to_string();+ debug!("opencode stdout: {}", line);+ let _ = app_handle.emit("opencode_log", &line);+ }+ CommandEvent::Stderr(line_bytes) => {+ let line = String::from_utf8_lossy(&line_bytes).to_string();+ if line.to_lowercase().contains("error") || line.to_lowercase().contains("failed") {+ error!("opencode stderr: {}", line);+ } else {+ debug!("opencode stderr: {}", line);+ }+ let _ = app_handle.emit("opencode_log", &line);+ }+ CommandEvent::Terminated(payload) => {+ warn!("opencode terminated with status: {:?}", payload.code);+ if let Ok(mut manager) = state_arc.try_lock() {+ if let Some(m) = manager.as_mut() {+ m.child_exited = true;+ }+ }+ let _ = app_handle.emit("opencode_terminated", payload.code);+ }+ CommandEvent::Error(message) => {+ error!("opencode error: {}", message);+ if let Ok(mut manager) = state_arc.try_lock() {+ if let Some(m) = manager.as_mut() {+ m.child_exited = true;+ }+ }+ let _ = app_handle.emit("opencode_error", &message);+ }+ _ => {}+ }+ }+ });++ // Wait for server to be ready (poll health endpoint)+ let base_url = format!("http://127.0.0.1:{}", port);+ let health_url = format!("{}/health", base_url);+ let client = reqwest::Client::new();++ let start = std::time::Instant::now();+ let timeout = std::time::Duration::from_secs(15);++ loop {+ // Check if process exited+ if let Some(m) = manager_guard.as_ref() {+ if m.child_exited {+ return Err("OpenCode exited unexpectedly. Check logs for details.".to_string());+ }+ }++ // Try health check+ match client.get(&health_url).send().await {+ Ok(resp) if resp.status().is_success() => {+ info!("OpenCode server is ready at {}", base_url);+ break;+ }+ _ => {}+ }++ if start.elapsed() > timeout {+ if let Some(m) = manager_guard.as_mut() {+ m.stop();+ }+ return Err("OpenCode server failed to start within 15 seconds.".to_string());+ }++ drop(manager_guard);+ tokio::time::sleep(tokio::time::Duration::from_millis(200)).await;+ manager_guard = state.0.lock().await;+ }++ match manager_guard.as_ref() {+ Some(m) => Ok(m.snapshot()),+ None => Ok(OpencodeInfo::default()),+ }+}++/// Check if opencode is available (either as sidecar or in PATH)+#[tauri::command]+#[specta::specta]+pub async fn opencode_check(app: tauri::AppHandle) -> Result<OpencodeCheckResult, String> {+ let sidecar_available = app.shell().sidecar("opencode").is_ok();++ let path_available = {+ #[cfg(target_os = "windows")]+ {+ std::process::Command::new("where")+ .arg("opencode")+ .output()+ .map(|o| o.status.success())+ .unwrap_or(false)+ }++ #[cfg(not(target_os = "windows"))]+ {+ std::process::Command::new("which")+ .arg("opencode")+ .output()+ .map(|o| o.status.success())+ .unwrap_or(false)+ }+ };++ Ok(OpencodeCheckResult {+ available: sidecar_available || path_available,+ sidecar_available,+ path_available,+ })+}++/// Install opencode via bun (runs in background)+/// Returns immediately, installation happens async+#[tauri::command]+#[specta::specta]+pub async fn opencode_install(app: tauri::AppHandle) -> Result<(), String> {+ info!("Installing opencode via bun...");++ // Use bundled bun sidecar to install opencode globally+ let bun_result = app.shell().sidecar("bun");++ match bun_result {+ Ok(cmd) => {+ let args = vec!["add", "-g", "opencode-ai"];+ info!("Running: bun {:?}", args);++ match cmd.args(&args).spawn() {+ Ok((mut rx, _child)) => {+ // Spawn a task to log output but don't block+ let app_handle = app.app_handle().clone();+ tauri::async_runtime::spawn(async move {+ while let Some(event) = rx.recv().await {+ match event {+ CommandEvent::Stdout(line) => {+ let text = String::from_utf8_lossy(&line);+ debug!("opencode install stdout: {}", text);+ }+ CommandEvent::Stderr(line) => {+ let text = String::from_utf8_lossy(&line);+ debug!("opencode install stderr: {}", text);+ }+ CommandEvent::Terminated(payload) => {+ if payload.code == Some(0) {+ info!("OpenCode installed successfully");+ let _ = app_handle.emit("opencode_installed", true);+ } else {+ error!("OpenCode installation failed with code: {:?}", payload.code);+ let _ = app_handle.emit("opencode_installed", false);+ }+ }+ CommandEvent::Error(e) => {+ error!("OpenCode install error: {}", e);+ let _ = app_handle.emit("opencode_installed", false);+ }+ _ => {}+ }+ }+ });+ Ok(())+ }+ Err(e) => {+ error!("Failed to spawn bun install: {}", e);+ Err(format!("Failed to start installation: {}", e))+ }+ }+ }+ Err(e) => {+ error!("Bun sidecar not available: {}", e);+ Err("Bun not available for installation".to_string())+ }+ }+}++/// Cleanup function to be called on app exit+pub async fn cleanup_opencode(state: &OpencodeState) {+ info!("Cleaning up opencode on app exit");+ let mut manager = state.0.lock().await;+ if let Some(m) = manager.as_mut() {+ m.stop();+ }+ kill_orphaned_opencode_processes().await;+}diff --git a/screenpipe-app-tauri/src-tauri/src/store.rs b/screenpipe-app-tauri/src-tauri/src/store.rsindex 2dba740fb..66f443249 100644--- a/screenpipe-app-tauri/src-tauri/src/store.rs+++ b/screenpipe-app-tauri/src-tauri/src/store.rs@@ -218,6 +218,8 @@ pub enum AIProviderType {Custom,#[serde(rename = "screenpipe-cloud")]ScreenpipeCloud,+ #[serde(rename = "opencode")]+ OpenCode,}#[derive(Serialize, Deserialize,Type,Clone)]