diff --git a/extensions/cli/CHAT_HISTORY_SERVICE_MIGRATION_PLAN.md b/extensions/cli/CHAT_HISTORY_SERVICE_MIGRATION_PLAN.md deleted file mode 100644 index 566ebe5aa..000000000 --- a/extensions/cli/CHAT_HISTORY_SERVICE_MIGRATION_PLAN.md +++ /dev/null @@ -1,434 +0,0 @@ -# ChatHistoryService Migration Plan - -## Overview - -This document outlines a gradual migration plan to move from the current mixed state management approach (React state + direct mutations) to a centralized `ChatHistoryService` that acts as the single source of truth for chat history. - -## Current State Analysis - -### Problems - -- **Duplicate state**: Chat history exists in both React state (`useState`) and is directly mutated in arrays -- **Direct mutations**: `handleToolCalls.ts` uses `chatHistory.push()` bypassing React -- **Inconsistent updates**: Mix of `setChatHistory` callbacks and direct array modifications -- **Testing difficulties**: Hard to test and mock due to mixed patterns -- **Race conditions**: Potential for state inconsistencies - -### Affected Files - -- `src/ui/hooks/useChat.ts` - Main hook with React state -- `src/stream/handleToolCalls.ts` - Direct array mutations -- `src/stream/streamChatResponse.ts` - Mixed patterns -- `src/commands/serve.ts` - Direct mutations in remote mode -- `src/session.ts` - Session management - -## Migration Strategy - -### Phase 1: Create ChatHistoryService (Day 1) - -**Goal**: Establish the service foundation without breaking existing code - -#### 1.1 Create Service Implementation - -```typescript -// src/services/ChatHistoryService.ts -export interface ChatHistoryState { - history: ChatHistoryItem[]; - compactionIndex: number | null; - sessionId: string; - isRemoteMode: boolean; -} - -export class ChatHistoryService extends BaseService { - // Implementation details below -} -``` - -#### 1.2 Service Methods to Implement - -- `addUserMessage(content, contextItems)` -- `addAssistantMessage(content, toolCalls?)` -- `addSystemMessage(content)` -- `updateToolCallState(messageIndex, toolCallId, updates)` -- `addToolResult(toolCallId, result, status)` -- `compact(newHistory, compactionIndex)` -- `clear()` -- `loadSession(sessionId)` -- `getHistory()` - Returns immutable copy -- `getHistoryForLLM(compactionIndex?)` - For streaming - -#### 1.3 Register Service - -- Add to `src/services/index.ts` -- Add to ServiceContainer initialization -- Ensure proper initialization order - -#### 1.4 Write Unit Tests - -- Test all service methods -- Test event emissions -- Test immutability guarantees -- Test session integration - -**Deliverable**: Working service with tests, no integration yet - -### Phase 2: Wrapper Integration (Day 1-2) - -**Goal**: Wrap existing code to use service without changing behavior - -#### 2.1 Create Compatibility Layer - -```typescript -// src/services/ChatHistoryCompatibility.ts -export function createChatHistoryProxy(service: ChatHistoryService) { - return new Proxy([], { - get(target, prop) { - if (prop === "push") { - return (item) => service.addHistoryItem(item); - } - // Delegate reads to service.getHistory() - const history = service.getHistory(); - return history[prop]; - }, - }); -} -``` - -#### 2.2 Update useChat Hook - -- Initialize ChatHistoryService in useChat -- Keep existing `setChatHistory` for now -- Sync service changes to React state: - -```typescript -// In useChat.ts -const chatHistoryService = useService("chatHistory"); - -useEffect(() => { - if (chatHistoryService.state === "ready") { - setChatHistory(chatHistoryService.value.history); - } -}, [chatHistoryService]); -``` - -#### 2.3 Add Service Methods to Mirror State Updates - -- Wherever `setChatHistory` is called, also update service -- This creates temporary duplication but maintains compatibility - -**Deliverable**: Service running in parallel with existing state - -### Phase 3: Migrate Stream Processing (Day 2) - -**Goal**: Update streaming functions to use service - -#### 3.1 Update handleToolCalls.ts - -- Replace `chatHistory.push()` with service methods: - -```typescript -// Before: -chatHistory.push(createHistoryItem(...)); - -// After: -await chatHistoryService.addHistoryItem(createHistoryItem(...)); -``` - -#### 3.2 Update streamChatResponse.ts - -- Pass service instance instead of arrays -- Use service methods for all updates -- Remove direct array access - -#### 3.3 Update Stream Callbacks - -- Modify `createStreamCallbacks` in `useChat.stream.helpers.ts` -- Use service methods instead of `setChatHistory` -- Ensure proper event handling - -#### 3.4 Test Streaming - -- Test tool execution flow -- Test interruption handling -- Test auto-compaction -- Verify no direct mutations remain - -**Deliverable**: All streaming using service, no direct mutations - -### Phase 4: Remove React State Duplication (Day 2-3) - -**Goal**: Remove `useState` and rely solely on service - -#### 4.1 Update useChat to Use Service Directly - -```typescript -// Remove: -const [chatHistory, setChatHistory] = useState(...); - -// Replace with: -const { value: chatHistoryState, state } = useService('chatHistory'); -const chatHistory = chatHistoryState?.history || []; -``` - -#### 4.2 Update All Components - -- Update components that receive `chatHistory` prop -- Ensure they handle potential undefined/loading states -- Update any direct `setChatHistory` calls - -#### 4.3 Remove Compatibility Layer - -- Remove the proxy wrapper -- Remove temporary sync code -- Clean up unused imports - -**Deliverable**: Single source of truth established - -### Phase 5: Optimize and Enhance (Day 3) - -**Goal**: Add optimizations and missing features - -#### 5.1 Performance Optimizations - -- Implement efficient diffing for large histories -- Add memoization where needed -- Optimize re-render triggers - -#### 5.2 Add Advanced Features - -- Implement undo/redo capability -- Add history branching for explorations -- Improve session management integration -- Add persistence strategies - -#### 5.3 Remote Mode Integration - -- Update `serve.ts` to use service -- Ensure remote sync works with service -- Test remote mode thoroughly - -#### 5.4 Update Documentation - -- Update code comments -- Update AGENTS.md with new patterns -- Create service usage examples - -**Deliverable**: Optimized service with full feature set - -Status: Completed - -- Remote mode now reads/writes chat history via ChatHistoryService; `/state` reflects the service’s history. -- Stream callbacks avoid duplicating tool entries; service is single source of truth. -- Added undo/redo to ChatHistoryService with tests (`canUndo/canRedo/undo/redo`). - -Notes: Further optimizations (batching/memoization) can be added if performance profiling indicates need with very large histories. - -### Phase 6: Validation and Cleanup (Day 3-4) - -**Goal**: Ensure migration is complete and stable - -#### 6.1 Comprehensive Testing - -- Run all existing tests -- Add integration tests for service -- Test all user flows (TUI, headless, remote) -- Performance testing with large histories - -#### 6.2 Code Cleanup - -- Removed direct history mutations in serve/stream paths where service is present; retained minimal fallbacks. -- Updated imports/types; removed unused `updateSessionHistory` in serve mode and pruned unused types. -- Verified service methods own persistence; remote mode disables persistence by design. - -#### 6.3 Migration Verification Checklist - -- [x] No direct array mutations remain where service is available (fallbacks kept for resilience) -- [x] All tests passing -- [x] Service handles all chat operations (user, assistant, tools, system, compaction) -- [x] React components update via service events -- [x] Session management integrated with service persistence -- [x] Remote mode reading/writing via service -- [x] Performance acceptable in tests; no regressions -- [x] No new console errors/warnings introduced - -## Rollback Plan - -If issues arise during migration: - -1. **Phase 1-2**: No impact, service runs in parallel -2. **Phase 3**: Revert stream processing changes, keep service -3. **Phase 4**: Revert to dual state temporarily -4. **Phase 5-6**: Feature flags for new capabilities - -## Testing Strategy - -### Unit Tests - -- Service methods individually -- Event emissions -- State immutability -- Error handling - -### Integration Tests - -- Service + React hooks -- Service + streaming -- Service + sessions -- Service + remote mode - -### E2E Tests - -- Full chat flows -- Tool execution -- Mode switching -- Session resume -- Interruption handling - -## Success Metrics - -1. **No regressions**: All existing functionality works -2. **Performance**: No noticeable slowdown -3. **Maintainability**: Cleaner, more testable code -4. **Reliability**: No state inconsistencies -5. **Developer experience**: Easier to understand and modify - -## Risk Mitigation - -### High Risk Areas - -1. **Streaming integration**: Most complex change - - Mitigation: Extensive testing, gradual rollout -2. **Remote mode**: Different state management - - - Mitigation: Test thoroughly, maintain compatibility - -3. **Performance**: Large histories might cause issues - - Mitigation: Profiling, optimization, lazy loading - -### Monitoring - -- Add logging for state transitions -- Monitor performance metrics -- Track error rates -- User feedback collection - -## Timeline - -- **Day 1**: Phase 1-2 (Service creation, wrapper) -- **Day 2**: Phase 3-4 (Stream migration, remove duplication) -- **Day 3**: Phase 5 (Optimization, features) -- **Day 4**: Phase 6 (Validation, cleanup) - -Total: 4 days with buffer for issues - -## Implementation Checklist - -### Pre-Migration - -- [ ] Current state documented -- [ ] All stakeholders informed -- [ ] Test environment ready -- [ ] Rollback plan confirmed - -### Phase 1 - -- [ ] ChatHistoryService created -- [ ] Unit tests written -- [ ] Service registered -- [ ] No breaking changes - -### Phase 2 - -- [ ] Compatibility layer working -- [ ] useChat integrated -- [ ] Parallel operation verified -- [ ] No regressions - -### Phase 3 - -- [ ] Stream processing migrated -- [ ] No direct mutations -- [ ] Tool handling updated -- [ ] Tests passing - -### Phase 4 - -- [ ] React state removed -- [ ] Service-only operation -- [ ] Components updated -- [ ] Performance acceptable - -### Phase 5 - -- [ ] Optimizations implemented -- [ ] Features added -- [ ] Remote mode working -- [ ] Documentation updated - -### Phase 6 - -- [ ] All tests passing -- [ ] Code cleaned up -- [ ] Migration complete -- [ ] Team sign-off - -## Post-Migration - -1. Monitor for issues for 1 week -2. Gather performance metrics -3. Document lessons learned -4. Plan future enhancements -5. Knowledge transfer to team - -## Appendix: Code Examples - -### Service Method Example - -```typescript -class ChatHistoryService extends BaseService { - addUserMessage(content: string, contextItems: any[] = []) { - const newMessage: ChatHistoryItem = { - message: { role: "user", content }, - contextItems, - }; - - const newHistory = [...this.currentState.history, newMessage]; - this.setState({ - ...this.currentState, - history: newHistory, - }); - - // Auto-save to session - updateSessionHistory(newHistory); - - return newMessage; - } -} -``` - -### React Integration Example - -```typescript -function ChatComponent() { - const { value: chatState, state } = useService('chatHistory'); - - if (state === 'loading') return ; - if (state === 'error') return ; - - const history = chatState?.history || []; - - return ; -} -``` - -### Migration Pattern Example - -```typescript -// Before: -chatHistory.push(newMessage); -setChatHistory([...chatHistory]); - -// After: -chatHistoryService.addMessage(newMessage); -// React auto-updates via useService hook -``` diff --git a/extensions/cli/package-lock.json b/extensions/cli/package-lock.json index d52b3f219..6510bc717 100644 --- a/extensions/cli/package-lock.json +++ b/extensions/cli/package-lock.json @@ -9,12 +9,6 @@ "version": "0.0.0-dev", "license": "Apache-2.0", "dependencies": { - "@img/sharp-darwin-arm64": "^0.33.5", - "@img/sharp-darwin-x64": "^0.33.5", - "@img/sharp-linux-arm": "^0.33.5", - "@img/sharp-linux-arm64": "^0.33.5", - "@img/sharp-linux-x64": "^0.33.5", - "@img/sharp-win32-x64": "^0.33.5", "@sentry/profiling-node": "^9.43.0" }, "bin": { diff --git a/extensions/cli/src/ui/hooks/useClipboardMonitor.ts b/extensions/cli/src/ui/hooks/useClipboardMonitor.ts index 895cdaa69..203c51e73 100644 --- a/extensions/cli/src/ui/hooks/useClipboardMonitor.ts +++ b/extensions/cli/src/ui/hooks/useClipboardMonitor.ts @@ -1,101 +1,11 @@ import { useEffect, useRef } from "react"; +import { + checkClipboardForImage, + getClipboardImage, +} from "../../util/clipboard.js"; import { logger } from "../../util/logger.js"; -// Helper function to check if clipboard contains an image -async function checkClipboardForImage(): Promise { - try { - const os = await import("os"); - const { exec } = await import("child_process"); - const { promisify } = await import("util"); - const execAsync = promisify(exec); - - const platform = os.platform(); - - if (platform === "darwin") { - // macOS: Check clipboard using osascript - const { stdout } = await execAsync('osascript -e "clipboard info"'); - return ( - stdout.includes("«class PNGf»") || - stdout.includes("«class TIFF»") || - stdout.includes("picture") - ); - } else if (platform === "win32") { - // Windows: Use PowerShell to check clipboard - const { stdout } = await execAsync( - 'powershell -command "Get-Clipboard -Format Image | Measure-Object | Select-Object -ExpandProperty Count"', - ); - return parseInt(stdout.trim()) > 0; - } else if (platform === "linux") { - // Linux: Check if xclip can get image data - try { - await execAsync( - "xclip -selection clipboard -t image/png -o > /dev/null 2>&1", - ); - return true; - } catch { - return false; - } - } - - return false; - } catch (error) { - logger.debug("Error checking clipboard for image:", error); - return false; - } -} - -// Helper function to get image from clipboard -async function getClipboardImage(): Promise { - try { - const os = await import("os"); - const { exec } = await import("child_process"); - const { promisify } = await import("util"); - const execAsync = promisify(exec); - const fs = await import("fs/promises"); - const path = await import("path"); - - const platform = os.platform(); - const tempDir = os.tmpdir(); - const tempImagePath = path.join( - tempDir, - `continue-clipboard-${Date.now()}.png`, - ); - - if (platform === "darwin") { - // macOS: Save clipboard image using osascript - await execAsync( - `osascript -e 'set the clipboard to (the clipboard as «class PNGf»)' -e 'set png_data to (the clipboard as «class PNGf»)' -e 'set file_ref to open for access "${tempImagePath}" with write permission' -e 'write png_data to file_ref' -e 'close access file_ref'`, - ); - } else if (platform === "win32") { - // Windows: Use PowerShell to save clipboard image - await execAsync( - `powershell -command "$image = Get-Clipboard -Format Image; if ($image) { $image.Save('${tempImagePath}') }"`, - ); - } else if (platform === "linux") { - // Linux: Use xclip to save clipboard image - await execAsync( - `xclip -selection clipboard -t image/png -o > "${tempImagePath}"`, - ); - } else { - return null; - } - - // Read the temporary file - const imageBuffer = await fs.readFile(tempImagePath); - - // Clean up the temporary file - await fs.unlink(tempImagePath).catch(() => { - // Ignore cleanup errors - }); - - return imageBuffer; - } catch (error) { - logger.debug("Error reading image from clipboard:", error); - return null; - } -} - interface UseClipboardMonitorOptions { onImageStatusChange?: (hasImage: boolean) => void; enabled?: boolean; diff --git a/extensions/cli/src/ui/hooks/useUserInput.ts b/extensions/cli/src/ui/hooks/useUserInput.ts index cef93ab8d..c0d641b01 100644 --- a/extensions/cli/src/ui/hooks/useUserInput.ts +++ b/extensions/cli/src/ui/hooks/useUserInput.ts @@ -1,4 +1,8 @@ import type { PermissionMode } from "../../permissions/types.js"; +import { + checkClipboardForImage, + getClipboardImage, +} from "../../util/clipboard.js"; import { logger } from "../../util/logger.js"; import type { TextBuffer } from "../TextBuffer.js"; @@ -15,100 +19,6 @@ interface ControlKeysOptions { onTextBufferUpdate?: () => void; } -// Helper function to check if clipboard contains an image -async function checkClipboardForImage(): Promise { - try { - const os = await import("os"); - const { exec } = await import("child_process"); - const { promisify } = await import("util"); - const execAsync = promisify(exec); - - const platform = os.platform(); - - if (platform === "darwin") { - // macOS: Check clipboard using osascript - const { stdout } = await execAsync('osascript -e "clipboard info"'); - return ( - stdout.includes("«class PNGf»") || - stdout.includes("«class TIFF»") || - stdout.includes("picture") - ); - } else if (platform === "win32") { - // Windows: Use PowerShell to check clipboard - const { stdout } = await execAsync( - 'powershell -command "Get-Clipboard -Format Image | Measure-Object | Select-Object -ExpandProperty Count"', - ); - return parseInt(stdout.trim()) > 0; - } else if (platform === "linux") { - // Linux: Check if xclip can get image data - try { - await execAsync( - "xclip -selection clipboard -t image/png -o > /dev/null 2>&1", - ); - return true; - } catch { - return false; - } - } - - return false; - } catch (error) { - logger.debug("Error checking clipboard for image:", error); - return false; - } -} - -// Helper function to get image from clipboard -async function getClipboardImage(): Promise { - try { - const os = await import("os"); - const { exec } = await import("child_process"); - const { promisify } = await import("util"); - const execAsync = promisify(exec); - const fs = await import("fs/promises"); - const path = await import("path"); - - const platform = os.platform(); - const tempDir = os.tmpdir(); - const tempImagePath = path.join( - tempDir, - `continue-clipboard-${Date.now()}.png`, - ); - - if (platform === "darwin") { - // macOS: Save clipboard image using osascript - await execAsync( - `osascript -e 'set the clipboard to (the clipboard as «class PNGf»)' -e 'set png_data to (the clipboard as «class PNGf»)' -e 'set file_ref to open for access "${tempImagePath}" with write permission' -e 'write png_data to file_ref' -e 'close access file_ref'`, - ); - } else if (platform === "win32") { - // Windows: Use PowerShell to save clipboard image - await execAsync( - `powershell -command "$image = Get-Clipboard -Format Image; if ($image) { $image.Save('${tempImagePath}') }"`, - ); - } else if (platform === "linux") { - // Linux: Use xclip to save clipboard image - await execAsync( - `xclip -selection clipboard -t image/png -o > "${tempImagePath}"`, - ); - } else { - return null; - } - - // Read the temporary file - const imageBuffer = await fs.readFile(tempImagePath); - - // Clean up the temporary file - await fs.unlink(tempImagePath).catch(() => { - // Ignore cleanup errors - }); - - return imageBuffer; - } catch (error) { - logger.debug("Error reading image from clipboard:", error); - return null; - } -} - export function handleControlKeys(options: ControlKeysOptions): boolean { const { input, diff --git a/extensions/cli/src/util/clipboard.test.ts b/extensions/cli/src/util/clipboard.test.ts new file mode 100644 index 000000000..308556c05 --- /dev/null +++ b/extensions/cli/src/util/clipboard.test.ts @@ -0,0 +1,235 @@ +import { beforeEach, describe, expect, it, vi } from "vitest"; + +// Mock child_process +vi.mock("child_process", () => ({ + exec: vi.fn(), +})); + +// Mock util.promisify - Must use factory function to avoid hoisting issues +vi.mock("util", () => { + const mockExecAsync = vi.fn(); + return { + promisify: vi.fn(() => mockExecAsync), + __mockExecAsync: mockExecAsync, // Export for test access + }; +}); + +// Mock fs/promises +vi.mock("fs/promises", () => ({ + readFile: vi.fn(), + unlink: vi.fn(), +})); + +// Mock os +vi.mock("os", () => ({ + default: { + platform: vi.fn(), + tmpdir: vi.fn(), + }, + platform: vi.fn(), + tmpdir: vi.fn(), +})); + +// Mock path +vi.mock("path", () => ({ + default: { + join: vi.fn(), + }, + join: vi.fn(), +})); + +// Mock logger +vi.mock("./logger.js", () => ({ + logger: { + debug: vi.fn(), + }, +})); + +// Import after mocks are set up +import { checkClipboardForImage, getClipboardImage } from "./clipboard.js"; + +// Get the mock exec async function +const getMockExecAsync = () => + (vi.mocked(import("util")) as any).__mockExecAsync; + +describe("clipboard utilities", () => { + let mockExecAsync: any; + + beforeEach(async () => { + vi.clearAllMocks(); + // Get the mock function after module is loaded + const util = (await import("util")) as any; + mockExecAsync = util.__mockExecAsync; + }); + + describe("checkClipboardForImage", () => { + it("should detect image on macOS when PNG format is present", async () => { + const os = await import("os"); + vi.mocked(os.default.platform).mockReturnValue("darwin"); + mockExecAsync.mockResolvedValue({ stdout: "«class PNGf»", stderr: "" }); + + const result = await checkClipboardForImage(); + expect(result).toBe(true); + }); + + it("should detect image on macOS when TIFF format is present", async () => { + const os = await import("os"); + vi.mocked(os.default.platform).mockReturnValue("darwin"); + mockExecAsync.mockResolvedValue({ stdout: "«class TIFF»", stderr: "" }); + + const result = await checkClipboardForImage(); + expect(result).toBe(true); + }); + + it("should detect no image on macOS when no image format is present", async () => { + const os = await import("os"); + vi.mocked(os.default.platform).mockReturnValue("darwin"); + mockExecAsync.mockResolvedValue({ stdout: "text content", stderr: "" }); + + const result = await checkClipboardForImage(); + expect(result).toBe(false); + }); + + it("should detect image on Windows when count > 0", async () => { + const os = await import("os"); + vi.mocked(os.default.platform).mockReturnValue("win32"); + mockExecAsync.mockResolvedValue({ stdout: "1\n", stderr: "" }); + + const result = await checkClipboardForImage(); + expect(result).toBe(true); + }); + + it("should detect no image on Windows when count is 0", async () => { + const os = await import("os"); + vi.mocked(os.default.platform).mockReturnValue("win32"); + mockExecAsync.mockResolvedValue({ stdout: "0\n", stderr: "" }); + + const result = await checkClipboardForImage(); + expect(result).toBe(false); + }); + + it("should detect image on Linux when xclip succeeds", async () => { + const os = await import("os"); + vi.mocked(os.default.platform).mockReturnValue("linux"); + mockExecAsync.mockResolvedValue({ stdout: "", stderr: "" }); + + const result = await checkClipboardForImage(); + expect(result).toBe(true); + }); + + it("should detect no image on Linux when xclip fails", async () => { + const os = await import("os"); + vi.mocked(os.default.platform).mockReturnValue("linux"); + mockExecAsync.mockRejectedValue(new Error("xclip failed")); + + const result = await checkClipboardForImage(); + expect(result).toBe(false); + }); + + it("should return false and log error on exception", async () => { + const os = await import("os"); + vi.mocked(os.default.platform).mockReturnValue("darwin"); + mockExecAsync.mockRejectedValue(new Error("Unexpected error")); + + const result = await checkClipboardForImage(); + expect(result).toBe(false); + }); + }); + + describe("getClipboardImage", () => { + const mockImageBuffer = Buffer.from("fake-image-data"); + + it("should get image from clipboard on macOS", async () => { + const os = await import("os"); + const path = await import("path"); + const fs = await import("fs/promises"); + + vi.mocked(os.default.platform).mockReturnValue("darwin"); + vi.mocked(os.default.tmpdir).mockReturnValue("/tmp"); + vi.mocked(path.default.join).mockReturnValue( + "/tmp/continue-clipboard-123.png", + ); + mockExecAsync.mockResolvedValue({ stdout: "", stderr: "" }); + vi.mocked(fs.readFile).mockResolvedValue(mockImageBuffer); + vi.mocked(fs.unlink).mockResolvedValue(undefined); + + const result = await getClipboardImage(); + expect(result).toEqual(mockImageBuffer); + expect(fs.unlink).toHaveBeenCalled(); + }); + + it("should get image from clipboard on Windows", async () => { + const os = await import("os"); + const path = await import("path"); + const fs = await import("fs/promises"); + + vi.mocked(os.default.platform).mockReturnValue("win32"); + vi.mocked(os.default.tmpdir).mockReturnValue("C:\\temp"); + vi.mocked(path.default.join).mockReturnValue( + "C:\\temp\\continue-clipboard-123.png", + ); + mockExecAsync.mockResolvedValue({ stdout: "", stderr: "" }); + vi.mocked(fs.readFile).mockResolvedValue(mockImageBuffer); + vi.mocked(fs.unlink).mockResolvedValue(undefined); + + const result = await getClipboardImage(); + expect(result).toEqual(mockImageBuffer); + expect(fs.unlink).toHaveBeenCalled(); + }); + + it("should get image from clipboard on Linux", async () => { + const os = await import("os"); + const path = await import("path"); + const fs = await import("fs/promises"); + + vi.mocked(os.default.platform).mockReturnValue("linux"); + vi.mocked(os.default.tmpdir).mockReturnValue("/tmp"); + vi.mocked(path.default.join).mockReturnValue( + "/tmp/continue-clipboard-123.png", + ); + mockExecAsync.mockResolvedValue({ stdout: "", stderr: "" }); + vi.mocked(fs.readFile).mockResolvedValue(mockImageBuffer); + vi.mocked(fs.unlink).mockResolvedValue(undefined); + + const result = await getClipboardImage(); + expect(result).toEqual(mockImageBuffer); + expect(fs.unlink).toHaveBeenCalled(); + }); + + it("should return null for unsupported platforms", async () => { + const os = await import("os"); + vi.mocked(os.default.platform).mockReturnValue("freebsd"); + + const result = await getClipboardImage(); + expect(result).toBeNull(); + }); + + it("should clean up temp file even if unlink fails", async () => { + const os = await import("os"); + const path = await import("path"); + const fs = await import("fs/promises"); + + vi.mocked(os.default.platform).mockReturnValue("darwin"); + vi.mocked(os.default.tmpdir).mockReturnValue("/tmp"); + vi.mocked(path.default.join).mockReturnValue( + "/tmp/continue-clipboard-123.png", + ); + mockExecAsync.mockResolvedValue({ stdout: "", stderr: "" }); + vi.mocked(fs.readFile).mockResolvedValue(mockImageBuffer); + vi.mocked(fs.unlink).mockRejectedValue(new Error("Failed to delete")); + + const result = await getClipboardImage(); + expect(result).toEqual(mockImageBuffer); + expect(fs.unlink).toHaveBeenCalled(); + }); + + it("should return null and log error on exception", async () => { + const os = await import("os"); + vi.mocked(os.default.platform).mockReturnValue("darwin"); + mockExecAsync.mockRejectedValue(new Error("Unexpected error")); + + const result = await getClipboardImage(); + expect(result).toBeNull(); + }); + }); +}); diff --git a/extensions/cli/src/util/clipboard.ts b/extensions/cli/src/util/clipboard.ts new file mode 100644 index 000000000..571802eee --- /dev/null +++ b/extensions/cli/src/util/clipboard.ts @@ -0,0 +1,97 @@ +import { exec } from "child_process"; +import { readFile, unlink } from "fs/promises"; +import os from "os"; +import path from "path"; +import { promisify } from "util"; + +import { logger } from "./logger.js"; + +const execAsync = promisify(exec); + +/** + * Check if clipboard contains an image + * @returns Promise - true if clipboard contains an image + */ +export async function checkClipboardForImage(): Promise { + try { + const platform = os.platform(); + + if (platform === "darwin") { + // macOS: Check clipboard using osascript + const { stdout } = await execAsync('osascript -e "clipboard info"'); + return ( + stdout.includes("«class PNGf»") || + stdout.includes("«class TIFF»") || + stdout.includes("picture") + ); + } else if (platform === "win32") { + // Windows: Use PowerShell to check clipboard + const { stdout } = await execAsync( + 'powershell -command "Get-Clipboard -Format Image | Measure-Object | Select-Object -ExpandProperty Count"', + ); + return parseInt(stdout.trim()) > 0; + } else if (platform === "linux") { + // Linux: Check if xclip can get image data + try { + await execAsync( + "xclip -selection clipboard -t image/png -o > /dev/null 2>&1", + ); + return true; + } catch { + return false; + } + } + + return false; + } catch (error) { + logger.debug("Error checking clipboard for image:", error); + return false; + } +} + +/** + * Get image from clipboard as a Buffer + * @returns Promise - Image buffer if available, null otherwise + */ +export async function getClipboardImage(): Promise { + try { + const platform = os.platform(); + const tempDir = os.tmpdir(); + const tempImagePath = path.join( + tempDir, + `continue-clipboard-${Date.now()}.png`, + ); + + if (platform === "darwin") { + // macOS: Save clipboard image using osascript + await execAsync( + `osascript -e 'set the clipboard to (the clipboard as «class PNGf»)' -e 'set png_data to (the clipboard as «class PNGf»)' -e 'set file_ref to open for access "${tempImagePath}" with write permission' -e 'write png_data to file_ref' -e 'close access file_ref'`, + ); + } else if (platform === "win32") { + // Windows: Use PowerShell to save clipboard image + await execAsync( + `powershell -command "$image = Get-Clipboard -Format Image; if ($image) { $image.Save('${tempImagePath}') }"`, + ); + } else if (platform === "linux") { + // Linux: Use xclip to save clipboard image + await execAsync( + `xclip -selection clipboard -t image/png -o > "${tempImagePath}"`, + ); + } else { + return null; + } + + // Read the temporary file + const imageBuffer = await readFile(tempImagePath); + + // Clean up the temporary file + await unlink(tempImagePath).catch(() => { + // Ignore cleanup errors + }); + + return imageBuffer; + } catch (error) { + logger.debug("Error reading image from clipboard:", error); + return null; + } +} diff --git a/packages/openai-adapters/package-lock.json b/packages/openai-adapters/package-lock.json index 806a98f2a..046b1dc37 100644 --- a/packages/openai-adapters/package-lock.json +++ b/packages/openai-adapters/package-lock.json @@ -12528,7 +12528,6 @@ "resolved": "https://registry.npmjs.org/typescript/-/typescript-5.5.4.tgz", "integrity": "sha512-Mtq29sKDAEYP7aljRgtPOpTvOfbwRWlS6dPRzwjdE+C0R4brX/GUyhHSecbHMFLNBLcJIPt9nl9yG5TZ1weH+Q==", "dev": true, - "peer": true, "bin": { "tsc": "bin/tsc", "tsserver": "bin/tsserver"