Merge pull request #7503 from continuedev/paste-images
feat: paste images in cn
This commit is contained in:
commit
608e93a385
14 changed files with 1345 additions and 334 deletions
223
extensions/cli/package-lock.json
generated
223
extensions/cli/package-lock.json
generated
|
|
@ -9,6 +9,12 @@
|
|||
"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": {
|
||||
|
|
@ -98,6 +104,14 @@
|
|||
"vitest": "^3.2.4",
|
||||
"winston": "^3.17.0",
|
||||
"yaml": "^2.8.0"
|
||||
},
|
||||
"optionalDependencies": {
|
||||
"@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"
|
||||
}
|
||||
},
|
||||
"../../core": {
|
||||
|
|
@ -1256,6 +1270,215 @@
|
|||
"url": "https://github.com/sponsors/nzakas"
|
||||
}
|
||||
},
|
||||
"node_modules/@img/sharp-darwin-arm64": {
|
||||
"version": "0.33.5",
|
||||
"resolved": "https://registry.npmjs.org/@img/sharp-darwin-arm64/-/sharp-darwin-arm64-0.33.5.tgz",
|
||||
"integrity": "sha512-UT4p+iz/2H4twwAoLCqfA9UH5pI6DggwKEGuaPy7nCVQ8ZsiY5PIcrRvD1DzuY3qYL07NtIQcWnBSY/heikIFQ==",
|
||||
"cpu": [
|
||||
"arm64"
|
||||
],
|
||||
"license": "Apache-2.0",
|
||||
"optional": true,
|
||||
"os": [
|
||||
"darwin"
|
||||
],
|
||||
"engines": {
|
||||
"node": "^18.17.0 || ^20.3.0 || >=21.0.0"
|
||||
},
|
||||
"funding": {
|
||||
"url": "https://opencollective.com/libvips"
|
||||
},
|
||||
"optionalDependencies": {
|
||||
"@img/sharp-libvips-darwin-arm64": "1.0.4"
|
||||
}
|
||||
},
|
||||
"node_modules/@img/sharp-darwin-x64": {
|
||||
"version": "0.33.5",
|
||||
"resolved": "https://registry.npmjs.org/@img/sharp-darwin-x64/-/sharp-darwin-x64-0.33.5.tgz",
|
||||
"integrity": "sha512-fyHac4jIc1ANYGRDxtiqelIbdWkIuQaI84Mv45KvGRRxSAa7o7d1ZKAOBaYbnepLC1WqxfpimdeWfvqqSGwR2Q==",
|
||||
"cpu": [
|
||||
"x64"
|
||||
],
|
||||
"license": "Apache-2.0",
|
||||
"optional": true,
|
||||
"os": [
|
||||
"darwin"
|
||||
],
|
||||
"engines": {
|
||||
"node": "^18.17.0 || ^20.3.0 || >=21.0.0"
|
||||
},
|
||||
"funding": {
|
||||
"url": "https://opencollective.com/libvips"
|
||||
},
|
||||
"optionalDependencies": {
|
||||
"@img/sharp-libvips-darwin-x64": "1.0.4"
|
||||
}
|
||||
},
|
||||
"node_modules/@img/sharp-libvips-darwin-arm64": {
|
||||
"version": "1.0.4",
|
||||
"resolved": "https://registry.npmjs.org/@img/sharp-libvips-darwin-arm64/-/sharp-libvips-darwin-arm64-1.0.4.tgz",
|
||||
"integrity": "sha512-XblONe153h0O2zuFfTAbQYAX2JhYmDHeWikp1LM9Hul9gVPjFY427k6dFEcOL72O01QxQsWi761svJ/ev9xEDg==",
|
||||
"cpu": [
|
||||
"arm64"
|
||||
],
|
||||
"license": "LGPL-3.0-or-later",
|
||||
"optional": true,
|
||||
"os": [
|
||||
"darwin"
|
||||
],
|
||||
"funding": {
|
||||
"url": "https://opencollective.com/libvips"
|
||||
}
|
||||
},
|
||||
"node_modules/@img/sharp-libvips-darwin-x64": {
|
||||
"version": "1.0.4",
|
||||
"resolved": "https://registry.npmjs.org/@img/sharp-libvips-darwin-x64/-/sharp-libvips-darwin-x64-1.0.4.tgz",
|
||||
"integrity": "sha512-xnGR8YuZYfJGmWPvmlunFaWJsb9T/AO2ykoP3Fz/0X5XV2aoYBPkX6xqCQvUTKKiLddarLaxpzNe+b1hjeWHAQ==",
|
||||
"cpu": [
|
||||
"x64"
|
||||
],
|
||||
"license": "LGPL-3.0-or-later",
|
||||
"optional": true,
|
||||
"os": [
|
||||
"darwin"
|
||||
],
|
||||
"funding": {
|
||||
"url": "https://opencollective.com/libvips"
|
||||
}
|
||||
},
|
||||
"node_modules/@img/sharp-libvips-linux-arm": {
|
||||
"version": "1.0.5",
|
||||
"resolved": "https://registry.npmjs.org/@img/sharp-libvips-linux-arm/-/sharp-libvips-linux-arm-1.0.5.tgz",
|
||||
"integrity": "sha512-gvcC4ACAOPRNATg/ov8/MnbxFDJqf/pDePbBnuBDcjsI8PssmjoKMAz4LtLaVi+OnSb5FK/yIOamqDwGmXW32g==",
|
||||
"cpu": [
|
||||
"arm"
|
||||
],
|
||||
"license": "LGPL-3.0-or-later",
|
||||
"optional": true,
|
||||
"os": [
|
||||
"linux"
|
||||
],
|
||||
"funding": {
|
||||
"url": "https://opencollective.com/libvips"
|
||||
}
|
||||
},
|
||||
"node_modules/@img/sharp-libvips-linux-arm64": {
|
||||
"version": "1.0.4",
|
||||
"resolved": "https://registry.npmjs.org/@img/sharp-libvips-linux-arm64/-/sharp-libvips-linux-arm64-1.0.4.tgz",
|
||||
"integrity": "sha512-9B+taZ8DlyyqzZQnoeIvDVR/2F4EbMepXMc/NdVbkzsJbzkUjhXv/70GQJ7tdLA4YJgNP25zukcxpX2/SueNrA==",
|
||||
"cpu": [
|
||||
"arm64"
|
||||
],
|
||||
"license": "LGPL-3.0-or-later",
|
||||
"optional": true,
|
||||
"os": [
|
||||
"linux"
|
||||
],
|
||||
"funding": {
|
||||
"url": "https://opencollective.com/libvips"
|
||||
}
|
||||
},
|
||||
"node_modules/@img/sharp-libvips-linux-x64": {
|
||||
"version": "1.0.4",
|
||||
"resolved": "https://registry.npmjs.org/@img/sharp-libvips-linux-x64/-/sharp-libvips-linux-x64-1.0.4.tgz",
|
||||
"integrity": "sha512-MmWmQ3iPFZr0Iev+BAgVMb3ZyC4KeFc3jFxnNbEPas60e1cIfevbtuyf9nDGIzOaW9PdnDciJm+wFFaTlj5xYw==",
|
||||
"cpu": [
|
||||
"x64"
|
||||
],
|
||||
"license": "LGPL-3.0-or-later",
|
||||
"optional": true,
|
||||
"os": [
|
||||
"linux"
|
||||
],
|
||||
"funding": {
|
||||
"url": "https://opencollective.com/libvips"
|
||||
}
|
||||
},
|
||||
"node_modules/@img/sharp-linux-arm": {
|
||||
"version": "0.33.5",
|
||||
"resolved": "https://registry.npmjs.org/@img/sharp-linux-arm/-/sharp-linux-arm-0.33.5.tgz",
|
||||
"integrity": "sha512-JTS1eldqZbJxjvKaAkxhZmBqPRGmxgu+qFKSInv8moZ2AmT5Yib3EQ1c6gp493HvrvV8QgdOXdyaIBrhvFhBMQ==",
|
||||
"cpu": [
|
||||
"arm"
|
||||
],
|
||||
"license": "Apache-2.0",
|
||||
"optional": true,
|
||||
"os": [
|
||||
"linux"
|
||||
],
|
||||
"engines": {
|
||||
"node": "^18.17.0 || ^20.3.0 || >=21.0.0"
|
||||
},
|
||||
"funding": {
|
||||
"url": "https://opencollective.com/libvips"
|
||||
},
|
||||
"optionalDependencies": {
|
||||
"@img/sharp-libvips-linux-arm": "1.0.5"
|
||||
}
|
||||
},
|
||||
"node_modules/@img/sharp-linux-arm64": {
|
||||
"version": "0.33.5",
|
||||
"resolved": "https://registry.npmjs.org/@img/sharp-linux-arm64/-/sharp-linux-arm64-0.33.5.tgz",
|
||||
"integrity": "sha512-JMVv+AMRyGOHtO1RFBiJy/MBsgz0x4AWrT6QoEVVTyh1E39TrCUpTRI7mx9VksGX4awWASxqCYLCV4wBZHAYxA==",
|
||||
"cpu": [
|
||||
"arm64"
|
||||
],
|
||||
"license": "Apache-2.0",
|
||||
"optional": true,
|
||||
"os": [
|
||||
"linux"
|
||||
],
|
||||
"engines": {
|
||||
"node": "^18.17.0 || ^20.3.0 || >=21.0.0"
|
||||
},
|
||||
"funding": {
|
||||
"url": "https://opencollective.com/libvips"
|
||||
},
|
||||
"optionalDependencies": {
|
||||
"@img/sharp-libvips-linux-arm64": "1.0.4"
|
||||
}
|
||||
},
|
||||
"node_modules/@img/sharp-linux-x64": {
|
||||
"version": "0.33.5",
|
||||
"resolved": "https://registry.npmjs.org/@img/sharp-linux-x64/-/sharp-linux-x64-0.33.5.tgz",
|
||||
"integrity": "sha512-opC+Ok5pRNAzuvq1AG0ar+1owsu842/Ab+4qvU879ippJBHvyY5n2mxF1izXqkPYlGuP/M556uh53jRLJmzTWA==",
|
||||
"cpu": [
|
||||
"x64"
|
||||
],
|
||||
"license": "Apache-2.0",
|
||||
"optional": true,
|
||||
"os": [
|
||||
"linux"
|
||||
],
|
||||
"engines": {
|
||||
"node": "^18.17.0 || ^20.3.0 || >=21.0.0"
|
||||
},
|
||||
"funding": {
|
||||
"url": "https://opencollective.com/libvips"
|
||||
},
|
||||
"optionalDependencies": {
|
||||
"@img/sharp-libvips-linux-x64": "1.0.4"
|
||||
}
|
||||
},
|
||||
"node_modules/@img/sharp-win32-x64": {
|
||||
"version": "0.33.5",
|
||||
"resolved": "https://registry.npmjs.org/@img/sharp-win32-x64/-/sharp-win32-x64-0.33.5.tgz",
|
||||
"integrity": "sha512-MpY/o8/8kj+EcnxwvrP4aTJSWw/aZ7JIGR4aBeZkZw5B7/Jn+tY9/VNwtcoGmdT7GfggGIU4kygOMSbYnOrAbg==",
|
||||
"cpu": [
|
||||
"x64"
|
||||
],
|
||||
"license": "Apache-2.0 AND LGPL-3.0-or-later",
|
||||
"optional": true,
|
||||
"os": [
|
||||
"win32"
|
||||
],
|
||||
"engines": {
|
||||
"node": "^18.17.0 || ^20.3.0 || >=21.0.0"
|
||||
},
|
||||
"funding": {
|
||||
"url": "https://opencollective.com/libvips"
|
||||
}
|
||||
},
|
||||
"node_modules/@isaacs/balanced-match": {
|
||||
"version": "4.0.1",
|
||||
"resolved": "https://registry.npmjs.org/@isaacs/balanced-match/-/balanced-match-4.0.1.tgz",
|
||||
|
|
|
|||
|
|
@ -59,79 +59,87 @@
|
|||
"@opentelemetry/resources": "^2.0.1",
|
||||
"@opentelemetry/sdk-node": "^0.203.0",
|
||||
"@opentelemetry/semantic-conventions": "^1.36.0",
|
||||
"@sentry/node": "^9.43.0",
|
||||
"@types/express": "^5.0.3",
|
||||
"@types/react": "^19.1.8",
|
||||
"@types/turndown": "^5.0.5",
|
||||
"@workos-inc/node": "^7.45.0",
|
||||
"chalk": "^5.4.1",
|
||||
"commander": "^14.0.0",
|
||||
"core": "file:../../core",
|
||||
"date-fns": "^4.1.0",
|
||||
"diff": "^7.0.0",
|
||||
"dotenv": "^16.5.0",
|
||||
"express": "^5.1.0",
|
||||
"glob": "^11.0.3",
|
||||
"gpt-tokenizer": "^3.0.1",
|
||||
"gradient-string": "^3.0.0",
|
||||
"ignore": "^7.0.5",
|
||||
"ignore-walk": "^7.0.0",
|
||||
"ink": "^6.1.0",
|
||||
"jszip": "^3.10.1",
|
||||
"lowlight": "^3.3.0",
|
||||
"minimatch": "^10.0.3",
|
||||
"node-fetch": "^3.3.2",
|
||||
"node-machine-id": "^1.1.12",
|
||||
"open": "^10.1.0",
|
||||
"posthog-node": "^5.6.0",
|
||||
"react": "^19.1.0",
|
||||
"readline-sync": "^1.4.10",
|
||||
"shell-quote": "^1.8.3",
|
||||
"swr": "^2.3.4",
|
||||
"turndown": "^7.2.0",
|
||||
"typescript": "^5.8.3",
|
||||
"uuid": "^9.0.1",
|
||||
"winston": "^3.17.0",
|
||||
"yaml": "^2.8.0",
|
||||
"@semantic-release/changelog": "^6.0.3",
|
||||
"@semantic-release/git": "^10.0.1",
|
||||
"@semantic-release/github": "^11.0.3",
|
||||
"@semantic-release/npm": "^12.0.2",
|
||||
"@sentry/node": "^9.43.0",
|
||||
"@testing-library/react": "^16.3.0",
|
||||
"@types/date-fns": "^2.5.3",
|
||||
"@types/diff": "^7.0.2",
|
||||
"@types/express": "^5.0.3",
|
||||
"@types/glob": "^8.1.0",
|
||||
"@types/ignore-walk": "^4.0.3",
|
||||
"@types/ink-testing-library": "^1.0.4",
|
||||
"@types/jszip": "^3.4.0",
|
||||
"@types/nock": "^10.0.3",
|
||||
"@types/react": "^19.1.8",
|
||||
"@types/readline-sync": "^1.4.8",
|
||||
"@types/shell-quote": "^1.7.5",
|
||||
"@types/supertest": "^6.0.3",
|
||||
"@types/turndown": "^5.0.5",
|
||||
"@types/uuid": "^10.0.0",
|
||||
"@typescript-eslint/eslint-plugin": "^8.39.0",
|
||||
"@typescript-eslint/parser": "^8.39.0",
|
||||
"@vitest/ui": "^3.2.4",
|
||||
"@workos-inc/node": "^7.45.0",
|
||||
"chalk": "^5.4.1",
|
||||
"commander": "^14.0.0",
|
||||
"conventional-changelog-conventionalcommits": "^9.1.0",
|
||||
"core": "file:../../core",
|
||||
"cross-env": "^7.0.3",
|
||||
"date-fns": "^4.1.0",
|
||||
"diff": "^7.0.0",
|
||||
"dotenv": "^16.5.0",
|
||||
"esbuild": "^0.25.9",
|
||||
"eslint": "^9.32.0",
|
||||
"eslint-import-resolver-typescript": "^4.4.4",
|
||||
"eslint-plugin-import": "^2.32.0",
|
||||
"eslint-plugin-unused-imports": "^4.1.4",
|
||||
"execa": "^9.6.0",
|
||||
"express": "^5.1.0",
|
||||
"glob": "^11.0.3",
|
||||
"gpt-tokenizer": "^3.0.1",
|
||||
"gradient-string": "^3.0.0",
|
||||
"happy-dom": "^18.0.1",
|
||||
"ignore": "^7.0.5",
|
||||
"ignore-walk": "^7.0.0",
|
||||
"ink": "^6.1.0",
|
||||
"ink-testing-library": "^4.0.0",
|
||||
"jsdom": "^26.1.0",
|
||||
"jszip": "^3.10.1",
|
||||
"lowlight": "^3.3.0",
|
||||
"minimatch": "^10.0.3",
|
||||
"nock": "^14.0.5",
|
||||
"node-fetch": "^3.3.2",
|
||||
"node-machine-id": "^1.1.12",
|
||||
"open": "^10.1.0",
|
||||
"posthog-node": "^5.6.0",
|
||||
"prettier": "^3.6.2",
|
||||
"react": "^19.1.0",
|
||||
"readline-sync": "^1.4.10",
|
||||
"semantic-release": "^24.2.7",
|
||||
"shell-quote": "^1.8.3",
|
||||
"supertest": "^7.1.3",
|
||||
"swr": "^2.3.4",
|
||||
"ts-node": "^10.9.2",
|
||||
"tsx": "^4.20.3",
|
||||
"vitest": "^3.2.4"
|
||||
"turndown": "^7.2.0",
|
||||
"typescript": "^5.8.3",
|
||||
"uuid": "^9.0.1",
|
||||
"vitest": "^3.2.4",
|
||||
"winston": "^3.17.0",
|
||||
"yaml": "^2.8.0"
|
||||
},
|
||||
"engine": {
|
||||
"node": ">=18"
|
||||
},
|
||||
"optionalDependencies": {
|
||||
"@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"
|
||||
}
|
||||
}
|
||||
|
|
|
|||
143
extensions/cli/src/ui/ImagePaste.test.ts
Normal file
143
extensions/cli/src/ui/ImagePaste.test.ts
Normal file
|
|
@ -0,0 +1,143 @@
|
|||
import { describe, it, expect, beforeEach } from "vitest";
|
||||
|
||||
import { TextBuffer } from "./TextBuffer.js";
|
||||
|
||||
describe("Image Pasting Functionality", () => {
|
||||
let textBuffer: TextBuffer;
|
||||
|
||||
beforeEach(() => {
|
||||
textBuffer = new TextBuffer();
|
||||
});
|
||||
|
||||
describe("TextBuffer Image Support", () => {
|
||||
it("should add image placeholder to text buffer", () => {
|
||||
const mockImageBuffer = Buffer.from("fake-image-data");
|
||||
|
||||
const placeholder = textBuffer.addImage(mockImageBuffer);
|
||||
|
||||
expect(placeholder).toBe("[Image #1]");
|
||||
expect(textBuffer.text).toBe("[Image #1]");
|
||||
expect(textBuffer.getAllImages().size).toBe(1);
|
||||
expect(textBuffer.getAllImages().get(placeholder)).toBe(mockImageBuffer);
|
||||
});
|
||||
|
||||
it("should handle multiple images with incrementing counters", () => {
|
||||
const mockImageBuffer1 = Buffer.from("fake-image-data-1");
|
||||
const mockImageBuffer2 = Buffer.from("fake-image-data-2");
|
||||
|
||||
const placeholder1 = textBuffer.addImage(mockImageBuffer1);
|
||||
const placeholder2 = textBuffer.addImage(mockImageBuffer2);
|
||||
|
||||
expect(placeholder1).toBe("[Image #1]");
|
||||
expect(placeholder2).toBe("[Image #2]");
|
||||
expect(textBuffer.text).toBe("[Image #1][Image #2]");
|
||||
expect(textBuffer.getAllImages().size).toBe(2);
|
||||
});
|
||||
|
||||
it("should clear images when buffer is cleared", () => {
|
||||
const mockImageBuffer = Buffer.from("fake-image-data");
|
||||
textBuffer.addImage(mockImageBuffer);
|
||||
|
||||
textBuffer.clear();
|
||||
|
||||
expect(textBuffer.getAllImages().size).toBe(0);
|
||||
expect(textBuffer.text).toBe("");
|
||||
});
|
||||
|
||||
it("should clear only images with clearImages()", () => {
|
||||
const mockImageBuffer = Buffer.from("fake-image-data");
|
||||
textBuffer.insertText("Some text ");
|
||||
textBuffer.addImage(mockImageBuffer);
|
||||
textBuffer.insertText(" more text");
|
||||
|
||||
textBuffer.clearImages();
|
||||
|
||||
expect(textBuffer.getAllImages().size).toBe(0);
|
||||
expect(textBuffer.text).toContain("Some text");
|
||||
expect(textBuffer.text).toContain("[Image #1]");
|
||||
expect(textBuffer.text).toContain("more text");
|
||||
});
|
||||
});
|
||||
|
||||
describe("Message Formatting with Images", () => {
|
||||
it("should format message with images correctly", async () => {
|
||||
const { formatMessageWithFiles } = await import(
|
||||
"./hooks/useChat.helpers.js"
|
||||
);
|
||||
|
||||
const message = "Here is an image: [Image #1] and some text";
|
||||
const attachedFiles: Array<{ path: string; content: string }> = [];
|
||||
const imageMap = new Map([
|
||||
["[Image #1]", Buffer.from("fake-image-data")],
|
||||
]);
|
||||
|
||||
const result = await formatMessageWithFiles(
|
||||
message,
|
||||
attachedFiles,
|
||||
imageMap,
|
||||
);
|
||||
|
||||
expect(result.message.role).toBe("user");
|
||||
expect(Array.isArray(result.message.content)).toBe(true);
|
||||
|
||||
const content = result.message.content as any[];
|
||||
expect(content).toHaveLength(3);
|
||||
expect(content[0]).toEqual({
|
||||
type: "text",
|
||||
text: "Here is an image: ",
|
||||
});
|
||||
expect(content[1]).toEqual({
|
||||
type: "imageUrl",
|
||||
imageUrl: { url: expect.stringMatching(/^data:image\/png;base64,/) },
|
||||
});
|
||||
expect(content[2]).toEqual({
|
||||
type: "text",
|
||||
text: " and some text",
|
||||
});
|
||||
});
|
||||
|
||||
it("should handle message with only text (no images)", async () => {
|
||||
const { formatMessageWithFiles } = await import(
|
||||
"./hooks/useChat.helpers.js"
|
||||
);
|
||||
|
||||
const message = "Just text, no images";
|
||||
const attachedFiles: Array<{ path: string; content: string }> = [];
|
||||
|
||||
const result = await formatMessageWithFiles(message, attachedFiles);
|
||||
|
||||
expect(result.message.role).toBe("user");
|
||||
expect(result.message.content).toBe("Just text, no images");
|
||||
});
|
||||
|
||||
it("should handle multiple images in message", async () => {
|
||||
const { formatMessageWithFiles } = await import(
|
||||
"./hooks/useChat.helpers.js"
|
||||
);
|
||||
|
||||
const message = "First [Image #1] then text [Image #2] end";
|
||||
const attachedFiles: Array<{ path: string; content: string }> = [];
|
||||
const imageMap = new Map([
|
||||
["[Image #1]", Buffer.from("fake-image-data-1")],
|
||||
["[Image #2]", Buffer.from("fake-image-data-2")],
|
||||
]);
|
||||
|
||||
const result = await formatMessageWithFiles(
|
||||
message,
|
||||
attachedFiles,
|
||||
imageMap,
|
||||
);
|
||||
|
||||
expect(Array.isArray(result.message.content)).toBe(true);
|
||||
const content = result.message.content as any[];
|
||||
|
||||
// Should have: text, image, text, image, text = 5 parts
|
||||
expect(content).toHaveLength(5);
|
||||
expect(content[0].type).toBe("text");
|
||||
expect(content[1].type).toBe("imageUrl");
|
||||
expect(content[2].type).toBe("text");
|
||||
expect(content[3].type).toBe("imageUrl");
|
||||
expect(content[4].type).toBe("text");
|
||||
});
|
||||
});
|
||||
});
|
||||
|
|
@ -2,6 +2,9 @@ import { Key } from "ink";
|
|||
|
||||
export const COLLAPSE_SIZE = 800; // Characters threshold for collapsing pasted content
|
||||
export const RAPID_INPUT_THRESHOLD = 200; // Minimum characters to trigger rapid input detection
|
||||
export const MAX_IMAGE_SIZE = 10 * 1024 * 1024; // 10MB per image
|
||||
export const MAX_IMAGE_COUNT = 20; // Maximum number of images
|
||||
export const MAX_TOTAL_IMAGE_MEMORY = 50 * 1024 * 1024; // 50MB total image memory
|
||||
|
||||
export class TextBuffer {
|
||||
private _text: string = "";
|
||||
|
|
@ -15,6 +18,8 @@ export class TextBuffer {
|
|||
private _onStateChange?: () => void;
|
||||
private _pasteMap = new Map<string, string>(); // placeholder -> original content
|
||||
private _pasteCounter: number = 0;
|
||||
private _imageMap = new Map<string, Buffer>(); // placeholder -> image buffer
|
||||
private _imageCounter: number = 0;
|
||||
|
||||
constructor(initialText: string = "") {
|
||||
this._text = initialText;
|
||||
|
|
@ -153,6 +158,8 @@ export class TextBuffer {
|
|||
this._cursor = 0;
|
||||
this._pasteMap.clear();
|
||||
this._pasteCounter = 0;
|
||||
this._imageMap.clear();
|
||||
this._imageCounter = 0;
|
||||
this._pasteBuffer = "";
|
||||
this._inPasteMode = false;
|
||||
this._rapidInputBuffer = "";
|
||||
|
|
@ -189,6 +196,52 @@ export class TextBuffer {
|
|||
this._pasteMap.clear();
|
||||
}
|
||||
|
||||
// Add image to buffer and return placeholder
|
||||
addImage(imageBuffer: Buffer): string {
|
||||
// Validate image size
|
||||
if (imageBuffer.length > MAX_IMAGE_SIZE) {
|
||||
throw new Error(
|
||||
`Image size ${(imageBuffer.length / 1024 / 1024).toFixed(1)}MB exceeds maximum allowed size of ${MAX_IMAGE_SIZE / 1024 / 1024}MB`,
|
||||
);
|
||||
}
|
||||
|
||||
// Check image count limit
|
||||
if (this._imageMap.size >= MAX_IMAGE_COUNT) {
|
||||
throw new Error(`Cannot add more than ${MAX_IMAGE_COUNT} images`);
|
||||
}
|
||||
|
||||
// Check total memory usage
|
||||
const currentMemoryUsage = Array.from(this._imageMap.values()).reduce(
|
||||
(total, buffer) => total + buffer.length,
|
||||
0,
|
||||
);
|
||||
|
||||
if (currentMemoryUsage + imageBuffer.length > MAX_TOTAL_IMAGE_MEMORY) {
|
||||
const currentUsageMB = (currentMemoryUsage / 1024 / 1024).toFixed(1);
|
||||
const maxUsageMB = MAX_TOTAL_IMAGE_MEMORY / 1024 / 1024;
|
||||
throw new Error(
|
||||
`Adding image would exceed total memory limit. Current usage: ${currentUsageMB}MB, Maximum: ${maxUsageMB}MB`,
|
||||
);
|
||||
}
|
||||
|
||||
this._imageCounter++;
|
||||
const placeholder = `[Image #${this._imageCounter}]`;
|
||||
this._imageMap.set(placeholder, imageBuffer);
|
||||
this.insertText(placeholder);
|
||||
return placeholder;
|
||||
}
|
||||
|
||||
// Get all images for message formatting
|
||||
getAllImages(): Map<string, Buffer> {
|
||||
return new Map(this._imageMap);
|
||||
}
|
||||
|
||||
// Clear images after message submission
|
||||
clearImages(): void {
|
||||
this._imageMap.clear();
|
||||
this._imageCounter = 0;
|
||||
}
|
||||
|
||||
// Test helper: forces immediate finalization without waiting for timers
|
||||
flushPendingInput(): void {
|
||||
if (this._rapidInputTimer) {
|
||||
|
|
|
|||
|
|
@ -20,7 +20,7 @@ import { SlashCommandUI } from "./SlashCommandUI.js";
|
|||
import { TextBuffer } from "./TextBuffer.js";
|
||||
|
||||
interface UserInputProps {
|
||||
onSubmit: (message: string) => void;
|
||||
onSubmit: (message: string, imageMap?: Map<string, Buffer>) => void;
|
||||
isWaitingForResponse: boolean;
|
||||
inputMode: boolean;
|
||||
onInterrupt?: () => void;
|
||||
|
|
@ -408,8 +408,11 @@ const UserInput: React.FC<UserInputProps> = ({
|
|||
return true;
|
||||
}
|
||||
|
||||
// Normal Enter behavior - submit if there's content OR if resuming after interruption
|
||||
// Normal Enter behavior - submit if there's content
|
||||
if ((textBuffer.text.trim() || wasInterrupted) && !isWaitingForResponse) {
|
||||
// Get images before expanding paste blocks
|
||||
const imageMap = textBuffer.getAllImages();
|
||||
|
||||
// Expand all paste blocks before submitting
|
||||
textBuffer.expandAllPasteBlocks();
|
||||
const submittedText = textBuffer.text.trim();
|
||||
|
|
@ -419,8 +422,9 @@ const UserInput: React.FC<UserInputProps> = ({
|
|||
inputHistory.addEntry(submittedText);
|
||||
}
|
||||
|
||||
// Send empty string when resuming, actual text otherwise
|
||||
onSubmit(submittedText);
|
||||
// Submit with images
|
||||
onSubmit(submittedText, imageMap);
|
||||
|
||||
textBuffer.clear();
|
||||
setInputText("");
|
||||
setCursorPosition(0);
|
||||
|
|
@ -481,6 +485,17 @@ const UserInput: React.FC<UserInputProps> = ({
|
|||
inputHistory.resetNavigation();
|
||||
};
|
||||
|
||||
// Handle text buffer updates for async operations like image pasting
|
||||
const handleTextBufferUpdate = () => {
|
||||
const newText = textBuffer.text;
|
||||
const newCursor = textBuffer.cursor;
|
||||
setInputText(newText);
|
||||
setCursorPosition(newCursor);
|
||||
updateSlashCommandState(newText, newCursor);
|
||||
updateFileSearchState(newText, newCursor);
|
||||
inputHistory.resetNavigation();
|
||||
};
|
||||
|
||||
useInput((input, key) => {
|
||||
// Don't handle any input when disabled
|
||||
if (disabled) {
|
||||
|
|
@ -497,6 +512,8 @@ const UserInput: React.FC<UserInputProps> = ({
|
|||
showFileSearch,
|
||||
cycleModes,
|
||||
clearInput,
|
||||
textBuffer,
|
||||
onTextBufferUpdate: handleTextBufferUpdate,
|
||||
})
|
||||
) {
|
||||
return;
|
||||
|
|
|
|||
|
|
@ -117,7 +117,7 @@ describe("TUIChat - Interruption UI (Minimal Test)", () => {
|
|||
stdin.write("\r");
|
||||
|
||||
// Should call onSubmit with empty string (for resume)
|
||||
expect(mockOnSubmit).toHaveBeenCalledWith("");
|
||||
expect(mockOnSubmit).toHaveBeenCalledWith("", expect.any(Map));
|
||||
} finally {
|
||||
unmount();
|
||||
}
|
||||
|
|
@ -145,6 +145,7 @@ describe("TUIChat - Interruption UI (Minimal Test)", () => {
|
|||
// Should call onSubmit with the typed content
|
||||
expect(mockOnSubmit).toHaveBeenCalledWith(
|
||||
"New message after interruption",
|
||||
expect.any(Map),
|
||||
);
|
||||
} finally {
|
||||
unmount();
|
||||
|
|
|
|||
|
|
@ -0,0 +1,145 @@
|
|||
import { render } from "ink-testing-library";
|
||||
import React from "react";
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import type {
|
||||
ChatHistoryItem,
|
||||
MessageContent,
|
||||
MessagePart,
|
||||
} from "../../../../../core/index.js";
|
||||
|
||||
import { MemoizedMessage } from "./MemoizedMessage.js";
|
||||
|
||||
describe("MemoizedMessage formatMessageContentForDisplay", () => {
|
||||
const createTestHistoryItem = (content: MessageContent): ChatHistoryItem => ({
|
||||
message: {
|
||||
role: "user",
|
||||
content,
|
||||
},
|
||||
contextItems: [],
|
||||
});
|
||||
|
||||
it("should display string content as-is", () => {
|
||||
const content = "Just a simple text message";
|
||||
const historyItem = createTestHistoryItem(content);
|
||||
|
||||
const { lastFrame } = render(
|
||||
<MemoizedMessage item={historyItem} index={1} />,
|
||||
);
|
||||
|
||||
expect(lastFrame()).toContain("Just a simple text message");
|
||||
});
|
||||
|
||||
it("should display message with images using placeholders", () => {
|
||||
const messageParts: MessagePart[] = [
|
||||
{ type: "text", text: "Here is an image: " },
|
||||
{ type: "imageUrl", imageUrl: { url: "data:image/png;base64,abc123" } },
|
||||
{ type: "text", text: " and some more text" },
|
||||
];
|
||||
const historyItem = createTestHistoryItem(messageParts);
|
||||
|
||||
const { lastFrame } = render(
|
||||
<MemoizedMessage item={historyItem} index={1} />,
|
||||
);
|
||||
|
||||
const output = lastFrame();
|
||||
expect(output).toContain("Here is an image: [Image #1] and some more text");
|
||||
expect(output).not.toContain("data:image/png;base64,abc123");
|
||||
expect(output).not.toContain("imageUrl");
|
||||
});
|
||||
|
||||
it("should display message with multiple images using incrementing placeholders", () => {
|
||||
const messageParts: MessagePart[] = [
|
||||
{ type: "text", text: "First " },
|
||||
{ type: "imageUrl", imageUrl: { url: "data:image/png;base64,abc123" } },
|
||||
{ type: "text", text: " then text " },
|
||||
{ type: "imageUrl", imageUrl: { url: "data:image/jpeg;base64,def456" } },
|
||||
{ type: "text", text: " end" },
|
||||
];
|
||||
const historyItem = createTestHistoryItem(messageParts);
|
||||
|
||||
const { lastFrame } = render(
|
||||
<MemoizedMessage item={historyItem} index={1} />,
|
||||
);
|
||||
|
||||
const output = lastFrame();
|
||||
expect(output).toContain("First [Image #1] then text [Image #2] end");
|
||||
expect(output).not.toContain("data:image/png;base64");
|
||||
expect(output).not.toContain("data:image/jpeg;base64");
|
||||
});
|
||||
|
||||
it("should display message with only images", () => {
|
||||
const messageParts: MessagePart[] = [
|
||||
{ type: "imageUrl", imageUrl: { url: "data:image/png;base64,abc123" } },
|
||||
{ type: "imageUrl", imageUrl: { url: "data:image/png;base64,def456" } },
|
||||
];
|
||||
const historyItem = createTestHistoryItem(messageParts);
|
||||
|
||||
const { lastFrame } = render(
|
||||
<MemoizedMessage item={historyItem} index={1} />,
|
||||
);
|
||||
|
||||
const output = lastFrame();
|
||||
expect(output).toContain("[Image #1][Image #2]");
|
||||
});
|
||||
|
||||
it("should handle empty text parts gracefully", () => {
|
||||
const messageParts: MessagePart[] = [
|
||||
{ type: "text", text: "" },
|
||||
{ type: "imageUrl", imageUrl: { url: "data:image/png;base64,abc123" } },
|
||||
{ type: "text", text: "" },
|
||||
];
|
||||
const historyItem = createTestHistoryItem(messageParts);
|
||||
|
||||
const { lastFrame } = render(
|
||||
<MemoizedMessage item={historyItem} index={1} />,
|
||||
);
|
||||
|
||||
const output = lastFrame();
|
||||
expect(output).toContain("[Image #1]");
|
||||
expect(output).not.toContain("data:image/png;base64");
|
||||
});
|
||||
|
||||
it("should display text-only message parts as regular string", () => {
|
||||
const messageParts: MessagePart[] = [
|
||||
{ type: "text", text: "Just text, no images here" },
|
||||
];
|
||||
const historyItem = createTestHistoryItem(messageParts);
|
||||
|
||||
const { lastFrame } = render(
|
||||
<MemoizedMessage item={historyItem} index={1} />,
|
||||
);
|
||||
|
||||
expect(lastFrame()).toContain("Just text, no images here");
|
||||
});
|
||||
|
||||
it("should handle unknown part types by converting to JSON", () => {
|
||||
const messageParts = [
|
||||
{ type: "text", text: "Start " },
|
||||
{ type: "unknown", data: { some: "data" } },
|
||||
{ type: "text", text: " end" },
|
||||
] as MessagePart[];
|
||||
const historyItem = createTestHistoryItem(messageParts);
|
||||
|
||||
const { lastFrame } = render(
|
||||
<MemoizedMessage item={historyItem} index={1} />,
|
||||
);
|
||||
|
||||
const output = lastFrame();
|
||||
// Verify whitespace preservation - trailing space after "Start" and leading space before "end"
|
||||
expect(output).toContain(
|
||||
'Start {"type":"unknown","data":{"some":"data"}} end',
|
||||
);
|
||||
});
|
||||
|
||||
it("should handle non-array non-string content by converting to JSON", () => {
|
||||
const content = { someObject: "data" } as any;
|
||||
const historyItem = createTestHistoryItem(content);
|
||||
|
||||
const { lastFrame } = render(
|
||||
<MemoizedMessage item={historyItem} index={1} />,
|
||||
);
|
||||
|
||||
expect(lastFrame()).toContain('{"someObject":"data"}');
|
||||
});
|
||||
});
|
||||
|
|
@ -7,6 +7,40 @@ import type { ChatHistoryItem } from "../../../../../core/index.js";
|
|||
import { MarkdownRenderer } from "../MarkdownRenderer.js";
|
||||
import { ToolResultSummary } from "../ToolResultSummary.js";
|
||||
|
||||
/**
|
||||
* Formats message content for display, converting message parts array back to
|
||||
* user-friendly format with placeholders like [Image #1], [Pasted Text #1], etc.
|
||||
*/
|
||||
function formatMessageContentForDisplay(
|
||||
content: import("../../../../../core/index.js").MessageContent,
|
||||
): string {
|
||||
if (typeof content === "string") {
|
||||
return content;
|
||||
}
|
||||
|
||||
if (!Array.isArray(content)) {
|
||||
return JSON.stringify(content);
|
||||
}
|
||||
|
||||
// Convert message parts array back to display format with placeholders
|
||||
let displayText = "";
|
||||
let imageCounter = 0;
|
||||
|
||||
for (const part of content) {
|
||||
if (part.type === "text") {
|
||||
displayText += part.text;
|
||||
} else if (part.type === "imageUrl") {
|
||||
imageCounter++;
|
||||
displayText += `[Image #${imageCounter}]`;
|
||||
} else {
|
||||
// Handle any other part types by converting to JSON
|
||||
displayText += JSON.stringify(part);
|
||||
}
|
||||
}
|
||||
|
||||
return displayText;
|
||||
}
|
||||
|
||||
interface MemoizedMessageProps {
|
||||
item: ChatHistoryItem;
|
||||
index: number;
|
||||
|
|
@ -62,11 +96,7 @@ export const MemoizedMessage = memo<MemoizedMessageProps>(
|
|||
<Text color="white">●</Text>
|
||||
<Text> </Text>
|
||||
<MarkdownRenderer
|
||||
content={
|
||||
typeof message.content === "string"
|
||||
? message.content
|
||||
: JSON.stringify(message.content)
|
||||
}
|
||||
content={formatMessageContentForDisplay(message.content)}
|
||||
/>
|
||||
</Box>
|
||||
)}
|
||||
|
|
@ -132,17 +162,11 @@ export const MemoizedMessage = memo<MemoizedMessageProps>(
|
|||
<Text> </Text>
|
||||
{isUser ? (
|
||||
<Text color="gray">
|
||||
{typeof message.content === "string"
|
||||
? message.content
|
||||
: JSON.stringify(message.content)}
|
||||
{formatMessageContentForDisplay(message.content)}
|
||||
</Text>
|
||||
) : (
|
||||
<MarkdownRenderer
|
||||
content={
|
||||
typeof message.content === "string"
|
||||
? message.content
|
||||
: JSON.stringify(message.content)
|
||||
}
|
||||
content={formatMessageContentForDisplay(message.content)}
|
||||
/>
|
||||
)}
|
||||
{isStreaming && <Text color="gray">▋</Text>}
|
||||
|
|
|
|||
|
|
@ -30,7 +30,7 @@ interface ScreenContentProps {
|
|||
createPolicy?: boolean,
|
||||
stopStream?: boolean,
|
||||
) => void;
|
||||
handleUserMessage: (message: string) => void;
|
||||
handleUserMessage: (message: string, imageMap?: Map<string, Buffer>) => void;
|
||||
isWaitingForResponse: boolean;
|
||||
inputMode: boolean;
|
||||
handleInterrupt: () => void;
|
||||
|
|
|
|||
193
extensions/cli/src/ui/hooks/useChat.compaction.ts
Normal file
193
extensions/cli/src/ui/hooks/useChat.compaction.ts
Normal file
|
|
@ -0,0 +1,193 @@
|
|||
import type { ChatHistoryItem, Session } from "core/index.js";
|
||||
|
||||
import { compactChatHistory } from "../../compaction.js";
|
||||
import { updateSessionHistory } from "../../session.js";
|
||||
import { formatError } from "../../util/formatError.js";
|
||||
import { logger } from "../../util/logger.js";
|
||||
import { shouldAutoCompact } from "../../util/tokenizer.js";
|
||||
|
||||
interface HandleCompactCommandOptions {
|
||||
chatHistory: ChatHistoryItem[];
|
||||
model: any;
|
||||
llmApi: any;
|
||||
setChatHistory: React.Dispatch<React.SetStateAction<ChatHistoryItem[]>>;
|
||||
setCompactionIndex: React.Dispatch<React.SetStateAction<number | null>>;
|
||||
currentSession: Session;
|
||||
setCurrentSession: React.Dispatch<React.SetStateAction<Session>>;
|
||||
}
|
||||
|
||||
/**
|
||||
* Handle compaction command
|
||||
*/
|
||||
export async function handleCompactCommand({
|
||||
chatHistory,
|
||||
model,
|
||||
llmApi,
|
||||
setChatHistory,
|
||||
setCompactionIndex,
|
||||
currentSession,
|
||||
setCurrentSession,
|
||||
}: HandleCompactCommandOptions): Promise<void> {
|
||||
// Add compacting message
|
||||
setChatHistory((prev) => [
|
||||
...prev,
|
||||
{
|
||||
message: {
|
||||
role: "system",
|
||||
content: "Compacting chat history...",
|
||||
},
|
||||
contextItems: [],
|
||||
},
|
||||
]);
|
||||
|
||||
try {
|
||||
// Compact the chat history directly (already in unified format)
|
||||
const result = await compactChatHistory(chatHistory, model, llmApi);
|
||||
|
||||
// Replace chat history with compacted version
|
||||
setChatHistory(result.compactedHistory);
|
||||
setCompactionIndex(result.compactionIndex);
|
||||
|
||||
// Save the compacted session
|
||||
const updatedSession: Session = {
|
||||
...currentSession,
|
||||
history: result.compactedHistory,
|
||||
};
|
||||
updateSessionHistory(result.compactedHistory);
|
||||
setCurrentSession(updatedSession);
|
||||
|
||||
setChatHistory((prev) => [
|
||||
...prev,
|
||||
{
|
||||
message: {
|
||||
role: "system",
|
||||
content: "Chat history compacted successfully.",
|
||||
},
|
||||
contextItems: [],
|
||||
},
|
||||
]);
|
||||
} catch (error) {
|
||||
logger.error("Compaction failed:", error);
|
||||
setChatHistory((prev) => [
|
||||
...prev,
|
||||
{
|
||||
message: {
|
||||
role: "system",
|
||||
content: `Compaction failed: ${formatError(error)}`,
|
||||
},
|
||||
contextItems: [],
|
||||
},
|
||||
]);
|
||||
}
|
||||
}
|
||||
|
||||
interface HandleAutoCompactionOptions {
|
||||
chatHistory: ChatHistoryItem[];
|
||||
model: any;
|
||||
llmApi: any;
|
||||
compactionIndex: number | null;
|
||||
setChatHistory: React.Dispatch<React.SetStateAction<ChatHistoryItem[]>>;
|
||||
setCompactionIndex: React.Dispatch<React.SetStateAction<number | null>>;
|
||||
}
|
||||
|
||||
/**
|
||||
* Handle auto-compaction when approaching context limit - TUI wrapper
|
||||
*/
|
||||
export async function handleAutoCompaction({
|
||||
chatHistory,
|
||||
model,
|
||||
llmApi,
|
||||
compactionIndex: _compactionIndex,
|
||||
setChatHistory,
|
||||
setCompactionIndex,
|
||||
}: HandleAutoCompactionOptions): Promise<{
|
||||
currentChatHistory: ChatHistoryItem[];
|
||||
currentCompactionIndex: number | null;
|
||||
}> {
|
||||
try {
|
||||
// Check if auto-compaction is needed
|
||||
// Check if auto-compaction is needed using ChatHistoryItem directly
|
||||
if (!model || !shouldAutoCompact(chatHistory, model)) {
|
||||
return {
|
||||
currentChatHistory: chatHistory,
|
||||
currentCompactionIndex: _compactionIndex,
|
||||
};
|
||||
}
|
||||
|
||||
logger.info("Auto-compaction triggered for TUI mode");
|
||||
|
||||
// Add compacting message
|
||||
setChatHistory((prev) => [
|
||||
...prev,
|
||||
{
|
||||
message: {
|
||||
role: "system",
|
||||
content: "Auto-compacting chat history...",
|
||||
},
|
||||
contextItems: [],
|
||||
},
|
||||
]);
|
||||
|
||||
// Compact the unified history
|
||||
const result = await compactChatHistory(chatHistory, model, llmApi);
|
||||
|
||||
// Keep the system message and append the compaction summary
|
||||
// This replaces the old messages with a summary to reduce context size
|
||||
const systemMessage = chatHistory.find(
|
||||
(item) => item.message.role === "system",
|
||||
);
|
||||
|
||||
const compactedMessage: ChatHistoryItem = {
|
||||
message: {
|
||||
role: "assistant" as const,
|
||||
content: result.compactionContent,
|
||||
},
|
||||
contextItems: [],
|
||||
conversationSummary: result.compactionContent, // Mark this as a summary
|
||||
};
|
||||
|
||||
// Create new history with system message (if exists) and compaction summary
|
||||
const updatedHistory: ChatHistoryItem[] = systemMessage
|
||||
? [systemMessage, compactedMessage]
|
||||
: [compactedMessage];
|
||||
|
||||
setChatHistory(updatedHistory);
|
||||
setCompactionIndex(updatedHistory.length - 1);
|
||||
|
||||
// Add success message
|
||||
setChatHistory((prev) => [
|
||||
...prev,
|
||||
{
|
||||
message: {
|
||||
role: "system",
|
||||
content: "✓ Chat history auto-compacted successfully.",
|
||||
},
|
||||
contextItems: [],
|
||||
},
|
||||
]);
|
||||
|
||||
return {
|
||||
currentChatHistory: updatedHistory,
|
||||
currentCompactionIndex: updatedHistory.length - 1,
|
||||
};
|
||||
} catch (error) {
|
||||
logger.error("Auto-compaction failed:", error);
|
||||
|
||||
// Add error message
|
||||
setChatHistory((prev) => [
|
||||
...prev,
|
||||
{
|
||||
message: {
|
||||
role: "system",
|
||||
content: `Auto-compaction failed: ${formatError(error)}. Continuing without compaction...`,
|
||||
},
|
||||
contextItems: [],
|
||||
},
|
||||
]);
|
||||
|
||||
return {
|
||||
currentChatHistory: chatHistory,
|
||||
currentCompactionIndex: null,
|
||||
};
|
||||
}
|
||||
}
|
||||
|
|
@ -1,22 +1,17 @@
|
|||
import * as path from "node:path";
|
||||
|
||||
import type { ChatHistoryItem, Session } from "core/index.js";
|
||||
import type { ChatHistoryItem } from "core/index.js";
|
||||
import { getLastNPathParts } from "core/util/uri.js";
|
||||
import { v4 as uuidv4 } from "uuid";
|
||||
|
||||
import { compactChatHistory } from "../../compaction.js";
|
||||
import { logger } from "src/util/logger.js";
|
||||
|
||||
import { DEFAULT_SESSION_TITLE } from "../../constants/session.js";
|
||||
import {
|
||||
loadSession,
|
||||
updateSessionHistory,
|
||||
startNewSession,
|
||||
} from "../../session.js";
|
||||
import { loadSession, startNewSession } from "../../session.js";
|
||||
import { posthogService } from "../../telemetry/posthogService.js";
|
||||
import { telemetryService } from "../../telemetry/telemetryService.js";
|
||||
import { formatError } from "../../util/formatError.js";
|
||||
import { logger } from "../../util/logger.js";
|
||||
import { shouldAutoCompact } from "../../util/tokenizer.js";
|
||||
|
||||
import { processImagePlaceholder } from "./useChat.imageProcessing.js";
|
||||
import { SlashCommandResult } from "./useChat.types.js";
|
||||
|
||||
/**
|
||||
|
|
@ -47,81 +42,6 @@ export function handleConfigCommand(onShowConfigSelector: () => void): void {
|
|||
onShowConfigSelector();
|
||||
}
|
||||
|
||||
interface HandleCompactCommandOptions {
|
||||
chatHistory: ChatHistoryItem[];
|
||||
model: any;
|
||||
llmApi: any;
|
||||
setChatHistory: React.Dispatch<React.SetStateAction<ChatHistoryItem[]>>;
|
||||
setCompactionIndex: React.Dispatch<React.SetStateAction<number | null>>;
|
||||
currentSession: Session;
|
||||
setCurrentSession: React.Dispatch<React.SetStateAction<Session>>;
|
||||
}
|
||||
|
||||
/**
|
||||
* Handle compaction command
|
||||
*/
|
||||
export async function handleCompactCommand({
|
||||
chatHistory,
|
||||
model,
|
||||
llmApi,
|
||||
setChatHistory,
|
||||
setCompactionIndex,
|
||||
currentSession,
|
||||
setCurrentSession,
|
||||
}: HandleCompactCommandOptions): Promise<void> {
|
||||
// Add compacting message
|
||||
setChatHistory((prev) => [
|
||||
...prev,
|
||||
{
|
||||
message: {
|
||||
role: "system",
|
||||
content: "Compacting chat history...",
|
||||
},
|
||||
contextItems: [],
|
||||
},
|
||||
]);
|
||||
|
||||
try {
|
||||
// Compact the chat history directly (already in unified format)
|
||||
const result = await compactChatHistory(chatHistory, model, llmApi);
|
||||
|
||||
// Replace chat history with compacted version
|
||||
setChatHistory(result.compactedHistory);
|
||||
setCompactionIndex(result.compactionIndex);
|
||||
|
||||
// Save the compacted session
|
||||
const updatedSession: Session = {
|
||||
...currentSession,
|
||||
history: result.compactedHistory,
|
||||
};
|
||||
updateSessionHistory(result.compactedHistory);
|
||||
setCurrentSession(updatedSession);
|
||||
|
||||
setChatHistory((prev) => [
|
||||
...prev,
|
||||
{
|
||||
message: {
|
||||
role: "system",
|
||||
content: "Chat history compacted successfully.",
|
||||
},
|
||||
contextItems: [],
|
||||
},
|
||||
]);
|
||||
} catch (error) {
|
||||
logger.error("Compaction failed:", error);
|
||||
setChatHistory((prev) => [
|
||||
...prev,
|
||||
{
|
||||
message: {
|
||||
role: "system",
|
||||
content: `Compaction failed: ${formatError(error)}`,
|
||||
},
|
||||
contextItems: [],
|
||||
},
|
||||
]);
|
||||
}
|
||||
}
|
||||
|
||||
interface ProcessSlashCommandResultOptions {
|
||||
result: SlashCommandResult;
|
||||
chatHistory: ChatHistoryItem[];
|
||||
|
|
@ -220,19 +140,13 @@ export function processSlashCommandResult({
|
|||
}
|
||||
|
||||
/**
|
||||
* Format message with attached files - returns message text and context items separately
|
||||
* Format message with attached files and images - returns a complete ChatHistoryItem
|
||||
*/
|
||||
export function formatMessageWithFiles(
|
||||
export async function formatMessageWithFiles(
|
||||
message: string,
|
||||
attachedFiles: Array<{ path: string; content: string }>,
|
||||
): {
|
||||
messageText: string;
|
||||
contextItems: import("core/index.js").ContextItemWithId[];
|
||||
} {
|
||||
if (attachedFiles.length === 0) {
|
||||
return { messageText: message, contextItems: [] };
|
||||
}
|
||||
|
||||
imageMap?: Map<string, Buffer>,
|
||||
): Promise<import("core/index.js").ChatHistoryItem> {
|
||||
// Convert attached files to context items
|
||||
const contextItems = attachedFiles.map((file) => ({
|
||||
id: {
|
||||
|
|
@ -248,8 +162,45 @@ export function formatMessageWithFiles(
|
|||
},
|
||||
}));
|
||||
|
||||
// Keep the original message text unchanged (preserving @filename references)
|
||||
return { messageText: message, contextItems };
|
||||
// Process message content for images
|
||||
let messageContent: import("core/index.js").MessageContent = message;
|
||||
|
||||
if (imageMap && imageMap.size > 0) {
|
||||
const messageParts: import("core/index.js").MessagePart[] = [];
|
||||
let textContent = message;
|
||||
|
||||
// Replace image placeholders with image parts
|
||||
for (const [placeholder, originalImageBuffer] of imageMap.entries()) {
|
||||
const result = await processImagePlaceholder(
|
||||
placeholder,
|
||||
originalImageBuffer,
|
||||
textContent,
|
||||
messageParts,
|
||||
);
|
||||
textContent = result.textContent;
|
||||
}
|
||||
|
||||
// Add any remaining text
|
||||
if (textContent) {
|
||||
messageParts.push({
|
||||
type: "text",
|
||||
text: textContent,
|
||||
});
|
||||
}
|
||||
|
||||
// Use message parts if we have images, otherwise keep as string
|
||||
if (messageParts.length > 0) {
|
||||
messageContent = messageParts;
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
message: {
|
||||
role: "user",
|
||||
content: messageContent,
|
||||
},
|
||||
contextItems,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
|
|
@ -302,117 +253,6 @@ export async function handleSpecialCommands({
|
|||
return false;
|
||||
}
|
||||
|
||||
interface HandleAutoCompactionOptions {
|
||||
chatHistory: ChatHistoryItem[];
|
||||
model: any;
|
||||
llmApi: any;
|
||||
compactionIndex: number | null;
|
||||
setChatHistory: React.Dispatch<React.SetStateAction<ChatHistoryItem[]>>;
|
||||
setCompactionIndex: React.Dispatch<React.SetStateAction<number | null>>;
|
||||
}
|
||||
|
||||
/**
|
||||
* Handle auto-compaction when approaching context limit - TUI wrapper
|
||||
*/
|
||||
export async function handleAutoCompaction({
|
||||
chatHistory,
|
||||
model,
|
||||
llmApi,
|
||||
compactionIndex: _compactionIndex,
|
||||
setChatHistory,
|
||||
setCompactionIndex,
|
||||
}: HandleAutoCompactionOptions): Promise<{
|
||||
currentChatHistory: ChatHistoryItem[];
|
||||
currentCompactionIndex: number | null;
|
||||
}> {
|
||||
try {
|
||||
// Check if auto-compaction is needed
|
||||
// Check if auto-compaction is needed using ChatHistoryItem directly
|
||||
if (!model || !shouldAutoCompact(chatHistory, model)) {
|
||||
return {
|
||||
currentChatHistory: chatHistory,
|
||||
currentCompactionIndex: _compactionIndex,
|
||||
};
|
||||
}
|
||||
|
||||
logger.info("Auto-compaction triggered for TUI mode");
|
||||
|
||||
// Add compacting message
|
||||
setChatHistory((prev) => [
|
||||
...prev,
|
||||
{
|
||||
message: {
|
||||
role: "system",
|
||||
content: "Auto-compacting chat history...",
|
||||
},
|
||||
contextItems: [],
|
||||
},
|
||||
]);
|
||||
|
||||
// Compact the unified history
|
||||
const result = await compactChatHistory(chatHistory, model, llmApi);
|
||||
|
||||
// Keep the system message and append the compaction summary
|
||||
// This replaces the old messages with a summary to reduce context size
|
||||
const systemMessage = chatHistory.find(
|
||||
(item) => item.message.role === "system",
|
||||
);
|
||||
|
||||
const compactedMessage: ChatHistoryItem = {
|
||||
message: {
|
||||
role: "assistant" as const,
|
||||
content: result.compactionContent,
|
||||
},
|
||||
contextItems: [],
|
||||
conversationSummary: result.compactionContent, // Mark this as a summary
|
||||
};
|
||||
|
||||
// Create new history with system message (if exists) and compaction summary
|
||||
const updatedHistory: ChatHistoryItem[] = systemMessage
|
||||
? [systemMessage, compactedMessage]
|
||||
: [compactedMessage];
|
||||
|
||||
setChatHistory(updatedHistory);
|
||||
setCompactionIndex(updatedHistory.length - 1);
|
||||
|
||||
// Add success message
|
||||
setChatHistory((prev) => [
|
||||
...prev,
|
||||
{
|
||||
message: {
|
||||
role: "system",
|
||||
content: "✓ Chat history auto-compacted successfully.",
|
||||
},
|
||||
contextItems: [],
|
||||
},
|
||||
]);
|
||||
|
||||
return {
|
||||
currentChatHistory: updatedHistory,
|
||||
currentCompactionIndex: updatedHistory.length - 1,
|
||||
};
|
||||
} catch (error) {
|
||||
logger.error("Auto-compaction failed:", error);
|
||||
|
||||
// Add error message
|
||||
setChatHistory((prev) => [
|
||||
...prev,
|
||||
{
|
||||
message: {
|
||||
role: "system",
|
||||
content: `Auto-compaction failed: ${formatError(error)}. Continuing without compaction...`,
|
||||
},
|
||||
contextItems: [],
|
||||
},
|
||||
]);
|
||||
|
||||
return {
|
||||
currentChatHistory: chatHistory,
|
||||
currentCompactionIndex: null,
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Generate a title for the session based on the first assistant response
|
||||
*/
|
||||
|
|
|
|||
189
extensions/cli/src/ui/hooks/useChat.imageProcessing.ts
Normal file
189
extensions/cli/src/ui/hooks/useChat.imageProcessing.ts
Normal file
|
|
@ -0,0 +1,189 @@
|
|||
import { logger } from "../../util/logger.js";
|
||||
|
||||
/**
|
||||
* Dynamically import Sharp without using eval
|
||||
*/
|
||||
async function loadSharp(): Promise<any> {
|
||||
try {
|
||||
// Use Function constructor to avoid bundler issues with dynamic imports
|
||||
const importSharp = new Function('return import("sharp")');
|
||||
const sharpModule = await importSharp().catch(() => null);
|
||||
return sharpModule ? sharpModule.default || sharpModule : null;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Process image buffer to JPEG with resizing using Sharp (if available)
|
||||
*/
|
||||
async function processImageWithSharp(
|
||||
imageBuffer: Buffer,
|
||||
maxWidth = 1024,
|
||||
maxHeight = 1024,
|
||||
): Promise<{ buffer: Buffer; isJpeg: boolean }> {
|
||||
try {
|
||||
// Try to load Sharp - it's an optional dependency
|
||||
const sharp = await loadSharp();
|
||||
if (!sharp) {
|
||||
logger.debug("Sharp not available, using original image buffer");
|
||||
return { buffer: imageBuffer, isJpeg: false };
|
||||
}
|
||||
|
||||
logger.debug("Processing image with Sharp...");
|
||||
|
||||
// Process image: convert to JPEG and resize if needed
|
||||
const processedBuffer = await sharp(imageBuffer)
|
||||
.resize(maxWidth, maxHeight, {
|
||||
fit: "inside",
|
||||
withoutEnlargement: true,
|
||||
})
|
||||
.jpeg({
|
||||
quality: 85,
|
||||
progressive: true,
|
||||
})
|
||||
.toBuffer();
|
||||
|
||||
logger.debug(
|
||||
`Image processed with Sharp: ${imageBuffer.length} bytes -> ${processedBuffer.length} bytes`,
|
||||
);
|
||||
return { buffer: processedBuffer, isJpeg: true };
|
||||
} catch (error) {
|
||||
logger.warn("Failed to process image with Sharp, using original:", error);
|
||||
return { buffer: imageBuffer, isJpeg: false };
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Detect image format from buffer header - simplified to reduce complexity
|
||||
*/
|
||||
function detectImageFormat(buffer: Buffer): string {
|
||||
if (buffer.length < 4) return "image/png";
|
||||
|
||||
const signature = buffer.subarray(0, 4);
|
||||
|
||||
// JPEG: FF D8 FF
|
||||
if (signature[0] === 0xff && signature[1] === 0xd8 && signature[2] === 0xff) {
|
||||
return "image/jpeg";
|
||||
}
|
||||
|
||||
// PNG: 89 50 4E 47
|
||||
if (
|
||||
signature[0] === 0x89 &&
|
||||
signature[1] === 0x50 &&
|
||||
signature[2] === 0x4e &&
|
||||
signature[3] === 0x47
|
||||
) {
|
||||
return "image/png";
|
||||
}
|
||||
|
||||
// GIF: 47 49 46 38
|
||||
if (
|
||||
signature[0] === 0x47 &&
|
||||
signature[1] === 0x49 &&
|
||||
signature[2] === 0x46 &&
|
||||
signature[3] === 0x38
|
||||
) {
|
||||
return "image/gif";
|
||||
}
|
||||
|
||||
// WebP: RIFF + WEBP at offset 8
|
||||
if (signature[0] === 0x52 && signature[1] === 0x49 && buffer.length >= 12) {
|
||||
const webpSig = buffer.subarray(8, 12);
|
||||
if (
|
||||
webpSig[0] === 0x57 &&
|
||||
webpSig[1] === 0x45 &&
|
||||
webpSig[2] === 0x42 &&
|
||||
webpSig[3] === 0x50
|
||||
) {
|
||||
return "image/webp";
|
||||
}
|
||||
}
|
||||
|
||||
return "image/png"; // Default fallback
|
||||
}
|
||||
|
||||
/**
|
||||
* Process a single image placeholder - extracted to reduce nesting depth
|
||||
*/
|
||||
export async function processImagePlaceholder(
|
||||
placeholder: string,
|
||||
originalImageBuffer: Buffer,
|
||||
textContent: string,
|
||||
messageParts: import("core/index.js").MessagePart[],
|
||||
): Promise<{ textContent: string }> {
|
||||
logger.debug(
|
||||
`Processing image placeholder: ${placeholder}, original size: ${originalImageBuffer.length} bytes`,
|
||||
);
|
||||
|
||||
try {
|
||||
// Process image with Sharp (convert to JPEG and resize)
|
||||
const processResult = await processImageWithSharp(originalImageBuffer);
|
||||
const processedImageBuffer = processResult.buffer;
|
||||
const isProcessedJpeg = processResult.isJpeg;
|
||||
|
||||
// Check processed image size
|
||||
const maxSize = 10 * 1024 * 1024; // 10MB limit
|
||||
if (processedImageBuffer.length > maxSize) {
|
||||
logger.warn(
|
||||
`Processed image is still too large (${Math.round(processedImageBuffer.length / 1024 / 1024)}MB). Skipping image.`,
|
||||
);
|
||||
return {
|
||||
textContent: textContent.replace(
|
||||
placeholder,
|
||||
"[Large image skipped - reduce image size and try again]",
|
||||
),
|
||||
};
|
||||
}
|
||||
|
||||
// Convert processed buffer to base64 data URL asynchronously to avoid blocking
|
||||
logger.debug("Converting processed image to base64...");
|
||||
const base64Image = await new Promise<string>((resolve) => {
|
||||
// Use setImmediate to yield to event loop
|
||||
setImmediate(() => {
|
||||
const result = processedImageBuffer.toString("base64");
|
||||
resolve(result);
|
||||
});
|
||||
});
|
||||
|
||||
// Use correct MIME type based on whether Sharp processing was successful
|
||||
const mimeType = isProcessedJpeg
|
||||
? "image/jpeg"
|
||||
: detectImageFormat(processedImageBuffer);
|
||||
const dataUrl = `data:${mimeType};base64,${base64Image}`;
|
||||
logger.debug(
|
||||
`Image converted to base64 with MIME type ${mimeType}, dataUrl length: ${dataUrl.length}`,
|
||||
);
|
||||
|
||||
// Split text around the placeholder
|
||||
const parts = textContent.split(placeholder);
|
||||
if (parts.length > 1) {
|
||||
// Add text before placeholder
|
||||
if (parts[0]) {
|
||||
messageParts.push({
|
||||
type: "text",
|
||||
text: parts[0],
|
||||
});
|
||||
}
|
||||
|
||||
// Add image part
|
||||
messageParts.push({
|
||||
type: "imageUrl",
|
||||
imageUrl: { url: dataUrl },
|
||||
});
|
||||
|
||||
// Continue with remaining text
|
||||
return { textContent: parts.slice(1).join(placeholder) };
|
||||
}
|
||||
|
||||
return { textContent };
|
||||
} catch (error) {
|
||||
logger.error(`Failed to process image ${placeholder}:`, error);
|
||||
return {
|
||||
textContent: textContent.replace(
|
||||
placeholder,
|
||||
"[Image processing failed]",
|
||||
),
|
||||
};
|
||||
}
|
||||
}
|
||||
|
|
@ -16,9 +16,11 @@ import { formatError } from "../../util/formatError.js";
|
|||
import { logger } from "../../util/logger.js";
|
||||
|
||||
import {
|
||||
formatMessageWithFiles,
|
||||
handleAutoCompaction,
|
||||
handleCompactCommand,
|
||||
} from "./useChat.compaction.js";
|
||||
import {
|
||||
formatMessageWithFiles,
|
||||
handleSpecialCommands,
|
||||
initChatHistory,
|
||||
processSlashCommandResult,
|
||||
|
|
@ -253,33 +255,103 @@ export function useChat({
|
|||
}
|
||||
};
|
||||
|
||||
const handleUserMessage = async (message: string) => {
|
||||
// Check if this is a resume request (empty message after interruption)
|
||||
if (message === "" && wasInterrupted) {
|
||||
// Find the index of the last user or tool message to resume from
|
||||
let lastUserOrToolIndex = -1;
|
||||
for (let i = chatHistory.length - 1; i >= 0; i--) {
|
||||
if (
|
||||
chatHistory[i].message.role === "user" ||
|
||||
!!chatHistory[i].toolCallStates?.length
|
||||
) {
|
||||
lastUserOrToolIndex = i;
|
||||
break;
|
||||
const handleResumeRequest = async (message: string) => {
|
||||
if (message !== "" || !wasInterrupted) return false;
|
||||
|
||||
// Find the index of the last user or tool message to resume from
|
||||
let lastUserOrToolIndex = -1;
|
||||
for (let i = chatHistory.length - 1; i >= 0; i--) {
|
||||
if (
|
||||
chatHistory[i].message.role === "user" ||
|
||||
!!chatHistory[i].toolCallStates?.length
|
||||
) {
|
||||
lastUserOrToolIndex = i;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
if (lastUserOrToolIndex >= 0) {
|
||||
// Truncate history to include up to and including the user/tool message
|
||||
const truncatedHistory = chatHistory.slice(0, lastUserOrToolIndex + 1);
|
||||
setChatHistory(truncatedHistory);
|
||||
|
||||
// Clear the interrupted state and resume
|
||||
setWasInterrupted(false);
|
||||
|
||||
// Re-execute streaming with the truncated history
|
||||
await executeStreamingResponse(truncatedHistory, compactionIndex);
|
||||
return true;
|
||||
}
|
||||
|
||||
return false;
|
||||
};
|
||||
|
||||
const handleSlashCommandProcessing = async (
|
||||
message: string,
|
||||
): Promise<string | null> => {
|
||||
// Handle slash commands (skip in remote mode except for /exit which we handled above)
|
||||
if (isRemoteMode || !assistant) {
|
||||
return message;
|
||||
}
|
||||
|
||||
const commandResult = await handleSlashCommands(message, assistant);
|
||||
if (!commandResult) {
|
||||
return message;
|
||||
}
|
||||
|
||||
if (commandResult.compact) {
|
||||
await handleCompactCommand({
|
||||
chatHistory,
|
||||
model,
|
||||
llmApi,
|
||||
setChatHistory,
|
||||
setCompactionIndex,
|
||||
currentSession,
|
||||
setCurrentSession,
|
||||
});
|
||||
return null;
|
||||
}
|
||||
|
||||
const newInput = processSlashCommandResult({
|
||||
result: commandResult,
|
||||
chatHistory,
|
||||
setChatHistory,
|
||||
exit,
|
||||
onShowConfigSelector,
|
||||
onShowModelSelector,
|
||||
onShowMCPSelector,
|
||||
onShowSessionSelector,
|
||||
onClear,
|
||||
});
|
||||
|
||||
return newInput || null;
|
||||
};
|
||||
|
||||
const convertMessageContentToString = (content: any): string => {
|
||||
if (typeof content === "string") {
|
||||
return content;
|
||||
}
|
||||
|
||||
// Convert MessagePart[] to string (extracting text, noting images)
|
||||
return content
|
||||
.map((part: any) => {
|
||||
if (part.type === "text") {
|
||||
return part.text;
|
||||
} else if (part.type === "imageUrl") {
|
||||
return "[Image]";
|
||||
}
|
||||
}
|
||||
return "";
|
||||
})
|
||||
.join("");
|
||||
};
|
||||
|
||||
if (lastUserOrToolIndex >= 0) {
|
||||
// Truncate history to include up to and including the user/tool message
|
||||
const truncatedHistory = chatHistory.slice(0, lastUserOrToolIndex + 1);
|
||||
setChatHistory(truncatedHistory);
|
||||
|
||||
// Clear the interrupted state and resume
|
||||
setWasInterrupted(false);
|
||||
|
||||
// Re-execute streaming with the truncated history
|
||||
await executeStreamingResponse(truncatedHistory, compactionIndex);
|
||||
return;
|
||||
}
|
||||
const handleUserMessage = async (
|
||||
message: string,
|
||||
imageMap?: Map<string, Buffer>,
|
||||
) => {
|
||||
// Check if this is a resume request (empty message after interruption)
|
||||
if (await handleResumeRequest(message)) {
|
||||
return;
|
||||
}
|
||||
|
||||
// Clear interrupted state if user types a new message
|
||||
|
|
@ -299,60 +371,41 @@ export function useChat({
|
|||
|
||||
if (handled) return;
|
||||
|
||||
// Handle slash commands (skip in remote mode except for /exit which we handled above)
|
||||
if (!isRemoteMode && assistant) {
|
||||
const commandResult = await handleSlashCommands(message, assistant);
|
||||
if (commandResult) {
|
||||
if (commandResult.compact) {
|
||||
await handleCompactCommand({
|
||||
chatHistory,
|
||||
model,
|
||||
llmApi,
|
||||
setChatHistory,
|
||||
setCompactionIndex,
|
||||
currentSession,
|
||||
setCurrentSession,
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
const newInput = processSlashCommandResult({
|
||||
result: commandResult,
|
||||
chatHistory,
|
||||
setChatHistory,
|
||||
exit,
|
||||
onShowConfigSelector,
|
||||
onShowModelSelector,
|
||||
onShowMCPSelector,
|
||||
onShowSessionSelector,
|
||||
onClear,
|
||||
});
|
||||
|
||||
if (newInput) {
|
||||
message = newInput;
|
||||
} else {
|
||||
return;
|
||||
}
|
||||
}
|
||||
// Handle slash commands
|
||||
const processedMessage = await handleSlashCommandProcessing(message);
|
||||
if (processedMessage === null) {
|
||||
return; // Command was handled and no further processing needed
|
||||
}
|
||||
message = processedMessage;
|
||||
|
||||
// Track telemetry
|
||||
trackUserMessage(message, model);
|
||||
|
||||
// Add user message to history and display
|
||||
const { messageText, contextItems } = formatMessageWithFiles(
|
||||
// Format message with attached files and images
|
||||
logger.debug("Processing message with images", {
|
||||
hasImages: !!(imageMap && imageMap.size > 0),
|
||||
imageCount: imageMap?.size || 0,
|
||||
});
|
||||
const newUserMessage = await formatMessageWithFiles(
|
||||
message,
|
||||
attachedFiles,
|
||||
imageMap,
|
||||
);
|
||||
logger.debug("Message formatted successfully");
|
||||
|
||||
if (attachedFiles.length > 0) {
|
||||
setAttachedFiles([]);
|
||||
}
|
||||
|
||||
// In remote mode, send message to server instead of processing locally
|
||||
if (isRemoteMode && remoteUrl) {
|
||||
const messageContentString = convertMessageContentToString(
|
||||
newUserMessage.message.content,
|
||||
);
|
||||
|
||||
await handleRemoteMessage({
|
||||
remoteUrl,
|
||||
messageContent: messageText,
|
||||
messageContent: messageContentString,
|
||||
setChatHistory,
|
||||
});
|
||||
return;
|
||||
|
|
@ -369,14 +422,7 @@ export function useChat({
|
|||
setCompactionIndex,
|
||||
});
|
||||
|
||||
// NOW add user message to history with context items
|
||||
const newUserMessage: ChatHistoryItem = {
|
||||
message: {
|
||||
role: "user",
|
||||
content: messageText,
|
||||
},
|
||||
contextItems,
|
||||
};
|
||||
// Add the formatted user message to history
|
||||
const newHistory = [...currentChatHistory, newUserMessage];
|
||||
setChatHistory(newHistory);
|
||||
|
||||
|
|
|
|||
|
|
@ -1,5 +1,6 @@
|
|||
import type { PermissionMode } from "../../permissions/types.js";
|
||||
import { logger } from "../../util/logger.js";
|
||||
import type { TextBuffer } from "../TextBuffer.js";
|
||||
|
||||
// Helper function to handle control keys
|
||||
interface ControlKeysOptions {
|
||||
|
|
@ -10,6 +11,102 @@ interface ControlKeysOptions {
|
|||
showFileSearch: boolean;
|
||||
cycleModes: () => Promise<PermissionMode>;
|
||||
clearInput?: () => void;
|
||||
textBuffer?: TextBuffer;
|
||||
onTextBufferUpdate?: () => void;
|
||||
}
|
||||
|
||||
// Helper function to check if clipboard contains an image
|
||||
async function checkClipboardForImage(): Promise<boolean> {
|
||||
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<Buffer | null> {
|
||||
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 {
|
||||
|
|
@ -21,6 +118,8 @@ export function handleControlKeys(options: ControlKeysOptions): boolean {
|
|||
showFileSearch,
|
||||
cycleModes,
|
||||
clearInput,
|
||||
textBuffer,
|
||||
onTextBufferUpdate,
|
||||
} = options;
|
||||
|
||||
// Handle Ctrl+C to clear input
|
||||
|
|
@ -29,6 +128,36 @@ export function handleControlKeys(options: ControlKeysOptions): boolean {
|
|||
return true;
|
||||
}
|
||||
|
||||
// Handle Ctrl+V for clipboard paste (including images)
|
||||
if (key.ctrl && input === "v" && textBuffer) {
|
||||
logger.debug("Handling clipboard paste");
|
||||
// Check for images asynchronously
|
||||
checkClipboardForImage()
|
||||
.then(async (hasImage) => {
|
||||
if (hasImage) {
|
||||
const imageBuffer = await getClipboardImage();
|
||||
if (imageBuffer) {
|
||||
textBuffer.addImage(imageBuffer);
|
||||
// Trigger UI update
|
||||
if (onTextBufferUpdate) {
|
||||
onTextBufferUpdate();
|
||||
}
|
||||
return;
|
||||
}
|
||||
}
|
||||
// If no image or image reading failed, let normal text paste handling continue
|
||||
// We return false here to allow the normal paste processing to happen
|
||||
})
|
||||
.catch((error) => {
|
||||
logger.debug("Error checking clipboard for image:", error);
|
||||
// Continue with normal text paste handling
|
||||
});
|
||||
|
||||
// Don't consume the event - let normal paste handling continue
|
||||
// This allows text pastes to work normally when no image is present
|
||||
return false;
|
||||
}
|
||||
|
||||
// Handle Ctrl+D to exit
|
||||
if (key.ctrl && input === "d") {
|
||||
exit();
|
||||
|
|
|
|||
Loading…
Add table
Reference in a new issue