Changesets · Branches · Tags · Compare
| Changeset | 4409bbdbfe8eb95b15ae5066f554665ba7846b8bd414a43e84c02cafec5655bf |
|---|---|
| Author | Nate Sesti <33237525+sestinj@users.noreply.github.com> · 2025-09-01 11:14 -07:00 |
| Committer | GitHub <noreply@github.com> · 2025-09-01 11:14 -07:00 |
| Parents | ea463c709f50, be2570f22daf |
14 files changed
modified extensions/cli/package-lock.json +0 −0
Not shown: the file is larger than the hub shows, or this page holds as much as it shows. View the file.
modified extensions/cli/package.json +43 −35
| @@ -59,79 +59,87 @@ | ||
| 59 | 59 | "@opentelemetry/resources": "^2.0.1", |
| 60 | 60 | "@opentelemetry/sdk-node": "^0.203.0", |
| 61 | 61 | "@opentelemetry/semantic-conventions": "^1.36.0", |
| 62 | - "@sentry/node": "^9.43.0", | |
| 63 | - "@types/express": "^5.0.3", | |
| 64 | - "@types/react": "^19.1.8", | |
| 65 | - "@types/turndown": "^5.0.5", | |
| 66 | - "@workos-inc/node": "^7.45.0", | |
| 67 | - "chalk": "^5.4.1", | |
| 68 | - "commander": "^14.0.0", | |
| 69 | - "core": "file:../../core", | |
| 70 | - "date-fns": "^4.1.0", | |
| 71 | - "diff": "^7.0.0", | |
| 72 | - "dotenv": "^16.5.0", | |
| 73 | - "express": "^5.1.0", | |
| 74 | - "glob": "^11.0.3", | |
| 75 | - "gpt-tokenizer": "^3.0.1", | |
| 76 | - "gradient-string": "^3.0.0", | |
| 77 | - "ignore": "^7.0.5", | |
| 78 | - "ignore-walk": "^7.0.0", | |
| 79 | - "ink": "^6.1.0", | |
| 80 | - "jszip": "^3.10.1", | |
| 81 | - "lowlight": "^3.3.0", | |
| 82 | - "minimatch": "^10.0.3", | |
| 83 | - "node-fetch": "^3.3.2", | |
| 84 | - "node-machine-id": "^1.1.12", | |
| 85 | - "open": "^10.1.0", | |
| 86 | - "posthog-node": "^5.6.0", | |
| 87 | - "react": "^19.1.0", | |
| 88 | - "readline-sync": "^1.4.10", | |
| 89 | - "shell-quote": "^1.8.3", | |
| 90 | - "swr": "^2.3.4", | |
| 91 | - "turndown": "^7.2.0", | |
| 92 | - "typescript": "^5.8.3", | |
| 93 | - "uuid": "^9.0.1", | |
| 94 | - "winston": "^3.17.0", | |
| 95 | - "yaml": "^2.8.0", | |
| 96 | 62 | "@semantic-release/changelog": "^6.0.3", |
| 97 | 63 | "@semantic-release/git": "^10.0.1", |
| 98 | 64 | "@semantic-release/github": "^11.0.3", |
| 99 | 65 | "@semantic-release/npm": "^12.0.2", |
| 66 | + "@sentry/node": "^9.43.0", | |
| 100 | 67 | "@testing-library/react": "^16.3.0", |
| 101 | 68 | "@types/date-fns": "^2.5.3", |
| 102 | 69 | "@types/diff": "^7.0.2", |
| 70 | + "@types/express": "^5.0.3", | |
| 103 | 71 | "@types/glob": "^8.1.0", |
| 104 | 72 | "@types/ignore-walk": "^4.0.3", |
| 105 | 73 | "@types/ink-testing-library": "^1.0.4", |
| 106 | 74 | "@types/jszip": "^3.4.0", |
| 107 | 75 | "@types/nock": "^10.0.3", |
| 76 | + "@types/react": "^19.1.8", | |
| 108 | 77 | "@types/readline-sync": "^1.4.8", |
| 109 | 78 | "@types/shell-quote": "^1.7.5", |
| 110 | 79 | "@types/supertest": "^6.0.3", |
| 80 | + "@types/turndown": "^5.0.5", | |
| 111 | 81 | "@types/uuid": "^10.0.0", |
| 112 | 82 | "@typescript-eslint/eslint-plugin": "^8.39.0", |
| 113 | 83 | "@typescript-eslint/parser": "^8.39.0", |
| 114 | 84 | "@vitest/ui": "^3.2.4", |
| 85 | + "@workos-inc/node": "^7.45.0", | |
| 86 | + "chalk": "^5.4.1", | |
| 87 | + "commander": "^14.0.0", | |
| 115 | 88 | "conventional-changelog-conventionalcommits": "^9.1.0", |
| 89 | + "core": "file:../../core", | |
| 116 | 90 | "cross-env": "^7.0.3", |
| 91 | + "date-fns": "^4.1.0", | |
| 92 | + "diff": "^7.0.0", | |
| 93 | + "dotenv": "^16.5.0", | |
| 117 | 94 | "esbuild": "^0.25.9", |
| 118 | 95 | "eslint": "^9.32.0", |
| 119 | 96 | "eslint-import-resolver-typescript": "^4.4.4", |
| 120 | 97 | "eslint-plugin-import": "^2.32.0", |
| 121 | 98 | "eslint-plugin-unused-imports": "^4.1.4", |
| 122 | 99 | "execa": "^9.6.0", |
| 100 | + "express": "^5.1.0", | |
| 101 | + "glob": "^11.0.3", | |
| 102 | + "gpt-tokenizer": "^3.0.1", | |
| 103 | + "gradient-string": "^3.0.0", | |
| 123 | 104 | "happy-dom": "^18.0.1", |
| 105 | + "ignore": "^7.0.5", | |
| 106 | + "ignore-walk": "^7.0.0", | |
| 107 | + "ink": "^6.1.0", | |
| 124 | 108 | "ink-testing-library": "^4.0.0", |
| 125 | 109 | "jsdom": "^26.1.0", |
| 110 | + "jszip": "^3.10.1", | |
| 111 | + "lowlight": "^3.3.0", | |
| 112 | + "minimatch": "^10.0.3", | |
| 126 | 113 | "nock": "^14.0.5", |
| 114 | + "node-fetch": "^3.3.2", | |
| 115 | + "node-machine-id": "^1.1.12", | |
| 116 | + "open": "^10.1.0", | |
| 117 | + "posthog-node": "^5.6.0", | |
| 127 | 118 | "prettier": "^3.6.2", |
| 119 | + "react": "^19.1.0", | |
| 120 | + "readline-sync": "^1.4.10", | |
| 128 | 121 | "semantic-release": "^24.2.7", |
| 122 | + "shell-quote": "^1.8.3", | |
| 129 | 123 | "supertest": "^7.1.3", |
| 124 | + "swr": "^2.3.4", | |
| 130 | 125 | "ts-node": "^10.9.2", |
| 131 | 126 | "tsx": "^4.20.3", |
| 132 | - "vitest": "^3.2.4" | |
| 127 | + "turndown": "^7.2.0", | |
| 128 | + "typescript": "^5.8.3", | |
| 129 | + "uuid": "^9.0.1", | |
| 130 | + "vitest": "^3.2.4", | |
| 131 | + "winston": "^3.17.0", | |
| 132 | + "yaml": "^2.8.0" | |
| 133 | 133 | }, |
| 134 | 134 | "engine": { |
| 135 | 135 | "node": ">=18" |
| 136 | + }, | |
| 137 | + "optionalDependencies": { | |
| 138 | + "@img/sharp-darwin-arm64": "^0.33.5", | |
| 139 | + "@img/sharp-darwin-x64": "^0.33.5", | |
| 140 | + "@img/sharp-linux-arm": "^0.33.5", | |
| 141 | + "@img/sharp-linux-arm64": "^0.33.5", | |
| 142 | + "@img/sharp-linux-x64": "^0.33.5", | |
| 143 | + "@img/sharp-win32-x64": "^0.33.5" | |
| 136 | 144 | } |
| 137 | 145 | } |
added extensions/cli/src/ui/ImagePaste.test.ts +143 −0
| @@ -0,0 +1,143 @@ | ||
| 1 | +import { describe, it, expect, beforeEach } from "vitest"; | |
| 2 | + | |
| 3 | +import { TextBuffer } from "./TextBuffer.js"; | |
| 4 | + | |
| 5 | +describe("Image Pasting Functionality", () => { | |
| 6 | + let textBuffer: TextBuffer; | |
| 7 | + | |
| 8 | + beforeEach(() => { | |
| 9 | + textBuffer = new TextBuffer(); | |
| 10 | + }); | |
| 11 | + | |
| 12 | + describe("TextBuffer Image Support", () => { | |
| 13 | + it("should add image placeholder to text buffer", () => { | |
| 14 | + const mockImageBuffer = Buffer.from("fake-image-data"); | |
| 15 | + | |
| 16 | + const placeholder = textBuffer.addImage(mockImageBuffer); | |
| 17 | + | |
| 18 | + expect(placeholder).toBe("[Image #1]"); | |
| 19 | + expect(textBuffer.text).toBe("[Image #1]"); | |
| 20 | + expect(textBuffer.getAllImages().size).toBe(1); | |
| 21 | + expect(textBuffer.getAllImages().get(placeholder)).toBe(mockImageBuffer); | |
| 22 | + }); | |
| 23 | + | |
| 24 | + it("should handle multiple images with incrementing counters", () => { | |
| 25 | + const mockImageBuffer1 = Buffer.from("fake-image-data-1"); | |
| 26 | + const mockImageBuffer2 = Buffer.from("fake-image-data-2"); | |
| 27 | + | |
| 28 | + const placeholder1 = textBuffer.addImage(mockImageBuffer1); | |
| 29 | + const placeholder2 = textBuffer.addImage(mockImageBuffer2); | |
| 30 | + | |
| 31 | + expect(placeholder1).toBe("[Image #1]"); | |
| 32 | + expect(placeholder2).toBe("[Image #2]"); | |
| 33 | + expect(textBuffer.text).toBe("[Image #1][Image #2]"); | |
| 34 | + expect(textBuffer.getAllImages().size).toBe(2); | |
| 35 | + }); | |
| 36 | + | |
| 37 | + it("should clear images when buffer is cleared", () => { | |
| 38 | + const mockImageBuffer = Buffer.from("fake-image-data"); | |
| 39 | + textBuffer.addImage(mockImageBuffer); | |
| 40 | + | |
| 41 | + textBuffer.clear(); | |
| 42 | + | |
| 43 | + expect(textBuffer.getAllImages().size).toBe(0); | |
| 44 | + expect(textBuffer.text).toBe(""); | |
| 45 | + }); | |
| 46 | + | |
| 47 | + it("should clear only images with clearImages()", () => { | |
| 48 | + const mockImageBuffer = Buffer.from("fake-image-data"); | |
| 49 | + textBuffer.insertText("Some text "); | |
| 50 | + textBuffer.addImage(mockImageBuffer); | |
| 51 | + textBuffer.insertText(" more text"); | |
| 52 | + | |
| 53 | + textBuffer.clearImages(); | |
| 54 | + | |
| 55 | + expect(textBuffer.getAllImages().size).toBe(0); | |
| 56 | + expect(textBuffer.text).toContain("Some text"); | |
| 57 | + expect(textBuffer.text).toContain("[Image #1]"); | |
| 58 | + expect(textBuffer.text).toContain("more text"); | |
| 59 | + }); | |
| 60 | + }); | |
| 61 | + | |
| 62 | + describe("Message Formatting with Images", () => { | |
| 63 | + it("should format message with images correctly", async () => { | |
| 64 | + const { formatMessageWithFiles } = await import( | |
| 65 | + "./hooks/useChat.helpers.js" | |
| 66 | + ); | |
| 67 | + | |
| 68 | + const message = "Here is an image: [Image #1] and some text"; | |
| 69 | + const attachedFiles: Array<{ path: string; content: string }> = []; | |
| 70 | + const imageMap = new Map([ | |
| 71 | + ["[Image #1]", Buffer.from("fake-image-data")], | |
| 72 | + ]); | |
| 73 | + | |
| 74 | + const result = await formatMessageWithFiles( | |
| 75 | + message, | |
| 76 | + attachedFiles, | |
| 77 | + imageMap, | |
| 78 | + ); | |
| 79 | + | |
| 80 | + expect(result.message.role).toBe("user"); | |
| 81 | + expect(Array.isArray(result.message.content)).toBe(true); | |
| 82 | + | |
| 83 | + const content = result.message.content as any[]; | |
| 84 | + expect(content).toHaveLength(3); | |
| 85 | + expect(content[0]).toEqual({ | |
| 86 | + type: "text", | |
| 87 | + text: "Here is an image: ", | |
| 88 | + }); | |
| 89 | + expect(content[1]).toEqual({ | |
| 90 | + type: "imageUrl", | |
| 91 | + imageUrl: { url: expect.stringMatching(/^data:image\/png;base64,/) }, | |
| 92 | + }); | |
| 93 | + expect(content[2]).toEqual({ | |
| 94 | + type: "text", | |
| 95 | + text: " and some text", | |
| 96 | + }); | |
| 97 | + }); | |
| 98 | + | |
| 99 | + it("should handle message with only text (no images)", async () => { | |
| 100 | + const { formatMessageWithFiles } = await import( | |
| 101 | + "./hooks/useChat.helpers.js" | |
| 102 | + ); | |
| 103 | + | |
| 104 | + const message = "Just text, no images"; | |
| 105 | + const attachedFiles: Array<{ path: string; content: string }> = []; | |
| 106 | + | |
| 107 | + const result = await formatMessageWithFiles(message, attachedFiles); | |
| 108 | + | |
| 109 | + expect(result.message.role).toBe("user"); | |
| 110 | + expect(result.message.content).toBe("Just text, no images"); | |
| 111 | + }); | |
| 112 | + | |
| 113 | + it("should handle multiple images in message", async () => { | |
| 114 | + const { formatMessageWithFiles } = await import( | |
| 115 | + "./hooks/useChat.helpers.js" | |
| 116 | + ); | |
| 117 | + | |
| 118 | + const message = "First [Image #1] then text [Image #2] end"; | |
| 119 | + const attachedFiles: Array<{ path: string; content: string }> = []; | |
| 120 | + const imageMap = new Map([ | |
| 121 | + ["[Image #1]", Buffer.from("fake-image-data-1")], | |
| 122 | + ["[Image #2]", Buffer.from("fake-image-data-2")], | |
| 123 | + ]); | |
| 124 | + | |
| 125 | + const result = await formatMessageWithFiles( | |
| 126 | + message, | |
| 127 | + attachedFiles, | |
| 128 | + imageMap, | |
| 129 | + ); | |
| 130 | + | |
| 131 | + expect(Array.isArray(result.message.content)).toBe(true); | |
| 132 | + const content = result.message.content as any[]; | |
| 133 | + | |
| 134 | + // Should have: text, image, text, image, text = 5 parts | |
| 135 | + expect(content).toHaveLength(5); | |
| 136 | + expect(content[0].type).toBe("text"); | |
| 137 | + expect(content[1].type).toBe("imageUrl"); | |
| 138 | + expect(content[2].type).toBe("text"); | |
| 139 | + expect(content[3].type).toBe("imageUrl"); | |
| 140 | + expect(content[4].type).toBe("text"); | |
| 141 | + }); | |
| 142 | + }); | |
| 143 | +}); |
modified extensions/cli/src/ui/TextBuffer.ts +53 −0
| @@ -2,6 +2,9 @@ | ||
| 2 | 2 | |
| 3 | 3 | export const COLLAPSE_SIZE = 800; // Characters threshold for collapsing pasted content |
| 4 | 4 | export const RAPID_INPUT_THRESHOLD = 200; // Minimum characters to trigger rapid input detection |
| 5 | +export const MAX_IMAGE_SIZE = 10 * 1024 * 1024; // 10MB per image | |
| 6 | +export const MAX_IMAGE_COUNT = 20; // Maximum number of images | |
| 7 | +export const MAX_TOTAL_IMAGE_MEMORY = 50 * 1024 * 1024; // 50MB total image memory | |
| 5 | 8 | |
| 6 | 9 | export class TextBuffer { |
| 7 | 10 | private _text: string = ""; |
| @@ -15,6 +18,8 @@ | ||
| 15 | 18 | private _onStateChange?: () => void; |
| 16 | 19 | private _pasteMap = new Map<string, string>(); // placeholder -> original content |
| 17 | 20 | private _pasteCounter: number = 0; |
| 21 | + private _imageMap = new Map<string, Buffer>(); // placeholder -> image buffer | |
| 22 | + private _imageCounter: number = 0; | |
| 18 | 23 | |
| 19 | 24 | constructor(initialText: string = "") { |
| 20 | 25 | this._text = initialText; |
| @@ -153,6 +158,8 @@ | ||
| 153 | 158 | this._cursor = 0; |
| 154 | 159 | this._pasteMap.clear(); |
| 155 | 160 | this._pasteCounter = 0; |
| 161 | + this._imageMap.clear(); | |
| 162 | + this._imageCounter = 0; | |
| 156 | 163 | this._pasteBuffer = ""; |
| 157 | 164 | this._inPasteMode = false; |
| 158 | 165 | this._rapidInputBuffer = ""; |
| @@ -189,6 +196,52 @@ | ||
| 189 | 196 | this._pasteMap.clear(); |
| 190 | 197 | } |
| 191 | 198 | |
| 199 | + // Add image to buffer and return placeholder | |
| 200 | + addImage(imageBuffer: Buffer): string { | |
| 201 | + // Validate image size | |
| 202 | + if (imageBuffer.length > MAX_IMAGE_SIZE) { | |
| 203 | + throw new Error( | |
| 204 | + `Image size ${(imageBuffer.length / 1024 / 1024).toFixed(1)}MB exceeds maximum allowed size of ${MAX_IMAGE_SIZE / 1024 / 1024}MB`, | |
| 205 | + ); | |
| 206 | + } | |
| 207 | + | |
| 208 | + // Check image count limit | |
| 209 | + if (this._imageMap.size >= MAX_IMAGE_COUNT) { | |
| 210 | + throw new Error(`Cannot add more than ${MAX_IMAGE_COUNT} images`); | |
| 211 | + } | |
| 212 | + | |
| 213 | + // Check total memory usage | |
| 214 | + const currentMemoryUsage = Array.from(this._imageMap.values()).reduce( | |
| 215 | + (total, buffer) => total + buffer.length, | |
| 216 | + 0, | |
| 217 | + ); | |
| 218 | + | |
| 219 | + if (currentMemoryUsage + imageBuffer.length > MAX_TOTAL_IMAGE_MEMORY) { | |
| 220 | + const currentUsageMB = (currentMemoryUsage / 1024 / 1024).toFixed(1); | |
| 221 | + const maxUsageMB = MAX_TOTAL_IMAGE_MEMORY / 1024 / 1024; | |
| 222 | + throw new Error( | |
| 223 | + `Adding image would exceed total memory limit. Current usage: ${currentUsageMB}MB, Maximum: ${maxUsageMB}MB`, | |
| 224 | + ); | |
| 225 | + } | |
| 226 | + | |
| 227 | + this._imageCounter++; | |
| 228 | + const placeholder = `[Image #${this._imageCounter}]`; | |
| 229 | + this._imageMap.set(placeholder, imageBuffer); | |
| 230 | + this.insertText(placeholder); | |
| 231 | + return placeholder; | |
| 232 | + } | |
| 233 | + | |
| 234 | + // Get all images for message formatting | |
| 235 | + getAllImages(): Map<string, Buffer> { | |
| 236 | + return new Map(this._imageMap); | |
| 237 | + } | |
| 238 | + | |
| 239 | + // Clear images after message submission | |
| 240 | + clearImages(): void { | |
| 241 | + this._imageMap.clear(); | |
| 242 | + this._imageCounter = 0; | |
| 243 | + } | |
| 244 | + | |
| 192 | 245 | // Test helper: forces immediate finalization without waiting for timers |
| 193 | 246 | flushPendingInput(): void { |
| 194 | 247 | if (this._rapidInputTimer) { |
modified extensions/cli/src/ui/UserInput.tsx +21 −4
| @@ -20,7 +20,7 @@ | ||
| 20 | 20 | import { TextBuffer } from "./TextBuffer.js"; |
| 21 | 21 | |
| 22 | 22 | interface UserInputProps { |
| 23 | - onSubmit: (message: string) => void; | |
| 23 | + onSubmit: (message: string, imageMap?: Map<string, Buffer>) => void; | |
| 24 | 24 | isWaitingForResponse: boolean; |
| 25 | 25 | inputMode: boolean; |
| 26 | 26 | onInterrupt?: () => void; |
| @@ -408,8 +408,11 @@ | ||
| 408 | 408 | return true; |
| 409 | 409 | } |
| 410 | 410 | |
| 411 | - // Normal Enter behavior - submit if there's content OR if resuming after interruption | |
| 411 | + // Normal Enter behavior - submit if there's content | |
| 412 | 412 | if ((textBuffer.text.trim() || wasInterrupted) && !isWaitingForResponse) { |
| 413 | + // Get images before expanding paste blocks | |
| 414 | + const imageMap = textBuffer.getAllImages(); | |
| 415 | + | |
| 413 | 416 | // Expand all paste blocks before submitting |
| 414 | 417 | textBuffer.expandAllPasteBlocks(); |
| 415 | 418 | const submittedText = textBuffer.text.trim(); |
| @@ -419,8 +422,9 @@ | ||
| 419 | 422 | inputHistory.addEntry(submittedText); |
| 420 | 423 | } |
| 421 | 424 | |
| 422 | - // Send empty string when resuming, actual text otherwise | |
| 423 | - onSubmit(submittedText); | |
| 425 | + // Submit with images | |
| 426 | + onSubmit(submittedText, imageMap); | |
| 427 | + | |
| 424 | 428 | textBuffer.clear(); |
| 425 | 429 | setInputText(""); |
| 426 | 430 | setCursorPosition(0); |
| @@ -481,6 +485,17 @@ | ||
| 481 | 485 | inputHistory.resetNavigation(); |
| 482 | 486 | }; |
| 483 | 487 | |
| 488 | + // Handle text buffer updates for async operations like image pasting | |
| 489 | + const handleTextBufferUpdate = () => { | |
| 490 | + const newText = textBuffer.text; | |
| 491 | + const newCursor = textBuffer.cursor; | |
| 492 | + setInputText(newText); | |
| 493 | + setCursorPosition(newCursor); | |
| 494 | + updateSlashCommandState(newText, newCursor); | |
| 495 | + updateFileSearchState(newText, newCursor); | |
| 496 | + inputHistory.resetNavigation(); | |
| 497 | + }; | |
| 498 | + | |
| 484 | 499 | useInput((input, key) => { |
| 485 | 500 | // Don't handle any input when disabled |
| 486 | 501 | if (disabled) { |
| @@ -497,6 +512,8 @@ | ||
| 497 | 512 | showFileSearch, |
| 498 | 513 | cycleModes, |
| 499 | 514 | clearInput, |
| 515 | + textBuffer, | |
| 516 | + onTextBufferUpdate: handleTextBufferUpdate, | |
| 500 | 517 | }) |
| 501 | 518 | ) { |
| 502 | 519 | return; |
modified extensions/cli/src/ui/__tests__/TUIChat.interruption.minimal.test.tsx +2 −1
| @@ -117,7 +117,7 @@ | ||
| 117 | 117 | stdin.write("\r"); |
| 118 | 118 | |
| 119 | 119 | // Should call onSubmit with empty string (for resume) |
| 120 | - expect(mockOnSubmit).toHaveBeenCalledWith(""); | |
| 120 | + expect(mockOnSubmit).toHaveBeenCalledWith("", expect.any(Map)); | |
| 121 | 121 | } finally { |
| 122 | 122 | unmount(); |
| 123 | 123 | } |
| @@ -145,6 +145,7 @@ | ||
| 145 | 145 | // Should call onSubmit with the typed content |
| 146 | 146 | expect(mockOnSubmit).toHaveBeenCalledWith( |
| 147 | 147 | "New message after interruption", |
| 148 | + expect.any(Map), | |
| 148 | 149 | ); |
| 149 | 150 | } finally { |
| 150 | 151 | unmount(); |
added extensions/cli/src/ui/components/MemoizedMessage.formatDisplay.test.tsx +145 −0
| @@ -0,0 +1,145 @@ | ||
| 1 | +import { render } from "ink-testing-library"; | |
| 2 | +import React from "react"; | |
| 3 | +import { describe, expect, it } from "vitest"; | |
| 4 | + | |
| 5 | +import type { | |
| 6 | + ChatHistoryItem, | |
| 7 | + MessageContent, | |
| 8 | + MessagePart, | |
| 9 | +} from "../../../../../core/index.js"; | |
| 10 | + | |
| 11 | +import { MemoizedMessage } from "./MemoizedMessage.js"; | |
| 12 | + | |
| 13 | +describe("MemoizedMessage formatMessageContentForDisplay", () => { | |
| 14 | + const createTestHistoryItem = (content: MessageContent): ChatHistoryItem => ({ | |
| 15 | + message: { | |
| 16 | + role: "user", | |
| 17 | + content, | |
| 18 | + }, | |
| 19 | + contextItems: [], | |
| 20 | + }); | |
| 21 | + | |
| 22 | + it("should display string content as-is", () => { | |
| 23 | + const content = "Just a simple text message"; | |
| 24 | + const historyItem = createTestHistoryItem(content); | |
| 25 | + | |
| 26 | + const { lastFrame } = render( | |
| 27 | + <MemoizedMessage item={historyItem} index={1} />, | |
| 28 | + ); | |
| 29 | + | |
| 30 | + expect(lastFrame()).toContain("Just a simple text message"); | |
| 31 | + }); | |
| 32 | + | |
| 33 | + it("should display message with images using placeholders", () => { | |
| 34 | + const messageParts: MessagePart[] = [ | |
| 35 | + { type: "text", text: "Here is an image: " }, | |
| 36 | + { type: "imageUrl", imageUrl: { url: "data:image/png;base64,abc123" } }, | |
| 37 | + { type: "text", text: " and some more text" }, | |
| 38 | + ]; | |
| 39 | + const historyItem = createTestHistoryItem(messageParts); | |
| 40 | + | |
| 41 | + const { lastFrame } = render( | |
| 42 | + <MemoizedMessage item={historyItem} index={1} />, | |
| 43 | + ); | |
| 44 | + | |
| 45 | + const output = lastFrame(); | |
| 46 | + expect(output).toContain("Here is an image: [Image #1] and some more text"); | |
| 47 | + expect(output).not.toContain("data:image/png;base64,abc123"); | |
| 48 | + expect(output).not.toContain("imageUrl"); | |
| 49 | + }); | |
| 50 | + | |
| 51 | + it("should display message with multiple images using incrementing placeholders", () => { | |
| 52 | + const messageParts: MessagePart[] = [ | |
| 53 | + { type: "text", text: "First " }, | |
| 54 | + { type: "imageUrl", imageUrl: { url: "data:image/png;base64,abc123" } }, | |
| 55 | + { type: "text", text: " then text " }, | |
| 56 | + { type: "imageUrl", imageUrl: { url: "data:image/jpeg;base64,def456" } }, | |
| 57 | + { type: "text", text: " end" }, | |
| 58 | + ]; | |
| 59 | + const historyItem = createTestHistoryItem(messageParts); | |
| 60 | + | |
| 61 | + const { lastFrame } = render( | |
| 62 | + <MemoizedMessage item={historyItem} index={1} />, | |
| 63 | + ); | |
| 64 | + | |
| 65 | + const output = lastFrame(); | |
| 66 | + expect(output).toContain("First [Image #1] then text [Image #2] end"); | |
| 67 | + expect(output).not.toContain("data:image/png;base64"); | |
| 68 | + expect(output).not.toContain("data:image/jpeg;base64"); | |
| 69 | + }); | |
| 70 | + | |
| 71 | + it("should display message with only images", () => { | |
| 72 | + const messageParts: MessagePart[] = [ | |
| 73 | + { type: "imageUrl", imageUrl: { url: "data:image/png;base64,abc123" } }, | |
| 74 | + { type: "imageUrl", imageUrl: { url: "data:image/png;base64,def456" } }, | |
| 75 | + ]; | |
| 76 | + const historyItem = createTestHistoryItem(messageParts); | |
| 77 | + | |
| 78 | + const { lastFrame } = render( | |
| 79 | + <MemoizedMessage item={historyItem} index={1} />, | |
| 80 | + ); | |
| 81 | + | |
| 82 | + const output = lastFrame(); | |
| 83 | + expect(output).toContain("[Image #1][Image #2]"); | |
| 84 | + }); | |
| 85 | + | |
| 86 | + it("should handle empty text parts gracefully", () => { | |
| 87 | + const messageParts: MessagePart[] = [ | |
| 88 | + { type: "text", text: "" }, | |
| 89 | + { type: "imageUrl", imageUrl: { url: "data:image/png;base64,abc123" } }, | |
| 90 | + { type: "text", text: "" }, | |
| 91 | + ]; | |
| 92 | + const historyItem = createTestHistoryItem(messageParts); | |
| 93 | + | |
| 94 | + const { lastFrame } = render( | |
| 95 | + <MemoizedMessage item={historyItem} index={1} />, | |
| 96 | + ); | |
| 97 | + | |
| 98 | + const output = lastFrame(); | |
| 99 | + expect(output).toContain("[Image #1]"); | |
| 100 | + expect(output).not.toContain("data:image/png;base64"); | |
| 101 | + }); | |
| 102 | + | |
| 103 | + it("should display text-only message parts as regular string", () => { | |
| 104 | + const messageParts: MessagePart[] = [ | |
| 105 | + { type: "text", text: "Just text, no images here" }, | |
| 106 | + ]; | |
| 107 | + const historyItem = createTestHistoryItem(messageParts); | |
| 108 | + | |
| 109 | + const { lastFrame } = render( | |
| 110 | + <MemoizedMessage item={historyItem} index={1} />, | |
| 111 | + ); | |
| 112 | + | |
| 113 | + expect(lastFrame()).toContain("Just text, no images here"); | |
| 114 | + }); | |
| 115 | + | |
| 116 | + it("should handle unknown part types by converting to JSON", () => { | |
| 117 | + const messageParts = [ | |
| 118 | + { type: "text", text: "Start " }, | |
| 119 | + { type: "unknown", data: { some: "data" } }, | |
| 120 | + { type: "text", text: " end" }, | |
| 121 | + ] as MessagePart[]; | |
| 122 | + const historyItem = createTestHistoryItem(messageParts); | |
| 123 | + | |
| 124 | + const { lastFrame } = render( | |
| 125 | + <MemoizedMessage item={historyItem} index={1} />, | |
| 126 | + ); | |
| 127 | + | |
| 128 | + const output = lastFrame(); | |
| 129 | + // Verify whitespace preservation - trailing space after "Start" and leading space before "end" | |
| 130 | + expect(output).toContain( | |
| 131 | + 'Start {"type":"unknown","data":{"some":"data"}} end', | |
| 132 | + ); | |
| 133 | + }); | |
| 134 | + | |
| 135 | + it("should handle non-array non-string content by converting to JSON", () => { | |
| 136 | + const content = { someObject: "data" } as any; | |
| 137 | + const historyItem = createTestHistoryItem(content); | |
| 138 | + | |
| 139 | + const { lastFrame } = render( | |
| 140 | + <MemoizedMessage item={historyItem} index={1} />, | |
| 141 | + ); | |
| 142 | + | |
| 143 | + expect(lastFrame()).toContain('{"someObject":"data"}'); | |
| 144 | + }); | |
| 145 | +}); |
modified extensions/cli/src/ui/components/MemoizedMessage.tsx +37 −13
| @@ -7,6 +7,40 @@ | ||
| 7 | 7 | import { MarkdownRenderer } from "../MarkdownRenderer.js"; |
| 8 | 8 | import { ToolResultSummary } from "../ToolResultSummary.js"; |
| 9 | 9 | |
| 10 | +/** | |
| 11 | + * Formats message content for display, converting message parts array back to | |
| 12 | + * user-friendly format with placeholders like [Image #1], [Pasted Text #1], etc. | |
| 13 | + */ | |
| 14 | +function formatMessageContentForDisplay( | |
| 15 | + content: import("../../../../../core/index.js").MessageContent, | |
| 16 | +): string { | |
| 17 | + if (typeof content === "string") { | |
| 18 | + return content; | |
| 19 | + } | |
| 20 | + | |
| 21 | + if (!Array.isArray(content)) { | |
| 22 | + return JSON.stringify(content); | |
| 23 | + } | |
| 24 | + | |
| 25 | + // Convert message parts array back to display format with placeholders | |
| 26 | + let displayText = ""; | |
| 27 | + let imageCounter = 0; | |
| 28 | + | |
| 29 | + for (const part of content) { | |
| 30 | + if (part.type === "text") { | |
| 31 | + displayText += part.text; | |
| 32 | + } else if (part.type === "imageUrl") { | |
| 33 | + imageCounter++; | |
| 34 | + displayText += `[Image #${imageCounter}]`; | |
| 35 | + } else { | |
| 36 | + // Handle any other part types by converting to JSON | |
| 37 | + displayText += JSON.stringify(part); | |
| 38 | + } | |
| 39 | + } | |
| 40 | + | |
| 41 | + return displayText; | |
| 42 | +} | |
| 43 | + | |
| 10 | 44 | interface MemoizedMessageProps { |
| 11 | 45 | item: ChatHistoryItem; |
| 12 | 46 | index: number; |
| @@ -62,11 +96,7 @@ | ||
| 62 | 96 | <Text color="white">●</Text> |
| 63 | 97 | <Text> </Text> |
| 64 | 98 | <MarkdownRenderer |
| 65 | - content={ | |
| 66 | - typeof message.content === "string" | |
| 67 | - ? message.content | |
| 68 | - : JSON.stringify(message.content) | |
| 69 | - } | |
| 99 | + content={formatMessageContentForDisplay(message.content)} | |
| 70 | 100 | /> |
| 71 | 101 | </Box> |
| 72 | 102 | )} |
| @@ -132,17 +162,11 @@ | ||
| 132 | 162 | <Text> </Text> |
| 133 | 163 | {isUser ? ( |
| 134 | 164 | <Text color="gray"> |
| 135 | - {typeof message.content === "string" | |
| 136 | - ? message.content | |
| 137 | - : JSON.stringify(message.content)} | |
| 165 | + {formatMessageContentForDisplay(message.content)} | |
| 138 | 166 | </Text> |
| 139 | 167 | ) : ( |
| 140 | 168 | <MarkdownRenderer |
| 141 | - content={ | |
| 142 | - typeof message.content === "string" | |
| 143 | - ? message.content | |
| 144 | - : JSON.stringify(message.content) | |
| 145 | - } | |
| 169 | + content={formatMessageContentForDisplay(message.content)} | |
| 146 | 170 | /> |
| 147 | 171 | )} |
| 148 | 172 | {isStreaming && <Text color="gray">▋</Text>} |
modified extensions/cli/src/ui/components/ScreenContent.tsx +1 −1
| @@ -30,7 +30,7 @@ | ||
| 30 | 30 | createPolicy?: boolean, |
| 31 | 31 | stopStream?: boolean, |
| 32 | 32 | ) => void; |
| 33 | - handleUserMessage: (message: string) => void; | |
| 33 | + handleUserMessage: (message: string, imageMap?: Map<string, Buffer>) => void; | |
| 34 | 34 | isWaitingForResponse: boolean; |
| 35 | 35 | inputMode: boolean; |
| 36 | 36 | handleInterrupt: () => void; |
added extensions/cli/src/ui/hooks/useChat.compaction.ts +193 −0
| @@ -0,0 +1,193 @@ | ||
| 1 | +import type { ChatHistoryItem, Session } from "core/index.js"; | |
| 2 | + | |
| 3 | +import { compactChatHistory } from "../../compaction.js"; | |
| 4 | +import { updateSessionHistory } from "../../session.js"; | |
| 5 | +import { formatError } from "../../util/formatError.js"; | |
| 6 | +import { logger } from "../../util/logger.js"; | |
| 7 | +import { shouldAutoCompact } from "../../util/tokenizer.js"; | |
| 8 | + | |
| 9 | +interface HandleCompactCommandOptions { | |
| 10 | + chatHistory: ChatHistoryItem[]; | |
| 11 | + model: any; | |
| 12 | + llmApi: any; | |
| 13 | + setChatHistory: React.Dispatch<React.SetStateAction<ChatHistoryItem[]>>; | |
| 14 | + setCompactionIndex: React.Dispatch<React.SetStateAction<number | null>>; | |
| 15 | + currentSession: Session; | |
| 16 | + setCurrentSession: React.Dispatch<React.SetStateAction<Session>>; | |
| 17 | +} | |
| 18 | + | |
| 19 | +/** | |
| 20 | + * Handle compaction command | |
| 21 | + */ | |
| 22 | +export async function handleCompactCommand({ | |
| 23 | + chatHistory, | |
| 24 | + model, | |
| 25 | + llmApi, | |
| 26 | + setChatHistory, | |
| 27 | + setCompactionIndex, | |
| 28 | + currentSession, | |
| 29 | + setCurrentSession, | |
| 30 | +}: HandleCompactCommandOptions): Promise<void> { | |
| 31 | + // Add compacting message | |
| 32 | + setChatHistory((prev) => [ | |
| 33 | + ...prev, | |
| 34 | + { | |
| 35 | + message: { | |
| 36 | + role: "system", | |
| 37 | + content: "Compacting chat history...", | |
| 38 | + }, | |
| 39 | + contextItems: [], | |
| 40 | + }, | |
| 41 | + ]); | |
| 42 | + | |
| 43 | + try { | |
| 44 | + // Compact the chat history directly (already in unified format) | |
| 45 | + const result = await compactChatHistory(chatHistory, model, llmApi); | |
| 46 | + | |
| 47 | + // Replace chat history with compacted version | |
| 48 | + setChatHistory(result.compactedHistory); | |
| 49 | + setCompactionIndex(result.compactionIndex); | |
| 50 | + | |
| 51 | + // Save the compacted session | |
| 52 | + const updatedSession: Session = { | |
| 53 | + ...currentSession, | |
| 54 | + history: result.compactedHistory, | |
| 55 | + }; | |
| 56 | + updateSessionHistory(result.compactedHistory); | |
| 57 | + setCurrentSession(updatedSession); | |
| 58 | + | |
| 59 | + setChatHistory((prev) => [ | |
| 60 | + ...prev, | |
| 61 | + { | |
| 62 | + message: { | |
| 63 | + role: "system", | |
| 64 | + content: "Chat history compacted successfully.", | |
| 65 | + }, | |
| 66 | + contextItems: [], | |
| 67 | + }, | |
| 68 | + ]); | |
| 69 | + } catch (error) { | |
| 70 | + logger.error("Compaction failed:", error); | |
| 71 | + setChatHistory((prev) => [ | |
| 72 | + ...prev, | |
| 73 | + { | |
| 74 | + message: { | |
| 75 | + role: "system", | |
| 76 | + content: `Compaction failed: ${formatError(error)}`, | |
| 77 | + }, | |
| 78 | + contextItems: [], | |
| 79 | + }, | |
| 80 | + ]); | |
| 81 | + } | |
| 82 | +} | |
| 83 | + | |
| 84 | +interface HandleAutoCompactionOptions { | |
| 85 | + chatHistory: ChatHistoryItem[]; | |
| 86 | + model: any; | |
| 87 | + llmApi: any; | |
| 88 | + compactionIndex: number | null; | |
| 89 | + setChatHistory: React.Dispatch<React.SetStateAction<ChatHistoryItem[]>>; | |
| 90 | + setCompactionIndex: React.Dispatch<React.SetStateAction<number | null>>; | |
| 91 | +} | |
| 92 | + | |
| 93 | +/** | |
| 94 | + * Handle auto-compaction when approaching context limit - TUI wrapper | |
| 95 | + */ | |
| 96 | +export async function handleAutoCompaction({ | |
| 97 | + chatHistory, | |
| 98 | + model, | |
| 99 | + llmApi, | |
| 100 | + compactionIndex: _compactionIndex, | |
| 101 | + setChatHistory, | |
| 102 | + setCompactionIndex, | |
| 103 | +}: HandleAutoCompactionOptions): Promise<{ | |
| 104 | + currentChatHistory: ChatHistoryItem[]; | |
| 105 | + currentCompactionIndex: number | null; | |
| 106 | +}> { | |
| 107 | + try { | |
| 108 | + // Check if auto-compaction is needed | |
| 109 | + // Check if auto-compaction is needed using ChatHistoryItem directly | |
| 110 | + if (!model || !shouldAutoCompact(chatHistory, model)) { | |
| 111 | + return { | |
| 112 | + currentChatHistory: chatHistory, | |
| 113 | + currentCompactionIndex: _compactionIndex, | |
| 114 | + }; | |
| 115 | + } | |
| 116 | + | |
| 117 | + logger.info("Auto-compaction triggered for TUI mode"); | |
| 118 | + | |
| 119 | + // Add compacting message | |
| 120 | + setChatHistory((prev) => [ | |
| 121 | + ...prev, | |
| 122 | + { | |
| 123 | + message: { | |
| 124 | + role: "system", | |
| 125 | + content: "Auto-compacting chat history...", | |
| 126 | + }, | |
| 127 | + contextItems: [], | |
| 128 | + }, | |
| 129 | + ]); | |
| 130 | + | |
| 131 | + // Compact the unified history | |
| 132 | + const result = await compactChatHistory(chatHistory, model, llmApi); | |
| 133 | + | |
| 134 | + // Keep the system message and append the compaction summary | |
| 135 | + // This replaces the old messages with a summary to reduce context size | |
| 136 | + const systemMessage = chatHistory.find( | |
| 137 | + (item) => item.message.role === "system", | |
| 138 | + ); | |
| 139 | + | |
| 140 | + const compactedMessage: ChatHistoryItem = { | |
| 141 | + message: { | |
| 142 | + role: "assistant" as const, | |
| 143 | + content: result.compactionContent, | |
| 144 | + }, | |
| 145 | + contextItems: [], | |
| 146 | + conversationSummary: result.compactionContent, // Mark this as a summary | |
| 147 | + }; | |
| 148 | + | |
| 149 | + // Create new history with system message (if exists) and compaction summary | |
| 150 | + const updatedHistory: ChatHistoryItem[] = systemMessage | |
| 151 | + ? [systemMessage, compactedMessage] | |
| 152 | + : [compactedMessage]; | |
| 153 | + | |
| 154 | + setChatHistory(updatedHistory); | |
| 155 | + setCompactionIndex(updatedHistory.length - 1); | |
| 156 | + | |
| 157 | + // Add success message | |
| 158 | + setChatHistory((prev) => [ | |
| 159 | + ...prev, | |
| 160 | + { | |
| 161 | + message: { | |
| 162 | + role: "system", | |
| 163 | + content: "✓ Chat history auto-compacted successfully.", | |
| 164 | + }, | |
| 165 | + contextItems: [], | |
| 166 | + }, | |
| 167 | + ]); | |
| 168 | + | |
| 169 | + return { | |
| 170 | + currentChatHistory: updatedHistory, | |
| 171 | + currentCompactionIndex: updatedHistory.length - 1, | |
| 172 | + }; | |
| 173 | + } catch (error) { | |
| 174 | + logger.error("Auto-compaction failed:", error); | |
| 175 | + | |
| 176 | + // Add error message | |
| 177 | + setChatHistory((prev) => [ | |
| 178 | + ...prev, | |
| 179 | + { | |
| 180 | + message: { | |
| 181 | + role: "system", | |
| 182 | + content: `Auto-compaction failed: ${formatError(error)}. Continuing without compaction...`, | |
| 183 | + }, | |
| 184 | + contextItems: [], | |
| 185 | + }, | |
| 186 | + ]); | |
| 187 | + | |
| 188 | + return { | |
| 189 | + currentChatHistory: chatHistory, | |
| 190 | + currentCompactionIndex: null, | |
| 191 | + }; | |
| 192 | + } | |
| 193 | +} |
modified extensions/cli/src/ui/hooks/useChat.helpers.ts +48 −208
| @@ -1,22 +1,17 @@ | ||
| 1 | 1 | import * as path from "node:path"; |
| 2 | 2 | |
| 3 | -import type { ChatHistoryItem, Session } from "core/index.js"; | |
| 3 | +import type { ChatHistoryItem } from "core/index.js"; | |
| 4 | 4 | import { getLastNPathParts } from "core/util/uri.js"; |
| 5 | 5 | import { v4 as uuidv4 } from "uuid"; |
| 6 | 6 | |
| 7 | -import { compactChatHistory } from "../../compaction.js"; | |
| 7 | +import { logger } from "src/util/logger.js"; | |
| 8 | + | |
| 8 | 9 | import { DEFAULT_SESSION_TITLE } from "../../constants/session.js"; |
| 9 | -import { | |
| 10 | - loadSession, | |
| 11 | - updateSessionHistory, | |
| 12 | - startNewSession, | |
| 13 | -} from "../../session.js"; | |
| 10 | +import { loadSession, startNewSession } from "../../session.js"; | |
| 14 | 11 | import { posthogService } from "../../telemetry/posthogService.js"; |
| 15 | 12 | import { telemetryService } from "../../telemetry/telemetryService.js"; |
| 16 | -import { formatError } from "../../util/formatError.js"; | |
| 17 | -import { logger } from "../../util/logger.js"; | |
| 18 | -import { shouldAutoCompact } from "../../util/tokenizer.js"; | |
| 19 | 13 | |
| 14 | +import { processImagePlaceholder } from "./useChat.imageProcessing.js"; | |
| 20 | 15 | import { SlashCommandResult } from "./useChat.types.js"; |
| 21 | 16 | |
| 22 | 17 | /** |
| @@ -47,81 +42,6 @@ | ||
| 47 | 42 | onShowConfigSelector(); |
| 48 | 43 | } |
| 49 | 44 | |
| 50 | -interface HandleCompactCommandOptions { | |
| 51 | - chatHistory: ChatHistoryItem[]; | |
| 52 | - model: any; | |
| 53 | - llmApi: any; | |
| 54 | - setChatHistory: React.Dispatch<React.SetStateAction<ChatHistoryItem[]>>; | |
| 55 | - setCompactionIndex: React.Dispatch<React.SetStateAction<number | null>>; | |
| 56 | - currentSession: Session; | |
| 57 | - setCurrentSession: React.Dispatch<React.SetStateAction<Session>>; | |
| 58 | -} | |
| 59 | - | |
| 60 | -/** | |
| 61 | - * Handle compaction command | |
| 62 | - */ | |
| 63 | -export async function handleCompactCommand({ | |
| 64 | - chatHistory, | |
| 65 | - model, | |
| 66 | - llmApi, | |
| 67 | - setChatHistory, | |
| 68 | - setCompactionIndex, | |
| 69 | - currentSession, | |
| 70 | - setCurrentSession, | |
| 71 | -}: HandleCompactCommandOptions): Promise<void> { | |
| 72 | - // Add compacting message | |
| 73 | - setChatHistory((prev) => [ | |
| 74 | - ...prev, | |
| 75 | - { | |
| 76 | - message: { | |
| 77 | - role: "system", | |
| 78 | - content: "Compacting chat history...", | |
| 79 | - }, | |
| 80 | - contextItems: [], | |
| 81 | - }, | |
| 82 | - ]); | |
| 83 | - | |
| 84 | - try { | |
| 85 | - // Compact the chat history directly (already in unified format) | |
| 86 | - const result = await compactChatHistory(chatHistory, model, llmApi); | |
| 87 | - | |
| 88 | - // Replace chat history with compacted version | |
| 89 | - setChatHistory(result.compactedHistory); | |
| 90 | - setCompactionIndex(result.compactionIndex); | |
| 91 | - | |
| 92 | - // Save the compacted session | |
| 93 | - const updatedSession: Session = { | |
| 94 | - ...currentSession, | |
| 95 | - history: result.compactedHistory, | |
| 96 | - }; | |
| 97 | - updateSessionHistory(result.compactedHistory); | |
| 98 | - setCurrentSession(updatedSession); | |
| 99 | - | |
| 100 | - setChatHistory((prev) => [ | |
| 101 | - ...prev, | |
| 102 | - { | |
| 103 | - message: { | |
| 104 | - role: "system", | |
| 105 | - content: "Chat history compacted successfully.", | |
| 106 | - }, | |
| 107 | - contextItems: [], | |
| 108 | - }, | |
| 109 | - ]); | |
| 110 | - } catch (error) { | |
| 111 | - logger.error("Compaction failed:", error); | |
| 112 | - setChatHistory((prev) => [ | |
| 113 | - ...prev, | |
| 114 | - { | |
| 115 | - message: { | |
| 116 | - role: "system", | |
| 117 | - content: `Compaction failed: ${formatError(error)}`, | |
| 118 | - }, | |
| 119 | - contextItems: [], | |
| 120 | - }, | |
| 121 | - ]); | |
| 122 | - } | |
| 123 | -} | |
| 124 | - | |
| 125 | 45 | interface ProcessSlashCommandResultOptions { |
| 126 | 46 | result: SlashCommandResult; |
| 127 | 47 | chatHistory: ChatHistoryItem[]; |
| @@ -220,19 +140,13 @@ | ||
| 220 | 140 | } |
| 221 | 141 | |
| 222 | 142 | /** |
| 223 | - * Format message with attached files - returns message text and context items separately | |
| 143 | + * Format message with attached files and images - returns a complete ChatHistoryItem | |
| 224 | 144 | */ |
| 225 | -export function formatMessageWithFiles( | |
| 145 | +export async function formatMessageWithFiles( | |
| 226 | 146 | message: string, |
| 227 | 147 | attachedFiles: Array<{ path: string; content: string }>, |
| 228 | -): { | |
| 229 | - messageText: string; | |
| 230 | - contextItems: import("core/index.js").ContextItemWithId[]; | |
| 231 | -} { | |
| 232 | - if (attachedFiles.length === 0) { | |
| 233 | - return { messageText: message, contextItems: [] }; | |
| 234 | - } | |
| 235 | - | |
| 148 | + imageMap?: Map<string, Buffer>, | |
| 149 | +): Promise<import("core/index.js").ChatHistoryItem> { | |
| 236 | 150 | // Convert attached files to context items |
| 237 | 151 | const contextItems = attachedFiles.map((file) => ({ |
| 238 | 152 | id: { |
| @@ -248,8 +162,45 @@ | ||
| 248 | 162 | }, |
| 249 | 163 | })); |
| 250 | 164 | |
| 251 | - // Keep the original message text unchanged (preserving @filename references) | |
| 252 | - return { messageText: message, contextItems }; | |
| 165 | + // Process message content for images | |
| 166 | + let messageContent: import("core/index.js").MessageContent = message; | |
| 167 | + | |
| 168 | + if (imageMap && imageMap.size > 0) { | |
| 169 | + const messageParts: import("core/index.js").MessagePart[] = []; | |
| 170 | + let textContent = message; | |
| 171 | + | |
| 172 | + // Replace image placeholders with image parts | |
| 173 | + for (const [placeholder, originalImageBuffer] of imageMap.entries()) { | |
| 174 | + const result = await processImagePlaceholder( | |
| 175 | + placeholder, | |
| 176 | + originalImageBuffer, | |
| 177 | + textContent, | |
| 178 | + messageParts, | |
| 179 | + ); | |
| 180 | + textContent = result.textContent; | |
| 181 | + } | |
| 182 | + | |
| 183 | + // Add any remaining text | |
| 184 | + if (textContent) { | |
| 185 | + messageParts.push({ | |
| 186 | + type: "text", | |
| 187 | + text: textContent, | |
| 188 | + }); | |
| 189 | + } | |
| 190 | + | |
| 191 | + // Use message parts if we have images, otherwise keep as string | |
| 192 | + if (messageParts.length > 0) { | |
| 193 | + messageContent = messageParts; | |
| 194 | + } | |
| 195 | + } | |
| 196 | + | |
| 197 | + return { | |
| 198 | + message: { | |
| 199 | + role: "user", | |
| 200 | + content: messageContent, | |
| 201 | + }, | |
| 202 | + contextItems, | |
| 203 | + }; | |
| 253 | 204 | } |
| 254 | 205 | |
| 255 | 206 | /** |
| @@ -302,117 +253,6 @@ | ||
| 302 | 253 | return false; |
| 303 | 254 | } |
| 304 | 255 | |
| 305 | -interface HandleAutoCompactionOptions { | |
| 306 | - chatHistory: ChatHistoryItem[]; | |
| 307 | - model: any; | |
| 308 | - llmApi: any; | |
| 309 | - compactionIndex: number | null; | |
| 310 | - setChatHistory: React.Dispatch<React.SetStateAction<ChatHistoryItem[]>>; | |
| 311 | - setCompactionIndex: React.Dispatch<React.SetStateAction<number | null>>; | |
| 312 | -} | |
| 313 | - | |
| 314 | -/** | |
| 315 | - * Handle auto-compaction when approaching context limit - TUI wrapper | |
| 316 | - */ | |
| 317 | -export async function handleAutoCompaction({ | |
| 318 | - chatHistory, | |
| 319 | - model, | |
| 320 | - llmApi, | |
| 321 | - compactionIndex: _compactionIndex, | |
| 322 | - setChatHistory, | |
| 323 | - setCompactionIndex, | |
| 324 | -}: HandleAutoCompactionOptions): Promise<{ | |
| 325 | - currentChatHistory: ChatHistoryItem[]; | |
| 326 | - currentCompactionIndex: number | null; | |
| 327 | -}> { | |
| 328 | - try { | |
| 329 | - // Check if auto-compaction is needed | |
| 330 | - // Check if auto-compaction is needed using ChatHistoryItem directly | |
| 331 | - if (!model || !shouldAutoCompact(chatHistory, model)) { | |
| 332 | - return { | |
| 333 | - currentChatHistory: chatHistory, | |
| 334 | - currentCompactionIndex: _compactionIndex, | |
| 335 | - }; | |
| 336 | - } | |
| 337 | - | |
| 338 | - logger.info("Auto-compaction triggered for TUI mode"); | |
| 339 | - | |
| 340 | - // Add compacting message | |
| 341 | - setChatHistory((prev) => [ | |
| 342 | - ...prev, | |
| 343 | - { | |
| 344 | - message: { | |
| 345 | - role: "system", | |
| 346 | - content: "Auto-compacting chat history...", | |
| 347 | - }, | |
| 348 | - contextItems: [], | |
| 349 | - }, | |
| 350 | - ]); | |
| 351 | - | |
| 352 | - // Compact the unified history | |
| 353 | - const result = await compactChatHistory(chatHistory, model, llmApi); | |
| 354 | - | |
| 355 | - // Keep the system message and append the compaction summary | |
| 356 | - // This replaces the old messages with a summary to reduce context size | |
| 357 | - const systemMessage = chatHistory.find( | |
| 358 | - (item) => item.message.role === "system", | |
| 359 | - ); | |
| 360 | - | |
| 361 | - const compactedMessage: ChatHistoryItem = { | |
| 362 | - message: { | |
| 363 | - role: "assistant" as const, | |
| 364 | - content: result.compactionContent, | |
| 365 | - }, | |
| 366 | - contextItems: [], | |
| 367 | - conversationSummary: result.compactionContent, // Mark this as a summary | |
| 368 | - }; | |
| 369 | - | |
| 370 | - // Create new history with system message (if exists) and compaction summary | |
| 371 | - const updatedHistory: ChatHistoryItem[] = systemMessage | |
| 372 | - ? [systemMessage, compactedMessage] | |
| 373 | - : [compactedMessage]; | |
| 374 | - | |
| 375 | - setChatHistory(updatedHistory); | |
| 376 | - setCompactionIndex(updatedHistory.length - 1); | |
| 377 | - | |
| 378 | - // Add success message | |
| 379 | - setChatHistory((prev) => [ | |
| 380 | - ...prev, | |
| 381 | - { | |
| 382 | - message: { | |
| 383 | - role: "system", | |
| 384 | - content: "✓ Chat history auto-compacted successfully.", | |
| 385 | - }, | |
| 386 | - contextItems: [], | |
| 387 | - }, | |
| 388 | - ]); | |
| 389 | - | |
| 390 | - return { | |
| 391 | - currentChatHistory: updatedHistory, | |
| 392 | - currentCompactionIndex: updatedHistory.length - 1, | |
| 393 | - }; | |
| 394 | - } catch (error) { | |
| 395 | - logger.error("Auto-compaction failed:", error); | |
| 396 | - | |
| 397 | - // Add error message | |
| 398 | - setChatHistory((prev) => [ | |
| 399 | - ...prev, | |
| 400 | - { | |
| 401 | - message: { | |
| 402 | - role: "system", | |
| 403 | - content: `Auto-compaction failed: ${formatError(error)}. Continuing without compaction...`, | |
| 404 | - }, | |
| 405 | - contextItems: [], | |
| 406 | - }, | |
| 407 | - ]); | |
| 408 | - | |
| 409 | - return { | |
| 410 | - currentChatHistory: chatHistory, | |
| 411 | - currentCompactionIndex: null, | |
| 412 | - }; | |
| 413 | - } | |
| 414 | -} | |
| 415 | - | |
| 416 | 256 | /** |
| 417 | 257 | * Generate a title for the session based on the first assistant response |
| 418 | 258 | */ |
added extensions/cli/src/ui/hooks/useChat.imageProcessing.ts +189 −0
| @@ -0,0 +1,189 @@ | ||
| 1 | +import { logger } from "../../util/logger.js"; | |
| 2 | + | |
| 3 | +/** | |
| 4 | + * Dynamically import Sharp without using eval | |
| 5 | + */ | |
| 6 | +async function loadSharp(): Promise<any> { | |
| 7 | + try { | |
| 8 | + // Use Function constructor to avoid bundler issues with dynamic imports | |
| 9 | + const importSharp = new Function('return import("sharp")'); | |
| 10 | + const sharpModule = await importSharp().catch(() => null); | |
| 11 | + return sharpModule ? sharpModule.default || sharpModule : null; | |
| 12 | + } catch { | |
| 13 | + return null; | |
| 14 | + } | |
| 15 | +} | |
| 16 | + | |
| 17 | +/** | |
| 18 | + * Process image buffer to JPEG with resizing using Sharp (if available) | |
| 19 | + */ | |
| 20 | +async function processImageWithSharp( | |
| 21 | + imageBuffer: Buffer, | |
| 22 | + maxWidth = 1024, | |
| 23 | + maxHeight = 1024, | |
| 24 | +): Promise<{ buffer: Buffer; isJpeg: boolean }> { | |
| 25 | + try { | |
| 26 | + // Try to load Sharp - it's an optional dependency | |
| 27 | + const sharp = await loadSharp(); | |
| 28 | + if (!sharp) { | |
| 29 | + logger.debug("Sharp not available, using original image buffer"); | |
| 30 | + return { buffer: imageBuffer, isJpeg: false }; | |
| 31 | + } | |
| 32 | + | |
| 33 | + logger.debug("Processing image with Sharp..."); | |
| 34 | + | |
| 35 | + // Process image: convert to JPEG and resize if needed | |
| 36 | + const processedBuffer = await sharp(imageBuffer) | |
| 37 | + .resize(maxWidth, maxHeight, { | |
| 38 | + fit: "inside", | |
| 39 | + withoutEnlargement: true, | |
| 40 | + }) | |
| 41 | + .jpeg({ | |
| 42 | + quality: 85, | |
| 43 | + progressive: true, | |
| 44 | + }) | |
| 45 | + .toBuffer(); | |
| 46 | + | |
| 47 | + logger.debug( | |
| 48 | + `Image processed with Sharp: ${imageBuffer.length} bytes -> ${processedBuffer.length} bytes`, | |
| 49 | + ); | |
| 50 | + return { buffer: processedBuffer, isJpeg: true }; | |
| 51 | + } catch (error) { | |
| 52 | + logger.warn("Failed to process image with Sharp, using original:", error); | |
| 53 | + return { buffer: imageBuffer, isJpeg: false }; | |
| 54 | + } | |
| 55 | +} | |
| 56 | + | |
| 57 | +/** | |
| 58 | + * Detect image format from buffer header - simplified to reduce complexity | |
| 59 | + */ | |
| 60 | +function detectImageFormat(buffer: Buffer): string { | |
| 61 | + if (buffer.length < 4) return "image/png"; | |
| 62 | + | |
| 63 | + const signature = buffer.subarray(0, 4); | |
| 64 | + | |
| 65 | + // JPEG: FF D8 FF | |
| 66 | + if (signature[0] === 0xff && signature[1] === 0xd8 && signature[2] === 0xff) { | |
| 67 | + return "image/jpeg"; | |
| 68 | + } | |
| 69 | + | |
| 70 | + // PNG: 89 50 4E 47 | |
| 71 | + if ( | |
| 72 | + signature[0] === 0x89 && | |
| 73 | + signature[1] === 0x50 && | |
| 74 | + signature[2] === 0x4e && | |
| 75 | + signature[3] === 0x47 | |
| 76 | + ) { | |
| 77 | + return "image/png"; | |
| 78 | + } | |
| 79 | + | |
| 80 | + // GIF: 47 49 46 38 | |
| 81 | + if ( | |
| 82 | + signature[0] === 0x47 && | |
| 83 | + signature[1] === 0x49 && | |
| 84 | + signature[2] === 0x46 && | |
| 85 | + signature[3] === 0x38 | |
| 86 | + ) { | |
| 87 | + return "image/gif"; | |
| 88 | + } | |
| 89 | + | |
| 90 | + // WebP: RIFF + WEBP at offset 8 | |
| 91 | + if (signature[0] === 0x52 && signature[1] === 0x49 && buffer.length >= 12) { | |
| 92 | + const webpSig = buffer.subarray(8, 12); | |
| 93 | + if ( | |
| 94 | + webpSig[0] === 0x57 && | |
| 95 | + webpSig[1] === 0x45 && | |
| 96 | + webpSig[2] === 0x42 && | |
| 97 | + webpSig[3] === 0x50 | |
| 98 | + ) { | |
| 99 | + return "image/webp"; | |
| 100 | + } | |
| 101 | + } | |
| 102 | + | |
| 103 | + return "image/png"; // Default fallback | |
| 104 | +} | |
| 105 | + | |
| 106 | +/** | |
| 107 | + * Process a single image placeholder - extracted to reduce nesting depth | |
| 108 | + */ | |
| 109 | +export async function processImagePlaceholder( | |
| 110 | + placeholder: string, | |
| 111 | + originalImageBuffer: Buffer, | |
| 112 | + textContent: string, | |
| 113 | + messageParts: import("core/index.js").MessagePart[], | |
| 114 | +): Promise<{ textContent: string }> { | |
| 115 | + logger.debug( | |
| 116 | + `Processing image placeholder: ${placeholder}, original size: ${originalImageBuffer.length} bytes`, | |
| 117 | + ); | |
| 118 | + | |
| 119 | + try { | |
| 120 | + // Process image with Sharp (convert to JPEG and resize) | |
| 121 | + const processResult = await processImageWithSharp(originalImageBuffer); | |
| 122 | + const processedImageBuffer = processResult.buffer; | |
| 123 | + const isProcessedJpeg = processResult.isJpeg; | |
| 124 | + | |
| 125 | + // Check processed image size | |
| 126 | + const maxSize = 10 * 1024 * 1024; // 10MB limit | |
| 127 | + if (processedImageBuffer.length > maxSize) { | |
| 128 | + logger.warn( | |
| 129 | + `Processed image is still too large (${Math.round(processedImageBuffer.length / 1024 / 1024)}MB). Skipping image.`, | |
| 130 | + ); | |
| 131 | + return { | |
| 132 | + textContent: textContent.replace( | |
| 133 | + placeholder, | |
| 134 | + "[Large image skipped - reduce image size and try again]", | |
| 135 | + ), | |
| 136 | + }; | |
| 137 | + } | |
| 138 | + | |
| 139 | + // Convert processed buffer to base64 data URL asynchronously to avoid blocking | |
| 140 | + logger.debug("Converting processed image to base64..."); | |
| 141 | + const base64Image = await new Promise<string>((resolve) => { | |
| 142 | + // Use setImmediate to yield to event loop | |
| 143 | + setImmediate(() => { | |
| 144 | + const result = processedImageBuffer.toString("base64"); | |
| 145 | + resolve(result); | |
| 146 | + }); | |
| 147 | + }); | |
| 148 | + | |
| 149 | + // Use correct MIME type based on whether Sharp processing was successful | |
| 150 | + const mimeType = isProcessedJpeg | |
| 151 | + ? "image/jpeg" | |
| 152 | + : detectImageFormat(processedImageBuffer); | |
| 153 | + const dataUrl = `data:${mimeType};base64,${base64Image}`; | |
| 154 | + logger.debug( | |
| 155 | + `Image converted to base64 with MIME type ${mimeType}, dataUrl length: ${dataUrl.length}`, | |
| 156 | + ); | |
| 157 | + | |
| 158 | + // Split text around the placeholder | |
| 159 | + const parts = textContent.split(placeholder); | |
| 160 | + if (parts.length > 1) { | |
| 161 | + // Add text before placeholder | |
| 162 | + if (parts[0]) { | |
| 163 | + messageParts.push({ | |
| 164 | + type: "text", | |
| 165 | + text: parts[0], | |
| 166 | + }); | |
| 167 | + } | |
| 168 | + | |
| 169 | + // Add image part | |
| 170 | + messageParts.push({ | |
| 171 | + type: "imageUrl", | |
| 172 | + imageUrl: { url: dataUrl }, | |
| 173 | + }); | |
| 174 | + | |
| 175 | + // Continue with remaining text | |
| 176 | + return { textContent: parts.slice(1).join(placeholder) }; | |
| 177 | + } | |
| 178 | + | |
| 179 | + return { textContent }; | |
| 180 | + } catch (error) { | |
| 181 | + logger.error(`Failed to process image ${placeholder}:`, error); | |
| 182 | + return { | |
| 183 | + textContent: textContent.replace( | |
| 184 | + placeholder, | |
| 185 | + "[Image processing failed]", | |
| 186 | + ), | |
| 187 | + }; | |
| 188 | + } | |
| 189 | +} |
modified extensions/cli/src/ui/hooks/useChat.ts +116 −70
| @@ -16,9 +16,11 @@ | ||
| 16 | 16 | import { logger } from "../../util/logger.js"; |
| 17 | 17 | |
| 18 | 18 | import { |
| 19 | - formatMessageWithFiles, | |
| 20 | 19 | handleAutoCompaction, |
| 21 | 20 | handleCompactCommand, |
| 21 | +} from "./useChat.compaction.js"; | |
| 22 | +import { | |
| 23 | + formatMessageWithFiles, | |
| 22 | 24 | handleSpecialCommands, |
| 23 | 25 | initChatHistory, |
| 24 | 26 | processSlashCommandResult, |
| @@ -253,33 +255,103 @@ | ||
| 253 | 255 | } |
| 254 | 256 | }; |
| 255 | 257 | |
| 256 | - const handleUserMessage = async (message: string) => { | |
| 257 | - // Check if this is a resume request (empty message after interruption) | |
| 258 | - if (message === "" && wasInterrupted) { | |
| 259 | - // Find the index of the last user or tool message to resume from | |
| 260 | - let lastUserOrToolIndex = -1; | |
| 261 | - for (let i = chatHistory.length - 1; i >= 0; i--) { | |
| 262 | - if ( | |
| 263 | - chatHistory[i].message.role === "user" || | |
| 264 | - !!chatHistory[i].toolCallStates?.length | |
| 265 | - ) { | |
| 266 | - lastUserOrToolIndex = i; | |
| 267 | - break; | |
| 268 | - } | |
| 258 | + const handleResumeRequest = async (message: string) => { | |
| 259 | + if (message !== "" || !wasInterrupted) return false; | |
| 260 | + | |
| 261 | + // Find the index of the last user or tool message to resume from | |
| 262 | + let lastUserOrToolIndex = -1; | |
| 263 | + for (let i = chatHistory.length - 1; i >= 0; i--) { | |
| 264 | + if ( | |
| 265 | + chatHistory[i].message.role === "user" || | |
| 266 | + !!chatHistory[i].toolCallStates?.length | |
| 267 | + ) { | |
| 268 | + lastUserOrToolIndex = i; | |
| 269 | + break; | |
| 269 | 270 | } |
| 271 | + } | |
| 270 | 272 | |
| 271 | - if (lastUserOrToolIndex >= 0) { | |
| 272 | - // Truncate history to include up to and including the user/tool message | |
| 273 | - const truncatedHistory = chatHistory.slice(0, lastUserOrToolIndex + 1); | |
| 274 | - setChatHistory(truncatedHistory); | |
| 273 | + if (lastUserOrToolIndex >= 0) { | |
| 274 | + // Truncate history to include up to and including the user/tool message | |
| 275 | + const truncatedHistory = chatHistory.slice(0, lastUserOrToolIndex + 1); | |
| 276 | + setChatHistory(truncatedHistory); | |
| 275 | 277 | |
| 276 | - // Clear the interrupted state and resume | |
| 277 | - setWasInterrupted(false); | |
| 278 | + // Clear the interrupted state and resume | |
| 279 | + setWasInterrupted(false); | |
| 278 | 280 | |
| 279 | - // Re-execute streaming with the truncated history | |
| 280 | - await executeStreamingResponse(truncatedHistory, compactionIndex); | |
| 281 | - return; | |
| 282 | - } | |
| 281 | + // Re-execute streaming with the truncated history | |
| 282 | + await executeStreamingResponse(truncatedHistory, compactionIndex); | |
| 283 | + return true; | |
| 284 | + } | |
| 285 | + | |
| 286 | + return false; | |
| 287 | + }; | |
| 288 | + | |
| 289 | + const handleSlashCommandProcessing = async ( | |
| 290 | + message: string, | |
| 291 | + ): Promise<string | null> => { | |
| 292 | + // Handle slash commands (skip in remote mode except for /exit which we handled above) | |
| 293 | + if (isRemoteMode || !assistant) { | |
| 294 | + return message; | |
| 295 | + } | |
| 296 | + | |
| 297 | + const commandResult = await handleSlashCommands(message, assistant); | |
| 298 | + if (!commandResult) { | |
| 299 | + return message; | |
| 300 | + } | |
| 301 | + | |
| 302 | + if (commandResult.compact) { | |
| 303 | + await handleCompactCommand({ | |
| 304 | + chatHistory, | |
| 305 | + model, | |
| 306 | + llmApi, | |
| 307 | + setChatHistory, | |
| 308 | + setCompactionIndex, | |
| 309 | + currentSession, | |
| 310 | + setCurrentSession, | |
| 311 | + }); | |
| 312 | + return null; | |
| 313 | + } | |
| 314 | + | |
| 315 | + const newInput = processSlashCommandResult({ | |
| 316 | + result: commandResult, | |
| 317 | + chatHistory, | |
| 318 | + setChatHistory, | |
| 319 | + exit, | |
| 320 | + onShowConfigSelector, | |
| 321 | + onShowModelSelector, | |
| 322 | + onShowMCPSelector, | |
| 323 | + onShowSessionSelector, | |
| 324 | + onClear, | |
| 325 | + }); | |
| 326 | + | |
| 327 | + return newInput || null; | |
| 328 | + }; | |
| 329 | + | |
| 330 | + const convertMessageContentToString = (content: any): string => { | |
| 331 | + if (typeof content === "string") { | |
| 332 | + return content; | |
| 333 | + } | |
| 334 | + | |
| 335 | + // Convert MessagePart[] to string (extracting text, noting images) | |
| 336 | + return content | |
| 337 | + .map((part: any) => { | |
| 338 | + if (part.type === "text") { | |
| 339 | + return part.text; | |
| 340 | + } else if (part.type === "imageUrl") { | |
| 341 | + return "[Image]"; | |
| 342 | + } | |
| 343 | + return ""; | |
| 344 | + }) | |
| 345 | + .join(""); | |
| 346 | + }; | |
| 347 | + | |
| 348 | + const handleUserMessage = async ( | |
| 349 | + message: string, | |
| 350 | + imageMap?: Map<string, Buffer>, | |
| 351 | + ) => { | |
| 352 | + // Check if this is a resume request (empty message after interruption) | |
| 353 | + if (await handleResumeRequest(message)) { | |
| 354 | + return; | |
| 283 | 355 | } |
| 284 | 356 | |
| 285 | 357 | // Clear interrupted state if user types a new message |
| @@ -299,60 +371,41 @@ | ||
| 299 | 371 | |
| 300 | 372 | if (handled) return; |
| 301 | 373 | |
| 302 | - // Handle slash commands (skip in remote mode except for /exit which we handled above) | |
| 303 | - if (!isRemoteMode && assistant) { | |
| 304 | - const commandResult = await handleSlashCommands(message, assistant); | |
| 305 | - if (commandResult) { | |
| 306 | - if (commandResult.compact) { | |
| 307 | - await handleCompactCommand({ | |
| 308 | - chatHistory, | |
| 309 | - model, | |
| 310 | - llmApi, | |
| 311 | - setChatHistory, | |
| 312 | - setCompactionIndex, | |
| 313 | - currentSession, | |
| 314 | - setCurrentSession, | |
| 315 | - }); | |
| 316 | - return; | |
| 317 | - } | |
| 318 | - | |
| 319 | - const newInput = processSlashCommandResult({ | |
| 320 | - result: commandResult, | |
| 321 | - chatHistory, | |
| 322 | - setChatHistory, | |
| 323 | - exit, | |
| 324 | - onShowConfigSelector, | |
| 325 | - onShowModelSelector, | |
| 326 | - onShowMCPSelector, | |
| 327 | - onShowSessionSelector, | |
| 328 | - onClear, | |
| 329 | - }); | |
| 330 | - | |
| 331 | - if (newInput) { | |
| 332 | - message = newInput; | |
| 333 | - } else { | |
| 334 | - return; | |
| 335 | - } | |
| 336 | - } | |
| 374 | + // Handle slash commands | |
| 375 | + const processedMessage = await handleSlashCommandProcessing(message); | |
| 376 | + if (processedMessage === null) { | |
| 377 | + return; // Command was handled and no further processing needed | |
| 337 | 378 | } |
| 379 | + message = processedMessage; | |
| 338 | 380 | |
| 339 | 381 | // Track telemetry |
| 340 | 382 | trackUserMessage(message, model); |
| 341 | 383 | |
| 342 | - // Add user message to history and display | |
| 343 | - const { messageText, contextItems } = formatMessageWithFiles( | |
| 384 | + // Format message with attached files and images | |
| 385 | + logger.debug("Processing message with images", { | |
| 386 | + hasImages: !!(imageMap && imageMap.size > 0), | |
| 387 | + imageCount: imageMap?.size || 0, | |
| 388 | + }); | |
| 389 | + const newUserMessage = await formatMessageWithFiles( | |
| 344 | 390 | message, |
| 345 | 391 | attachedFiles, |
| 392 | + imageMap, | |
| 346 | 393 | ); |
| 394 | + logger.debug("Message formatted successfully"); | |
| 395 | + | |
| 347 | 396 | if (attachedFiles.length > 0) { |
| 348 | 397 | setAttachedFiles([]); |
| 349 | 398 | } |
| 350 | 399 | |
| 351 | 400 | // In remote mode, send message to server instead of processing locally |
| 352 | 401 | if (isRemoteMode && remoteUrl) { |
| 402 | + const messageContentString = convertMessageContentToString( | |
| 403 | + newUserMessage.message.content, | |
| 404 | + ); | |
| 405 | + | |
| 353 | 406 | await handleRemoteMessage({ |
| 354 | 407 | remoteUrl, |
| 355 | - messageContent: messageText, | |
| 408 | + messageContent: messageContentString, | |
| 356 | 409 | setChatHistory, |
| 357 | 410 | }); |
| 358 | 411 | return; |
| @@ -369,14 +422,7 @@ | ||
| 369 | 422 | setCompactionIndex, |
| 370 | 423 | }); |
| 371 | 424 | |
| 372 | - // NOW add user message to history with context items | |
| 373 | - const newUserMessage: ChatHistoryItem = { | |
| 374 | - message: { | |
| 375 | - role: "user", | |
| 376 | - content: messageText, | |
| 377 | - }, | |
| 378 | - contextItems, | |
| 379 | - }; | |
| 425 | + // Add the formatted user message to history | |
| 380 | 426 | const newHistory = [...currentChatHistory, newUserMessage]; |
| 381 | 427 | setChatHistory(newHistory); |
| 382 | 428 |
modified extensions/cli/src/ui/hooks/useUserInput.ts +129 −0
| @@ -1,5 +1,6 @@ | ||
| 1 | 1 | import type { PermissionMode } from "../../permissions/types.js"; |
| 2 | 2 | import { logger } from "../../util/logger.js"; |
| 3 | +import type { TextBuffer } from "../TextBuffer.js"; | |
| 3 | 4 | |
| 4 | 5 | // Helper function to handle control keys |
| 5 | 6 | interface ControlKeysOptions { |
| @@ -10,6 +11,102 @@ | ||
| 10 | 11 | showFileSearch: boolean; |
| 11 | 12 | cycleModes: () => Promise<PermissionMode>; |
| 12 | 13 | clearInput?: () => void; |
| 14 | + textBuffer?: TextBuffer; | |
| 15 | + onTextBufferUpdate?: () => void; | |
| 16 | +} | |
| 17 | + | |
| 18 | +// Helper function to check if clipboard contains an image | |
| 19 | +async function checkClipboardForImage(): Promise<boolean> { | |
| 20 | + try { | |
| 21 | + const os = await import("os"); | |
| 22 | + const { exec } = await import("child_process"); | |
| 23 | + const { promisify } = await import("util"); | |
| 24 | + const execAsync = promisify(exec); | |
| 25 | + | |
| 26 | + const platform = os.platform(); | |
| 27 | + | |
| 28 | + if (platform === "darwin") { | |
| 29 | + // macOS: Check clipboard using osascript | |
| 30 | + const { stdout } = await execAsync('osascript -e "clipboard info"'); | |
| 31 | + return ( | |
| 32 | + stdout.includes("«class PNGf»") || | |
| 33 | + stdout.includes("«class TIFF»") || | |
| 34 | + stdout.includes("picture") | |
| 35 | + ); | |
| 36 | + } else if (platform === "win32") { | |
| 37 | + // Windows: Use PowerShell to check clipboard | |
| 38 | + const { stdout } = await execAsync( | |
| 39 | + 'powershell -command "Get-Clipboard -Format Image | Measure-Object | Select-Object -ExpandProperty Count"', | |
| 40 | + ); | |
| 41 | + return parseInt(stdout.trim()) > 0; | |
| 42 | + } else if (platform === "linux") { | |
| 43 | + // Linux: Check if xclip can get image data | |
| 44 | + try { | |
| 45 | + await execAsync( | |
| 46 | + "xclip -selection clipboard -t image/png -o > /dev/null 2>&1", | |
| 47 | + ); | |
| 48 | + return true; | |
| 49 | + } catch { | |
| 50 | + return false; | |
| 51 | + } | |
| 52 | + } | |
| 53 | + | |
| 54 | + return false; | |
| 55 | + } catch (error) { | |
| 56 | + logger.debug("Error checking clipboard for image:", error); | |
| 57 | + return false; | |
| 58 | + } | |
| 59 | +} | |
| 60 | + | |
| 61 | +// Helper function to get image from clipboard | |
| 62 | +async function getClipboardImage(): Promise<Buffer | null> { | |
| 63 | + try { | |
| 64 | + const os = await import("os"); | |
| 65 | + const { exec } = await import("child_process"); | |
| 66 | + const { promisify } = await import("util"); | |
| 67 | + const execAsync = promisify(exec); | |
| 68 | + const fs = await import("fs/promises"); | |
| 69 | + const path = await import("path"); | |
| 70 | + | |
| 71 | + const platform = os.platform(); | |
| 72 | + const tempDir = os.tmpdir(); | |
| 73 | + const tempImagePath = path.join( | |
| 74 | + tempDir, | |
| 75 | + `continue-clipboard-${Date.now()}.png`, | |
| 76 | + ); | |
| 77 | + | |
| 78 | + if (platform === "darwin") { | |
| 79 | + // macOS: Save clipboard image using osascript | |
| 80 | + await execAsync( | |
| 81 | + `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'`, | |
| 82 | + ); | |
| 83 | + } else if (platform === "win32") { | |
| 84 | + // Windows: Use PowerShell to save clipboard image | |
| 85 | + await execAsync( | |
| 86 | + `powershell -command "$image = Get-Clipboard -Format Image; if ($image) { $image.Save('${tempImagePath}') }"`, | |
| 87 | + ); | |
| 88 | + } else if (platform === "linux") { | |
| 89 | + // Linux: Use xclip to save clipboard image | |
| 90 | + await execAsync( | |
| 91 | + `xclip -selection clipboard -t image/png -o > "${tempImagePath}"`, | |
| 92 | + ); | |
| 93 | + } else { | |
| 94 | + return null; | |
| 95 | + } | |
| 96 | + | |
| 97 | + // Read the temporary file | |
| 98 | + const imageBuffer = await fs.readFile(tempImagePath); | |
| 99 | + | |
| 100 | + // Clean up the temporary file | |
| 101 | + await fs.unlink(tempImagePath).catch(() => { | |
| 102 | + // Ignore cleanup errors | |
| 103 | + }); | |
| 104 | + | |
| 105 | + return imageBuffer; | |
| 106 | + } catch (error) { | |
| 107 | + logger.debug("Error reading image from clipboard:", error); | |
| 108 | + return null; | |
| 109 | + } | |
| 13 | 110 | } |
| 14 | 111 | |
| 15 | 112 | export function handleControlKeys(options: ControlKeysOptions): boolean { |
| @@ -21,6 +118,8 @@ | ||
| 21 | 118 | showFileSearch, |
| 22 | 119 | cycleModes, |
| 23 | 120 | clearInput, |
| 121 | + textBuffer, | |
| 122 | + onTextBufferUpdate, | |
| 24 | 123 | } = options; |
| 25 | 124 | |
| 26 | 125 | // Handle Ctrl+C to clear input |
| @@ -29,6 +128,36 @@ | ||
| 29 | 128 | return true; |
| 30 | 129 | } |
| 31 | 130 | |
| 131 | + // Handle Ctrl+V for clipboard paste (including images) | |
| 132 | + if (key.ctrl && input === "v" && textBuffer) { | |
| 133 | + logger.debug("Handling clipboard paste"); | |
| 134 | + // Check for images asynchronously | |
| 135 | + checkClipboardForImage() | |
| 136 | + .then(async (hasImage) => { | |
| 137 | + if (hasImage) { | |
| 138 | + const imageBuffer = await getClipboardImage(); | |
| 139 | + if (imageBuffer) { | |
| 140 | + textBuffer.addImage(imageBuffer); | |
| 141 | + // Trigger UI update | |
| 142 | + if (onTextBufferUpdate) { | |
| 143 | + onTextBufferUpdate(); | |
| 144 | + } | |
| 145 | + return; | |
| 146 | + } | |
| 147 | + } | |
| 148 | + // If no image or image reading failed, let normal text paste handling continue | |
| 149 | + // We return false here to allow the normal paste processing to happen | |
| 150 | + }) | |
| 151 | + .catch((error) => { | |
| 152 | + logger.debug("Error checking clipboard for image:", error); | |
| 153 | + // Continue with normal text paste handling | |
| 154 | + }); | |
| 155 | + | |
| 156 | + // Don't consume the event - let normal paste handling continue | |
| 157 | + // This allows text pastes to work normally when no image is present | |
| 158 | + return false; | |
| 159 | + } | |
| 160 | + | |
| 32 | 161 | // Handle Ctrl+D to exit |
| 33 | 162 | if (key.ctrl && input === "d") { |
| 34 | 163 | exit(); |