Elffuss BraidHub

kikocis/continue public

Merge pull request #7671 from continuedev/tingwai/con-3846-cli-web-fetch

feat: cli fetch tool to use fetchUrlContent from core
Changesetb339f37e78ceaf2bd9a340ee368acd35e177ed20280a33af0f6beb2014603ae0
AuthorNate Sesti <33237525+sestinj@users.noreply.github.com> · 2025-09-10 14:47 -07:00
CommitterGitHub <noreply@github.com> · 2025-09-10 14:47 -07:00
Parents5474b5e9e86c, 3bec07507498

Browse the files at this changeset

4 files changed

modified extensions/cli/build.mjs +12 −1
@@ -1,7 +1,7 @@
11 #!/usr/bin/env node
22
33 import * as esbuild from "esbuild";
4-import { chmodSync, writeFileSync } from "fs";
4+import { chmodSync, writeFileSync, copyFileSync } from "fs";
55 import { dirname, resolve } from "path";
66 import { fileURLToPath } from "url";
77
@@ -13,6 +13,7 @@
1313 const external = [
1414 "@sentry/profiling-node", // Contains native profiler bindings (optional)
1515 "fsevents", // macOS native file watcher (optional dependency)
16+ "./xhr-sync-worker.js", // JSDOM worker file that needs to be copied separately
1617 ];
1718
1819 console.log("Building CLI with esbuild...");
@@ -84,6 +85,16 @@
8485 // Write metafile for analysis
8586 writeFileSync("dist/meta.json", JSON.stringify(result.metafile, null, 2));
8687
88+ // Copy worker files needed by JSDOM
89+ const workerSource = resolve(__dirname, "node_modules/jsdom/lib/jsdom/living/xhr/xhr-sync-worker.js");
90+ const workerDest = resolve(__dirname, "dist/xhr-sync-worker.js");
91+ try {
92+ copyFileSync(workerSource, workerDest);
93+ console.log("✓ Copied xhr-sync-worker.js");
94+ } catch (error) {
95+ console.warn("Warning: Could not copy xhr-sync-worker.js:", error.message);
96+ }
97+
8798 // Create wrapper script with shebang
8899 writeFileSync("dist/cn.js", "#!/usr/bin/env node\nimport('./index.js');");
89100
added extensions/cli/src/tools/fetch.test.ts +169 −0
@@ -0,0 +1,169 @@
1+import type { ContextItem } from "core/index.js";
2+import { fetchUrlContentImpl } from "core/tools/implementations/fetchUrlContent.js";
3+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
4+
5+import { fetchTool } from "./fetch.js";
6+
7+// Mock the core fetchUrlContent implementation
8+vi.mock("core/tools/implementations/fetchUrlContent.js", () => ({
9+ fetchUrlContentImpl: vi.fn(),
10+}));
11+
12+const mockFetchUrlContentImpl = vi.mocked(fetchUrlContentImpl);
13+
14+describe("fetchTool", () => {
15+ let originalConsoleError: typeof console.error;
16+
17+ beforeEach(() => {
18+ originalConsoleError = console.error;
19+ console.error = vi.fn();
20+ mockFetchUrlContentImpl.mockReset();
21+ });
22+
23+ afterEach(() => {
24+ console.error = originalConsoleError;
25+ });
26+
27+ it("should return clean content from successful fetch", async () => {
28+ const mockContextItems: ContextItem[] = [
29+ {
30+ name: "Example Page",
31+ description: "https://example.com",
32+ content:
33+ "# Example Page\n\nThis is some example content from a webpage.",
34+ uri: { type: "url", value: "https://example.com" },
35+ },
36+ ];
37+
38+ mockFetchUrlContentImpl.mockResolvedValue(mockContextItems);
39+
40+ const result = await fetchTool.run({ url: "https://example.com" });
41+
42+ expect(result).toBe(
43+ "# Example Page\n\nThis is some example content from a webpage.",
44+ );
45+ expect(mockFetchUrlContentImpl).toHaveBeenCalledWith(
46+ { url: "https://example.com" },
47+ { fetch },
48+ );
49+ });
50+
51+ it("should handle truncation warnings from core implementation", async () => {
52+ const mockContextItems: ContextItem[] = [
53+ {
54+ name: "Long Page",
55+ description: "https://example.com",
56+ content: "This is the main content that was truncated.",
57+ uri: { type: "url", value: "https://example.com" },
58+ },
59+ {
60+ name: "Truncation warning",
61+ description: "",
62+ content:
63+ "The content from https://example.com was truncated because it exceeded the 20000 character limit.",
64+ },
65+ ];
66+
67+ mockFetchUrlContentImpl.mockResolvedValue(mockContextItems);
68+
69+ const result = await fetchTool.run({ url: "https://example.com" });
70+
71+ expect(result).toBe(
72+ "This is the main content that was truncated.\n\nThe content from https://example.com was truncated because it exceeded the 20000 character limit.",
73+ );
74+ });
75+
76+ it("should handle multiple content items", async () => {
77+ const mockContextItems: ContextItem[] = [
78+ {
79+ name: "Page 1",
80+ description: "https://example.com",
81+ content: "Content from page 1",
82+ uri: { type: "url", value: "https://example.com" },
83+ },
84+ {
85+ name: "Page 2",
86+ description: "https://example.com",
87+ content: "Content from page 2",
88+ uri: { type: "url", value: "https://example.com" },
89+ },
90+ ];
91+
92+ mockFetchUrlContentImpl.mockResolvedValue(mockContextItems);
93+
94+ const result = await fetchTool.run({ url: "https://example.com" });
95+
96+ expect(result).toBe("Content from page 1\n\nContent from page 2");
97+ });
98+
99+ it("should return error message when no content items returned", async () => {
100+ mockFetchUrlContentImpl.mockResolvedValue([]);
101+
102+ const result = await fetchTool.run({ url: "https://example.com" });
103+
104+ expect(result).toBe(
105+ "Error: Could not fetch content from https://example.com",
106+ );
107+ });
108+
109+ it("should handle errors from core implementation", async () => {
110+ const error = new Error("Network error");
111+ mockFetchUrlContentImpl.mockRejectedValue(error);
112+
113+ const result = await fetchTool.run({ url: "https://example.com" });
114+
115+ expect(result).toBe("Error: Network error");
116+ });
117+
118+ it("should call fetchUrlContentImpl with correct arguments", async () => {
119+ const mockContextItems: ContextItem[] = [
120+ {
121+ name: "Test Page",
122+ description: "https://example.com",
123+ content: "Test content",
124+ uri: { type: "url", value: "https://example.com" },
125+ },
126+ ];
127+
128+ mockFetchUrlContentImpl.mockResolvedValue(mockContextItems);
129+
130+ await fetchTool.run({ url: "https://example.com" });
131+
132+ expect(mockFetchUrlContentImpl).toHaveBeenCalledWith(
133+ { url: "https://example.com" },
134+ { fetch },
135+ );
136+ });
137+
138+ it("should have correct tool metadata", () => {
139+ expect(fetchTool.name).toBe("Fetch");
140+ expect(fetchTool.displayName).toBe("Fetch");
141+ expect(fetchTool.description).toBe(
142+ "Fetches content from a URL, converts to markdown, and handles long content with truncation",
143+ );
144+ expect(fetchTool.readonly).toBe(true);
145+ expect(fetchTool.isBuiltIn).toBe(true);
146+ expect(fetchTool.parameters).toEqual({
147+ url: {
148+ type: "string",
149+ description: "The URL to fetch content from",
150+ required: true,
151+ },
152+ });
153+ });
154+
155+ it("should provide correct preview in preprocess", async () => {
156+ const args = { url: "https://example.com" };
157+ const result = await fetchTool.preprocess?.(args);
158+
159+ expect(result).toEqual({
160+ preview: [
161+ {
162+ type: "text",
163+ content: "Will fetch: https://example.com",
164+ },
165+ ],
166+ args,
167+ });
168+ });
169+});
modified extensions/cli/src/tools/fetch.ts +24 −97
@@ -1,50 +1,19 @@
1-import TurndownService from "turndown";
1+import type { ContextItem } from "core/index.js";
2+import { fetchUrlContentImpl } from "core/tools/implementations/fetchUrlContent.js";
23
34 import { Tool } from "./types.js";
45
5-const turndownService = new TurndownService({
6- headingStyle: "atx",
7- codeBlockStyle: "fenced",
8- fence: "```",
9- emDelimiter: "*",
10- strongDelimiter: "**",
11- linkStyle: "inlined",
12- linkReferenceStyle: "full",
13-});
14-
15-// Configure turndown for better markdown output
16-turndownService.addRule("strikethrough", {
17- filter: ["del", "s"],
18- replacement: function (content) {
19- return "~~" + content + "~~";
20- },
21-});
22-
23-// Handle code blocks better
24-turndownService.addRule("pre", {
25- filter: "pre",
26- replacement: function (content, node) {
27- const codeEl = node.querySelector("code");
28- const language = codeEl?.className.match(/language-(\w+)/)?.[1] || "";
29- return "\n\n```" + language + "\n" + content + "\n```\n\n";
30- },
31-});
32-
336 export const fetchTool: Tool = {
347 name: "Fetch",
358 displayName: "Fetch",
36- description: "Fetches content from a URL and converts it to markdown format",
9+ description:
10+ "Fetches content from a URL, converts to markdown, and handles long content with truncation",
3711 parameters: {
3812 url: {
3913 type: "string",
4014 description: "The URL to fetch content from",
4115 required: true,
4216 },
43- timeout: {
44- type: "number",
45- description: "Request timeout in milliseconds (default: 10000)",
46- required: false,
47- },
4817 },
4918 readonly: true,
5019 isBuiltIn: true,
@@ -59,76 +28,34 @@
5928 args,
6029 };
6130 },
62- run: async (args: { url: string; timeout?: number }): Promise<string> => {
63- const { url, timeout = 10000 } = args;
31+ run: async (args: { url: string }): Promise<string> => {
32+ const { url } = args;
6433
6534 try {
66- // Validate URL
67- const urlObj = new URL(url);
68- if (!["http:", "https:"].includes(urlObj.protocol)) {
69- return "Error: Only HTTP and HTTPS URLs are supported";
70- }
71-
72- // Fetch the content
73- const controller = new AbortController();
74- const timeoutId = setTimeout(() => controller.abort(), timeout);
75-
76- const response = await fetch(url, {
77- signal: controller.signal,
78- headers: {
79- "User-Agent": "Continue-CLI/1.0 (https://continue.dev)",
80- Accept:
81- "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8",
82- "Accept-Language": "en-US,en;q=0.5",
83- "Accept-Encoding": "gzip, deflate",
84- "Cache-Control": "no-cache",
85- },
86- });
35+ // Suppress console errors from JSDOM CSS parsing
36+ const originalConsoleError = console.error;
37+ console.error = () => {};
8738
88- clearTimeout(timeoutId);
39+ // Use the core fetchUrlContent implementation
40+ const contextItems = await fetchUrlContentImpl({ url }, { fetch });
8941
90- if (!response.ok) {
91- return `Error: HTTP ${response.status} - ${response.statusText}`;
92- }
93-
94- const contentType = response.headers.get("content-type") || "";
95-
96- // Handle different content types
97- if (contentType.includes("application/json")) {
98- const json = await response.json();
99- return "```json\n" + JSON.stringify(json, null, 2) + "\n```";
100- }
101-
102- if (contentType.includes("text/plain")) {
103- const text = await response.text();
104- return text;
105- }
42+ // Restore console.error
43+ console.error = originalConsoleError;
10644
107- if (!contentType.includes("text/html")) {
108- return `Error: Unsupported content type: ${contentType}`;
45+ if (contextItems.length === 0) {
46+ return `Error: Could not fetch content from ${url}`;
10947 }
11048
111- // Process HTML content
112- const html = await response.text();
113-
114- // Convert HTML to markdown
115- const markdown = turndownService.turndown(html);
116-
117- // Clean up the markdown
118- const cleanedMarkdown = markdown
119- .replace(/\n\s*\n\s*\n/g, "\n\n") // Remove excessive newlines
120- .replace(/^\s+|\s+$/g, "") // Trim whitespace
121- .replace(/\\\[/g, "[") // Unescape brackets
122- .replace(/\\\]/g, "]");
123-
124- return `# Content from ${url}\n\n${cleanedMarkdown}`;
49+ // Format the results for CLI display
50+ return contextItems
51+ .map((item: ContextItem) => {
52+ if (item.name === "Truncation warning") {
53+ return item.content;
54+ }
55+ return item.content;
56+ })
57+ .join("\n\n");
12558 } catch (error) {
126- if (error instanceof TypeError && error.message.includes("fetch")) {
127- return `Error: Failed to fetch URL "${url}". Please check the URL and try again.`;
128- }
129- if (error instanceof Error && error.name === "AbortError") {
130- return `Error: Request timed out after ${timeout}ms`;
131- }
13259 return `Error: ${error instanceof Error ? error.message : String(error)}`;
13360 }
13461 },
modified extensions/cli/src/ui/__tests__/BottomStatusBarCtrlC.test.tsx +7 −0
@@ -13,6 +13,13 @@
1313 setExitMessageCallback: vi.fn(),
1414 }));
1515
16+// Mock git utility functions
17+vi.mock("../../util/git.js", () => ({
18+ isGitRepo: vi.fn(() => false),
19+ getGitRemoteUrl: vi.fn(() => null),
20+ getGitBranch: vi.fn(() => null),
21+}));
22+
1623 describe("BottomStatusBar Ctrl+C message", () => {
1724 const defaultProps: BottomStatusBarProps = {
1825 currentMode: "normal" as const,