Elffuss BraidHub

kikocis/continue public

Merge branch 'main' into agent-dev-data
Changeset2e6c624272fbe991c49245179e0feecd71ea590071f3d2bdd7f5fe2a087168c3
Authoruinstinct <61635505+uinstinct@users.noreply.github.com> · 2025-05-26 18:13 +05:30
Committeruinstinct <61635505+uinstinct@users.noreply.github.com> · 2025-05-26 18:13 +05:30
Parents0bc8a18563fc, cb66032ac113

Browse the files at this changeset

170 files changed

added .github/workflows/metrics.yaml +75 −0
@@ -0,0 +1,75 @@
1+name: Monthly issue metrics
2+on:
3+ workflow_dispatch:
4+ schedule:
5+ # Runs every Monday at 9:00 AM PST (17:00 UTC)
6+ - cron: "0 17 * * 1"
7+
8+ push:
9+ branches:
10+ - nate/metrics-action
11+
12+permissions:
13+ contents: read
14+
15+jobs:
16+ build:
17+ name: issue metrics
18+ runs-on: ubuntu-latest
19+ permissions:
20+ issues: write
21+ pull-requests: read
22+ steps:
23+ - name: Get dates for last month
24+ shell: bash
25+ run: |
26+ # Calculate the first day of the previous month
27+ first_day=$(date -d "last month" +%Y-%m-01)
28+
29+ # Calculate the last day of the previous month
30+ last_day=$(date -d "$first_day +1 month -1 day" +%Y-%m-%d)
31+
32+ #Set an environment variable with the date range
33+ echo "$first_day..$last_day"
34+ echo "last_month=$first_day..$last_day" >> "$GITHUB_ENV"
35+
36+ - name: Run issue-metrics tool
37+ uses: github/issue-metrics@v3
38+ env:
39+ GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
40+ SEARCH_QUERY: 'repo:continuedev/continue created:${{ env.last_month }} -reason:"not planned"'
41+
42+ - name: Read metrics file content
43+ id: read-metrics
44+ run: |
45+ content=$(cat ./issue_metrics.md)
46+ # This prepares the content in a way that can be used in GitHub Actions
47+ content="${content//'%'/'%25'}"
48+ content="${content//$'\n'/'%0A'}"
49+ # content="${content//$'\r'/'%0D'}"
50+ echo "metrics_content=$content" >> "$GITHUB_OUTPUT"
51+
52+ - name: Post a message in a channel
53+ uses: slackapi/slack-github-action@v2.1.0
54+ with:
55+ webhook: ${{ secrets.ISSUE_PR_METRICS_SLACK_WEBHOOK_URL }}
56+ webhook-type: incoming-webhook
57+ payload: |
58+ text: "Issue / PR Metrics Report"
59+ blocks:
60+ - type: "header"
61+ text:
62+ type: "plain_text"
63+ text: "Monthly Issue Metrics Report"
64+ emoji: true
65+ - type: "section"
66+ text:
67+ type: "mrkdwn"
68+ text: |
69+ ${{ steps.read-metrics.outputs.metrics_content }}
70+
71+ - name: Upload metrics report as artifact
72+ uses: actions/upload-artifact@v4
73+ with:
74+ name: issue-metrics-report
75+ path: ./issue_metrics.md
modified binary/package-lock.json +3 −3
@@ -2589,9 +2589,9 @@
25892589 }
25902590 },
25912591 "node_modules/axios": {
2592- "version": "1.7.9",
2593- "resolved": "https://registry.npmjs.org/axios/-/axios-1.7.9.tgz",
2594- "integrity": "sha512-LhLcE7Hbiryz8oMDdDptSrWowmB4Bl6RCt6sIJKpRB4XtVf0iEgewX3au/pJqm+Py1kCASkb/FFKjxQaLtxJvw==",
2592+ "version": "1.9.0",
2593+ "resolved": "https://registry.npmjs.org/axios/-/axios-1.9.0.tgz",
2594+ "integrity": "sha512-re4CqKTJaURpzbLHtIi6XpDv20/CnpXOtjRY5/CU32L8gU8ek9UIivcfvSWvmKEngmVbrUtPpdDwWDWL7DNHvg==",
25952595 "license": "MIT",
25962596 "dependencies": {
25972597 "follow-redirects": "^1.15.6",
modified binary/test/binary.test.ts +2 −0
@@ -226,6 +226,7 @@
226226 title: "Test Model",
227227 provider: "openai",
228228 model: "gpt-3.5-turbo",
229+ underlyingProviderName: "openai",
229230 };
230231 await messenger.request("config/addModel", {
231232 model,
@@ -252,6 +253,7 @@
252253 title: "Test Model",
253254 provider: "mock",
254255 model: "gpt-3.5-turbo",
256+ underlyingProviderName: "mock",
255257 };
256258 await messenger.request("config/addModel", {
257259 model,
modified core/autocomplete/CompletionProvider.ts +1 −1
@@ -244,7 +244,7 @@
244244 prefix,
245245 suffix,
246246 prompt,
247- modelProvider: llm.providerName,
247+ modelProvider: llm.underlyingProviderName,
248248 modelName: llm.model,
249249 completionOptions,
250250 cacheHit,
modified core/commands/slash/http.ts +1 −1
@@ -1,6 +1,6 @@
1+import { streamResponse } from "@continuedev/fetch";
12 import { SlashCommand } from "../../index.js";
23 import { removeQuotesAndEscapes } from "../../util/index.js";
3-import { streamResponse } from "../../llm/stream.js";
44
55 const HttpSlashCommand: SlashCommand = {
66 name: "http",
modified core/config/load.ts +1 −0
@@ -627,6 +627,7 @@
627627 function llmToSerializedModelDescription(llm: ILLM): ModelDescription {
628628 return {
629629 provider: llm.providerName,
630+ underlyingProviderName: llm.underlyingProviderName,
630631 model: llm.model,
631632 title: llm.title ?? llm.model,
632633 apiKey: llm.apiKey,
modified core/config/markdown/parseMarkdownRule.test.ts +20 −0
@@ -151,4 +151,24 @@
151151 );
152152 expect(result.name).toBe("custom-rule");
153153 });
154+
155+ it("should include description from frontmatter", () => {
156+ const content = `---
157+globs: "**/test/**/*.kt"
158+name: Test Rule
159+description: This is a rule description from frontmatter
160+---
161+
162+# Test Rule
163+
164+This is the content of the rule.`;
165+
166+ const result = convertMarkdownRuleToContinueRule(
167+ "/path/to/rule.md",
168+ content,
169+ );
170+ expect(result.description).toBe(
171+ "This is a rule description from frontmatter",
172+ );
173+ });
154174 });
modified core/config/markdown/parseMarkdownRule.ts +2 −1
@@ -59,9 +59,10 @@
5959 }
6060
6161 return {
62+ name,
6263 rule: markdown,
6364 globs: frontmatter.globs,
64- name,
65+ description: frontmatter.description,
6566 source: "rules-block",
6667 ruleFile: path,
6768 };
modified core/config/util.ts +1 −0
@@ -77,6 +77,7 @@
7777 model: model.model,
7878 apiKey: model.apiKey,
7979 apiBase: model.apiBase,
80+ maxStopWords: model.maxStopWords,
8081 defaultCompletionOptions: model.completionOptions,
8182 };
8283 if (model.systemMessage) {
modified core/config/yaml/loadYaml.ts +2 −2
@@ -71,7 +71,7 @@
7171 command: server.command,
7272 args: server.args ?? [],
7373 env: server.env,
74- },
74+ } as any, // TODO: Fix the mcpServers types in config-yaml (discriminated union)
7575 timeout: server.connectionTimeout,
7676 };
7777 }
@@ -458,7 +458,7 @@
458458 transport: {
459459 type: "stdio",
460460 args: [],
461- ...server,
461+ ...(server as any), // TODO: fix the types on mcpServers in config-yaml
462462 },
463463 timeout: server.connectionTimeout,
464464 })),
modified core/context/mcp/MCPConnection.test.ts +35 −3
@@ -4,7 +4,7 @@
44
55 describe("MCPConnection", () => {
66 beforeEach(() => {
7- jest.clearAllMocks();
7+ jest.restoreAllMocks();
88 });
99
1010 describe("constructor", () => {
@@ -173,11 +173,11 @@
173173 });
174174
175175 it("should handle custom connection timeout", async () => {
176- const conn = new MCPConnection({ ...options, timeout: 11 });
176+ const conn = new MCPConnection({ ...options, timeout: 1500 });
177177 const mockConnect = jest
178178 .spyOn(Client.prototype, "connect")
179179 .mockImplementation(
180- () => new Promise((resolve) => setTimeout(resolve, 10)),
180+ () => new Promise((resolve) => setTimeout(resolve, 1000)),
181181 );
182182
183183 const abortController = new AbortController();
@@ -229,6 +229,38 @@
229229 expect(conn.errors[0]).toContain('command "test-cmd" not found');
230230 expect(mockConnect).toHaveBeenCalled();
231231 });
232+
233+ it.skip("should include stderr output in error message when stdio command fails", async () => {
234+ // Clear any existing mocks to ensure we get real behavior
235+ jest.restoreAllMocks();
236+
237+ // Use a command that will definitely fail and produce stderr output
238+ const failingOptions = {
239+ name: "failing-mcp",
240+ id: "failing-id",
241+ transport: {
242+ type: "stdio" as const,
243+ command: "node",
244+ args: [
245+ "-e",
246+ "console.error('Custom error message from stderr'); process.exit(1);",
247+ ],
248+ },
249+ timeout: 5000, // Give enough time for the command to run and fail
250+ };
251+
252+ const conn = new MCPConnection(failingOptions);
253+ const abortController = new AbortController();
254+
255+ await conn.connectClient(false, abortController.signal);
256+
257+ expect(conn.status).toBe("error");
258+ expect(conn.errors).toHaveLength(1);
259+ expect(conn.errors[0]).toContain("Failed to connect");
260+ expect(conn.errors[0]).toContain("Process output:");
261+ expect(conn.errors[0]).toContain("STDERR:");
262+ expect(conn.errors[0]).toContain("Custom error message from stderr");
263+ });
232264 });
233265
234266 describe.skip("actually connect to Filesystem MCP", () => {
modified core/context/mcp/MCPConnection.ts +29 −1
@@ -38,6 +38,10 @@
3838 public resources: MCPResource[] = [];
3939 private transport: Transport;
4040 private connectionPromise: Promise<unknown> | null = null;
41+ private stdioOutput: { stdout: string; stderr: string } = {
42+ stdout: "",
43+ stderr: "",
44+ };
4145
4246 constructor(public options: MCPOptions) {
4347 this.transport = this.constructTransport(options);
@@ -91,6 +95,7 @@
9195 this.prompts = [];
9296 this.resources = [];
9397 this.errors = [];
98+ this.stdioOutput = { stdout: "", stderr: "" };
9499
95100 this.abortController.abort();
96101 this.abortController = new AbortController();
@@ -215,6 +220,20 @@
215220 }
216221 }
217222
223+ // Include stdio output if available for stdio transport
224+ if (
225+ this.options.transport.type === "stdio" &&
226+ (this.stdioOutput.stdout || this.stdioOutput.stderr)
227+ ) {
228+ errorMessage += "\n\nProcess output:";
229+ if (this.stdioOutput.stdout) {
230+ errorMessage += `\nSTDOUT:\n${this.stdioOutput.stdout}`;
231+ }
232+ if (this.stdioOutput.stderr) {
233+ errorMessage += `\nSTDERR:\n${this.stdioOutput.stderr}`;
234+ }
235+ }
236+
218237 this.status = "error";
219238 this.errors.push(errorMessage);
220239 } finally {
@@ -284,11 +303,20 @@
284303 options.transport.args || [],
285304 );
286305
287- return new StdioClientTransport({
306+ const transport = new StdioClientTransport({
288307 command,
289308 args,
290309 env,
310+ stderr: "pipe",
291311 });
312+
313+ // Capture stdio output for better error reporting
314+
315+ transport.stderr?.on("data", (data: Buffer) => {
316+ this.stdioOutput.stderr += data.toString();
317+ });
318+
319+ return transport;
292320 case "websocket":
293321 return new WebSocketClientTransport(new URL(options.transport.url));
294322 case "sse":
modified core/control-plane/schema.ts +1 −0
@@ -26,6 +26,7 @@
2626 apiKey: z.string().optional(),
2727 apiBase: z.string().optional(),
2828 contextLength: z.number().optional(),
29+ maxStopWords: z.number().optional(),
2930 template: z
3031 .enum([
3132 "llama2",
modified core/core.ts +65 −70
@@ -35,7 +35,6 @@
3535
3636 import {
3737 ContextItemWithId,
38- DiffLine,
3938 IdeSettings,
4039 ModelDescription,
4140 RangeInFile,
@@ -62,61 +61,7 @@
6261 import { llmStreamChat } from "./llm/streamChat";
6362 import type { FromCoreProtocol, ToCoreProtocol } from "./protocol";
6463 import type { IMessenger, Message } from "./protocol/messenger";
65-
66-// This function is used for jetbrains inline edit and apply
67-async function* streamDiffLinesGenerator(
68- configHandler: ConfigHandler,
69- abortedMessageIds: Set<string>,
70- msg: Message<ToCoreProtocol["streamDiffLines"][0]>,
71-): AsyncGenerator<DiffLine> {
72- const {
73- highlighted,
74- prefix,
75- suffix,
76- input,
77- language,
78- modelTitle,
79- includeRulesInSystemMessage,
80- } = msg.data;
81-
82- const { config } = await configHandler.loadConfig();
83- if (!config) {
84- throw new Error("Failed to load config");
85- }
86-
87- // Title can be an edit, chat, or apply model
88- // Fall back to chat
89- const llm =
90- config.modelsByRole.edit.find((m) => m.title === modelTitle) ??
91- config.modelsByRole.apply.find((m) => m.title === modelTitle) ??
92- config.modelsByRole.chat.find((m) => m.title === modelTitle) ??
93- config.selectedModelByRole.chat;
94-
95- if (!llm) {
96- throw new Error("No model selected");
97- }
98-
99- // rules included for edit, NOT apply
100- const rules = includeRulesInSystemMessage ? config.rules : undefined;
101-
102- for await (const diffLine of streamDiffLines({
103- highlighted,
104- prefix,
105- suffix,
106- llm,
107- rulesToInclude: rules,
108- input,
109- language,
110- onlyOneInsertion: false,
111- overridePrompt: undefined,
112- })) {
113- if (abortedMessageIds.has(msg.messageId)) {
114- abortedMessageIds.delete(msg.messageId);
115- break;
116- }
117- yield diffLine;
118- }
119-}
64+import { StreamAbortManager } from "./util/abortManager";
12065
12166 export class Core {
12267 configHandler: ConfigHandler;
@@ -132,7 +77,18 @@
13277 this.globalContext.get("indexingPaused") === true,
13378 );
13479
135- private abortedMessageIds: Set<string> = new Set();
80+ private messageAbortControllers = new Map<string, AbortController>();
81+ private addMessageAbortController(id: string): AbortController {
82+ const controller = new AbortController();
83+ this.messageAbortControllers.set(id, controller);
84+ controller.signal.addEventListener("abort", () => {
85+ this.messageAbortControllers.delete(id);
86+ });
87+ return controller;
88+ }
89+ private abortById(messageId: string) {
90+ this.messageAbortControllers.get(messageId)?.abort();
91+ }
13692
13793 invoke<T extends keyof ToCoreProtocol>(
13894 messageType: T,
@@ -301,7 +257,7 @@
301257 });
302258
303259 on("abort", (msg) => {
304- this.abortedMessageIds.add(msg.messageId);
260+ this.abortById(msg.data ?? msg.messageId);
305261 });
306262
307263 on("ping", (msg) => {
@@ -470,27 +426,28 @@
470426 }
471427 });
472428
473- on("llm/streamChat", (msg) =>
474- llmStreamChat(
429+ on("llm/streamChat", (msg) => {
430+ const abortController = this.addMessageAbortController(msg.messageId);
431+ return llmStreamChat(
475432 this.configHandler,
476- this.abortedMessageIds,
433+ abortController,
477434 msg,
478435 this.ide,
479436 this.messenger,
480- ),
481- );
437+ );
438+ });
482439
483440 on("llm/complete", async (msg) => {
484- const model = (await this.configHandler.loadConfig()).config
485- ?.selectedModelByRole.chat;
486-
441+ const { config } = await this.configHandler.loadConfig();
442+ const model = config?.selectedModelByRole.chat;
487443 if (!model) {
488444 throw new Error("No chat model selected");
489445 }
446+ const abortController = this.addMessageAbortController(msg.messageId);
490447
491448 const completion = await model.complete(
492449 msg.data.prompt,
493- new AbortController().signal,
450+ abortController.signal,
494451 msg.data.completionOptions,
495452 );
496453 return completion;
@@ -532,9 +489,47 @@
532489 this.completionProvider.cancel();
533490 });
534491
535- on("streamDiffLines", (msg) =>
536- streamDiffLinesGenerator(this.configHandler, this.abortedMessageIds, msg),
537- );
492+ on("streamDiffLines", async (msg) => {
493+ const { config } = await this.configHandler.loadConfig();
494+ if (!config) {
495+ throw new Error("Failed to load config");
496+ }
497+
498+ const { data } = msg;
499+
500+ // Title can be an edit, chat, or apply model
501+ // Fall back to chat
502+ const llm =
503+ config.modelsByRole.edit.find((m) => m.title === data.modelTitle) ??
504+ config.modelsByRole.apply.find((m) => m.title === data.modelTitle) ??
505+ config.modelsByRole.chat.find((m) => m.title === data.modelTitle) ??
506+ config.selectedModelByRole.chat;
507+
508+ if (!llm) {
509+ throw new Error("No model selected");
510+ }
511+
512+ return streamDiffLines({
513+ highlighted: data.highlighted,
514+ prefix: data.prefix,
515+ suffix: data.suffix,
516+ llm,
517+ // rules included for edit, NOT apply
518+ rulesToInclude: data.includeRulesInSystemMessage
519+ ? config.rules
520+ : undefined,
521+ input: data.input,
522+ language: data.language,
523+ onlyOneInsertion: false,
524+ overridePrompt: undefined,
525+ abortControllerId: data.fileUri ?? "current-file-stream", // not super important since currently cancelling apply will cancel all streams it's one file at a time
526+ });
527+ });
528+
529+ on("cancelApply", async (msg) => {
530+ const abortManager = StreamAbortManager.getInstance();
531+ abortManager.clear();
532+ });
538533
539534 on("completeOnboarding", this.handleCompleteOnboarding.bind(this));
540535
modified core/edit/recursiveStream.ts +5 −2
@@ -16,6 +16,7 @@
1616
1717 export async function* recursiveStream(
1818 llm: ILLM,
19+ abortController: AbortController,
1920 prompt: ChatMessage[] | string,
2021 prediction: Prediction | undefined,
2122 currentBuffer = "",
@@ -28,7 +29,7 @@
2829 // let whiteSpaceAtEndOfBuffer = buffer.match(/\s*$/)?.[0] ?? ""; // attempts at fixing whitespace bug with recursive boundaries
2930
3031 if (typeof prompt === "string") {
31- const generator = llm.streamComplete(prompt, new AbortController().signal, {
32+ const generator = llm.streamComplete(prompt, abortController.signal, {
3233 raw: true,
3334 prediction: undefined,
3435 reasoning: false,
@@ -50,6 +51,7 @@
5051 // // TODO - Prediction capabilities lost because of partial input
5152 // yield* recursiveStream(
5253 // llm,
54+ // abortController,
5355 // continuationPrompt,
5456 // undefined,
5557 // buffer,
@@ -60,7 +62,7 @@
6062 }
6163 }
6264 } else {
63- const generator = llm.streamChat(prompt, new AbortController().signal, {
65+ const generator = llm.streamChat(prompt, abortController.signal, {
6466 prediction,
6567 reasoning: false,
6668 });
@@ -90,6 +92,7 @@
9092 // await generator.return(DUD_PROMPT_LOG);
9193 // yield* recursiveStream(
9294 // llm,
95+ // abortController,
9396 // continuationPrompt,
9497 // undefined,
9598 // buffer,
modified core/edit/streamDiffLines.ts +6 −1
@@ -20,6 +20,7 @@
2020 import { streamLines } from "../diff/util";
2121 import { getSystemMessageWithRules } from "../llm/rules/getSystemMessageWithRules";
2222 import { gptEditPrompt } from "../llm/templates/edit";
23+import { StreamAbortManager } from "../util/abortManager";
2324 import { findLast } from "../util/findLast";
2425 import { Telemetry } from "../util/posthog";
2526 import { recursiveStream } from "./recursiveStream";
@@ -63,6 +64,7 @@
6364 highlighted,
6465 suffix,
6566 llm,
67+ abortControllerId,
6668 input,
6769 language,
6870 onlyOneInsertion,
@@ -73,12 +75,15 @@
7375 highlighted: string;
7476 suffix: string;
7577 llm: ILLM;
78+ abortControllerId: string;
7679 input: string;
7780 language: string | undefined;
7881 onlyOneInsertion: boolean;
7982 overridePrompt: ChatMessage[] | undefined;
8083 rulesToInclude: RuleWithSource[] | undefined;
8184 }): AsyncGenerator<DiffLine> {
85+ const abortManager = StreamAbortManager.getInstance();
86+ const abortController = abortManager.get(abortControllerId);
8287 void Telemetry.capture(
8388 "inlineEdit",
8489 {
@@ -158,7 +163,7 @@
158163 content: highlighted,
159164 };
160165
161- const completion = recursiveStream(llm, prompt, prediction);
166+ const completion = recursiveStream(llm, abortController, prompt, prediction);
162167
163168 let lines = streamLines(completion);
164169
modified core/index.d.ts +5 −1
@@ -93,6 +93,7 @@
9393 extends Omit<LLMOptions, RequiredLLMOptions>,
9494 Required<Pick<LLMOptions, RequiredLLMOptions>> {
9595 get providerName(): string;
96+ get underlyingProviderName(): string;
9697
9798 complete(
9899 prompt: string,
@@ -423,7 +424,7 @@
423424 completion: string;
424425 }
425426
426-export type MessageModes = "chat" | "edit" | "agent";
427+export type MessageModes = "chat" | "agent";
427428
428429 export type ToolStatus =
429430 | "generating"
@@ -1035,6 +1036,7 @@
10351036 export interface ModelDescription {
10361037 title: string;
10371038 provider: string;
1039+ underlyingProviderName: string;
10381040 model: string;
10391041 apiKey?: string;
10401042
@@ -1240,6 +1242,7 @@
12401242 language: string | undefined;
12411243 modelTitle: string | undefined;
12421244 includeRulesInSystemMessage: boolean;
1245+ fileUri?: string;
12431246 }
12441247
12451248 export interface HighlightedCodePayload {
@@ -1332,6 +1335,7 @@
13321335 export interface JSONModelDescription {
13331336 title: string;
13341337 provider: string;
1338+ underlyingProviderName: string;
13351339 model: string;
13361340 apiKey?: string;
13371341 apiBase?: string;
modified core/llm/index.ts +12 −1
@@ -88,6 +88,14 @@
8888 return (this.constructor as typeof BaseLLM).providerName;
8989 }
9090
91+ /**
92+ * This exists because for the continue-proxy, sometimes we want to get the value of the underlying provider that is used on the server
93+ * For example, the underlying provider should always be sent with dev data
94+ */
95+ get underlyingProviderName(): string {
96+ return this.providerName;
97+ }
98+
9199 supportsFim(): boolean {
92100 return false;
93101 }
@@ -332,7 +340,7 @@
332340 name: "tokensGenerated",
333341 data: {
334342 model: model,
335- provider: this.providerName,
343+ provider: this.underlyingProviderName,
336344 promptTokens: promptTokens,
337345 generatedTokens: generatedTokens,
338346 },
@@ -382,6 +390,9 @@
382390
383391 // Error mapping to be more helpful
384392 if (!resp.ok) {
393+ if (resp.status === 499) {
394+ return resp; // client side cancellation
395+ }
385396 let text = await resp.text();
386397 if (resp.status === 404 && !resp.url.includes("/v1")) {
387398 const error = JSON.parse(text)?.error?.replace(/"/g, "'");
modified core/llm/llms/Anthropic.ts +5 −1
@@ -1,7 +1,7 @@
1+import { streamSse } from "@continuedev/fetch";
12 import { ChatMessage, CompletionOptions, LLMOptions } from "../../index.js";
23 import { renderChatMessage, stripImages } from "../../util/messageContent.js";
34 import { BaseLLM } from "../index.js";
4-import { streamSse } from "../stream.js";
55
66 class Anthropic extends BaseLLM {
77 static providerName = "anthropic";
@@ -213,6 +213,10 @@
213213 signal,
214214 });
215215
216+ if (response.status === 499) {
217+ return; // Aborted by user
218+ }
219+
216220 if (!response.ok) {
217221 const json = await response.json();
218222 if (json.type === "error") {
modified core/llm/llms/Asksage.ts +4 −8
@@ -134,10 +134,8 @@
134134 body: JSON.stringify(args),
135135 });
136136
137- if (!response.ok) {
138- throw new Error(
139- `API request failed with status ${response.status}: ${response.statusText}`,
140- );
137+ if (response.status === 499) {
138+ return ""; // Aborted by user
141139 }
142140
143141 const data = await response.json();
@@ -167,10 +165,8 @@
167165 signal,
168166 });
169167
170- if (!response.ok) {
171- throw new Error(
172- `API request failed with status ${response.status}: ${response.statusText}`,
173- );
168+ if (response.status === 499) {
169+ return; // Aborted by user
174170 }
175171
176172 const data = await response.json();
modified core/llm/llms/Bedrock.ts +1 −1
@@ -306,7 +306,7 @@
306306 }
307307
308308 const supportsTools =
309- PROVIDER_TOOL_SUPPORT.bedrock?.(options.model || "") ?? false;
309+ (this.capabilities?.tools || PROVIDER_TOOL_SUPPORT.bedrock?.(options.model)) ?? false;
310310
311311 let toolConfig = supportsTools && options.tools
312312 ? {
modified core/llm/llms/Cloudflare.ts +1 −1
@@ -1,7 +1,7 @@
1+import { streamSse } from "@continuedev/fetch";
12 import { ChatMessage, CompletionOptions } from "../../index.js";
23 import { renderChatMessage } from "../../util/messageContent.js";
34 import { BaseLLM } from "../index.js";
4-import { streamSse } from "../stream.js";
55
66 export default class Cloudflare extends BaseLLM {
77 static providerName = "cloudflare";
modified core/llm/llms/Cohere.ts +5 −1
@@ -1,3 +1,4 @@
1+import { streamJSON } from "@continuedev/fetch";
12 import {
23 ChatMessage,
34 Chunk,
@@ -6,7 +7,6 @@
67 } from "../../index.js";
78 import { renderChatMessage, stripImages } from "../../util/messageContent.js";
89 import { BaseLLM } from "../index.js";
9-import { streamJSON } from "../stream.js";
1010
1111 class Cohere extends BaseLLM {
1212 static providerName = "cohere";
@@ -84,6 +84,10 @@
8484 signal,
8585 });
8686
87+ if (resp.status === 499) {
88+ return; // Aborted by user
89+ }
90+
8791 if (options.stream === false) {
8892 const data = await resp.json();
8993 yield { role: "assistant", content: data.text };
modified core/llm/llms/Deepseek.ts +1 −1
@@ -1,5 +1,5 @@
1+import { streamSse } from "@continuedev/fetch";
12 import { CompletionOptions, LLMOptions } from "../../index.js";
2-import { streamSse } from "../stream.js";
33 import { osModelsEditPrompt } from "../templates/edit.js";
44
55 import OpenAI from "./OpenAI.js";
modified core/llm/llms/Flowise.ts +7 −3
@@ -132,12 +132,16 @@
132132 ): AsyncGenerator<ChatMessage> {
133133 const requestBody = this._getRequestBody(messages, options);
134134 const { socket, socketInfo } = await this._initializeSocket();
135- const request = this.fetch(this._getChatUrl(), {
135+ const response = await this.fetch(this._getChatUrl(), {
136136 method: "POST",
137137 headers: this._getHeaders(),
138138 body: JSON.stringify({ ...requestBody, socketIOClientId: socket.id }),
139139 signal,
140- }).then((res) => res.json());
140+ });
141+
142+ if (response.status === 499) {
143+ return; // Aborted by user
144+ }
141145
142146 while (await socketInfo.hasNextToken()) {
143147 yield { role: "assistant", content: socketInfo.getCurrentMessage() };
@@ -145,7 +149,7 @@
145149 if (socketInfo.error) {
146150 socket.disconnect();
147151 try {
148- yield { role: "assistant", content: (await request).text };
152+ yield { role: "assistant", content: await response.text() };
149153 } catch (error: any) {
150154 yield { role: "assistant", content: (error as Error).message ?? error };
151155 }
modified core/llm/llms/FreeTrial.ts +1 −1
@@ -1,3 +1,4 @@
1+import { streamResponse } from "@continuedev/fetch";
12 import { TRIAL_FIM_MODEL } from "../../config/onboarding.js";
23 import { getHeaders } from "../../continueServer/stubs/headers.js";
34 import { TRIAL_PROXY_URL } from "../../control-plane/client.js";
@@ -8,7 +9,6 @@
89 LLMOptions,
910 } from "../../index.js";
1011 import { BaseLLM } from "../index.js";
11-import { streamResponse } from "../stream.js";
1212
1313 class FreeTrial extends BaseLLM {
1414 static providerName = "free-trial";
modified core/llm/llms/Gemini.ts +4 −1
@@ -1,3 +1,4 @@
1+import { streamResponse } from "@continuedev/fetch";
12 import { v4 as uuidv4 } from "uuid";
23 import {
34 AssistantChatMessage,
@@ -10,7 +11,6 @@
1011 } from "../../index.js";
1112 import { renderChatMessage, stripImages } from "../../util/messageContent.js";
1213 import { BaseLLM } from "../index.js";
13-import { streamResponse } from "../stream.js";
1414 import {
1515 GeminiChatContent,
1616 GeminiChatContentPart,
@@ -438,6 +438,9 @@
438438 body: JSON.stringify(body),
439439 signal,
440440 });
441+ if (response.status === 499) {
442+ return; // Aborted by user
443+ }
441444 const data = await response.json();
442445 yield { role: "assistant", content: data.candidates[0].content };
443446 }
modified core/llm/llms/HuggingFaceInferenceAPI.ts +1 −1
@@ -1,6 +1,6 @@
1+import { streamSse } from "@continuedev/fetch";
12 import { CompletionOptions } from "../../index.js";
23 import { BaseLLM } from "../index.js";
3-import { streamSse } from "../stream.js";
44
55 class HuggingFaceInferenceAPI extends BaseLLM {
66 static providerName = "huggingface-inference-api";
modified core/llm/llms/HuggingFaceTGI.ts +1 −1
@@ -1,6 +1,6 @@
1+import { streamSse } from "@continuedev/fetch";
12 import { CompletionOptions, LLMOptions } from "../../index.js";
23 import { BaseLLM } from "../index.js";
3-import { streamSse } from "../stream.js";
44
55 class HuggingFaceTGI extends BaseLLM {
66 private static MAX_STOP_TOKENS = 4;
modified core/llm/llms/Inception.ts +1 −1
@@ -1,5 +1,5 @@
1+import { streamSse } from "@continuedev/fetch";
12 import { CompletionOptions, LLMOptions } from "../../index.js";
2-import { streamSse } from "../stream.js";
33
44 import OpenAI from "./OpenAI.js";
55
modified core/llm/llms/LlamaCpp.ts +1 −1
@@ -1,6 +1,6 @@
1+import { streamSse } from "@continuedev/fetch";
12 import { CompletionOptions, LLMOptions } from "../../index.js";
23 import { BaseLLM } from "../index.js";
3-import { streamSse } from "../stream.js";
44
55 class LlamaCpp extends BaseLLM {
66 static providerName = "llama.cpp";
modified core/llm/llms/Moonshot.ts +1 −1
@@ -1,5 +1,5 @@
1+import { streamSse } from "@continuedev/fetch";
12 import { CompletionOptions, LLMOptions } from "../../index.js";
2-import { streamSse } from "../stream.js";
33 import { osModelsEditPrompt } from "../templates/edit.js";
44
55 import OpenAI from "./OpenAI.js";
modified core/llm/llms/Ollama.ts +4 −1
@@ -2,6 +2,7 @@
22 import { JSONSchema7, JSONSchema7Object } from "json-schema";
33 import { v4 as uuidv4 } from "uuid";
44
5+import { streamResponse } from "@continuedev/fetch";
56 import {
67 ChatMessage,
78 ChatMessageRole,
@@ -12,7 +13,6 @@
1213 import { renderChatMessage } from "../../util/messageContent.js";
1314 import { getRemoteModelInfo } from "../../util/ollamaHelper.js";
1415 import { BaseLLM } from "../index.js";
15-import { streamResponse } from "../stream.js";
1616
1717 type OllamaChatMessage = {
1818 role: ChatMessageRole;
@@ -457,6 +457,9 @@
457457 }
458458
459459 if (chatOptions.stream === false) {
460+ if (response.status === 499) {
461+ return; // Aborted by user
462+ }
460463 const json = (await response.json()) as OllamaChatResponse;
461464 yield convertChatMessage(json);
462465 } else {
modified core/llm/llms/OpenAI.ts +4 −1
@@ -3,6 +3,7 @@
33 ChatCompletionMessageParam,
44 } from "openai/resources/index";
55
6+import { streamSse } from "@continuedev/fetch";
67 import {
78 ChatMessage,
89 CompletionOptions,
@@ -16,7 +17,6 @@
1617 LlmApiRequestType,
1718 toChatBody,
1819 } from "../openaiTypeConverters.js";
19-import { streamSse } from "../stream.js";
2020
2121 const NON_CHAT_MODELS = [
2222 "text-davinci-002",
@@ -352,6 +352,9 @@
352352
353353 // Handle non-streaming response
354354 if (body.stream === false) {
355+ if (response.status === 499) {
356+ return; // Aborted by user
357+ }
355358 const data = await response.json();
356359 yield data.choices[0].message;
357360 return;
modified core/llm/llms/SiliconFlow.ts +2 −2
@@ -1,5 +1,5 @@
1+import { streamSse } from "@continuedev/fetch";
12 import { Chunk, CompletionOptions, LLMOptions } from "../../index.js";
2-import { streamSse } from "../stream.js";
33 import { osModelsEditPrompt } from "../templates/edit.js";
44
55 import OpenAI from "./OpenAI.js";
@@ -58,7 +58,7 @@
5858 console.warn("[SiliconFlow] rerank: query is empty");
5959 return [];
6060 }
61-
61+
6262 if (!chunks || chunks.length === 0) {
6363 console.warn("[SiliconFlow] rerank: chunks is empty");
6464 return [];
modified core/llm/llms/VertexAI.ts +23 −5
@@ -1,9 +1,9 @@
11 import { GoogleAuth } from "google-auth-library";
22
3+import { streamResponse, streamSse } from "@continuedev/fetch";
34 import { ChatMessage, CompletionOptions, LLMOptions } from "../../index.js";
45 import { renderChatMessage, stripImages } from "../../util/messageContent.js";
56 import { BaseLLM } from "../index.js";
6-import { streamResponse, streamSse } from "../stream.js";
77
88 import Anthropic from "./Anthropic.js";
99 import Gemini from "./Gemini.js";
@@ -95,6 +95,7 @@
9595 protected async *StreamChatAnthropic(
9696 messages: ChatMessage[],
9797 options: CompletionOptions,
98+ signal: AbortSignal,
9899 ): AsyncGenerator<ChatMessage> {
99100 const systemMessage = stripImages(
100101 messages.filter((m) => m.role === "system")[0]?.content ?? "",
@@ -128,8 +129,13 @@
128129 ]
129130 : systemMessage,
130131 }),
132+ signal,
131133 });
132134
135+ if (response.status === 499) {
136+ return; // Aborted by user
137+ }
138+
133139 if (options.stream === false) {
134140 const data = await response.json();
135141 yield { role: "assistant", content: data.content[0].text };
@@ -150,6 +156,7 @@
150156 private async *streamChatGemini(
151157 messages: ChatMessage[],
152158 options: CompletionOptions,
159+ signal: AbortSignal,
153160 ): AsyncGenerator<ChatMessage> {
154161 const apiURL = new URL(
155162 `publishers/google/models/${options.model}:streamGenerateContent`,
@@ -160,6 +167,7 @@
160167 const response = await this.fetch(apiURL, {
161168 method: "POST",
162169 body: JSON.stringify(body),
170+ signal,
163171 });
164172 for await (const message of this.geminiInstance.processGeminiResponse(
165173 streamResponse(response),
@@ -171,6 +179,7 @@
171179 private async *streamChatBison(
172180 messages: ChatMessage[],
173181 options: CompletionOptions,
182+ signal: AbortSignal,
174183 ): AsyncGenerator<ChatMessage> {
175184 const instances = messages.map((message) => ({ prompt: message.content }));
176185
@@ -193,7 +202,11 @@
193202 const response = await this.fetch(apiURL, {
194203 method: "POST",
195204 body: JSON.stringify(body),
205+ signal,
196206 });
207+ if (response.status === 499) {
208+ return; // Aborted by user
209+ }
197210 const data = await response.json();
198211 yield { role: "assistant", content: data.predictions[0].content };
199212 }
@@ -203,6 +216,7 @@
203216 protected async *StreamChatMistral(
204217 messages: ChatMessage[],
205218 options: CompletionOptions,
219+ signal: AbortSignal,
206220 ): AsyncGenerator<ChatMessage> {
207221 const apiBase = this.apiBase!;
208222 const apiURL = new URL(
@@ -228,6 +242,7 @@
228242 const response = await this.fetch(apiURL, {
229243 method: "POST",
230244 body: JSON.stringify(body),
245+ signal,
231246 });
232247
233248 for await (const chunk of streamSse(response)) {
@@ -304,6 +319,9 @@
304319 }),
305320 signal,
306321 });
322+ if (resp.status === 499) {
323+ return; // Aborted by user
324+ }
307325 // Streaming is not supported by code-gecko
308326 // TODO: convert to non-streaming fim method when one exist in continue.
309327 yield (await resp.json()).predictions[0].content;
@@ -323,14 +341,14 @@
323341 ? this.geminiInstance.removeSystemMessage(messages)
324342 : messages;
325343 if (this.vertexProvider === "gemini") {
326- yield* this.streamChatGemini(convertedMsgs, options);
344+ yield* this.streamChatGemini(convertedMsgs, options, signal);
327345 } else if (this.vertexProvider === "mistral") {
328- yield* this.StreamChatMistral(messages, options);
346+ yield* this.StreamChatMistral(messages, options, signal);
329347 } else if (this.vertexProvider === "anthropic") {
330- yield* this.StreamChatAnthropic(messages, options);
348+ yield* this.StreamChatAnthropic(messages, options, signal);
331349 } else {
332350 if (options.model.includes("bison")) {
333- yield* this.streamChatBison(convertedMsgs, options);
351+ yield* this.streamChatBison(convertedMsgs, options, signal);
334352 } else {
335353 throw new Error(`Unsupported model: ${options.model}`);
336354 }
modified core/llm/llms/Vllm.ts +4 −0
@@ -12,6 +12,10 @@
1212 }
1313 }
1414
15+ supportsFim(): boolean {
16+ return false;
17+ }
18+
1519 private _setupCompletionOptions() {
1620 this.fetch(this._getEndpoint("models"), {
1721 method: "GET",
modified core/llm/llms/WatsonX.ts +37 −53
@@ -1,15 +1,12 @@
1+import { streamResponse, streamSse } from "@continuedev/fetch";
12 import {
23 ChatMessage,
34 Chunk,
45 CompletionOptions,
56 LLMOptions,
67 } from "../../index.js";
7-import {
8- fromChatCompletionChunk,
9-} from "../openaiTypeConverters.js";
10-import { renderChatMessage } from "../../util/messageContent.js";
118 import { BaseLLM } from "../index.js";
12-import { streamResponse, streamSse } from "../stream.js";
9+import { fromChatCompletionChunk } from "../openaiTypeConverters.js";
1310
1411 let watsonxToken = {
1512 expiration: 0,
@@ -86,7 +83,7 @@
8683 }
8784
8885 _getEndpoint(endpoint: string): string {
89- return `${this.apiBase}/ml/v1/${this.deploymentId ? `deployments/${this.deploymentId}/` : ""}text/${endpoint}_stream?version=${this.apiVersion}`
86+ return `${this.apiBase}/ml/v1/${this.deploymentId ? `deployments/${this.deploymentId}/` : ""}text/${endpoint}_stream?version=${this.apiVersion}`;
9087 }
9188
9289 static providerName = "watsonx";
@@ -182,7 +179,6 @@
182179 signal: AbortSignal,
183180 options: CompletionOptions,
184181 ): AsyncGenerator<string> {
185-
186182 await this.updateWatsonxToken();
187183
188184 const stopSequences = options.stop?.slice(0, 6) ?? [];
@@ -214,44 +210,38 @@
214210 payload.project_id = this.projectId;
215211 }
216212
217- var response = await this.fetch(url, {
213+ const response = await this.fetch(url, {
218214 method: "POST",
219215 headers: headers,
220216 body: JSON.stringify(payload),
221217 signal,
222218 });
223219
224- if (!response.ok || response.body === null) {
225- throw new Error(
226- "Something went wrong. No response received, check your connection",
227- );
228- } else {
229- for await (const value of streamResponse(response)) {
230- const lines = value.split("\n");
231- let generatedChunk = "";
232- let generatedTextIndex = undefined;
233- lines.forEach((el: string) => {
234- // console.log(`${el}`);
235- if (el.startsWith("id:")) {
236- generatedTextIndex = parseInt(el.replace(/^id:\s+/, ""));
237- if (isNaN(generatedTextIndex)) {
238- console.error(`Unable to parse stream chunk ID: ${el}`);
239- }
240- } else if (el.startsWith("data:")) {
241- const dataStr = el.replace(/^data:\s+/, "");
242- try {
243- const data = JSON.parse(dataStr);
244- data.results.forEach((result: any) => {
245- generatedChunk += result.generated_text || "";
246- });
247- } catch (e) {
248- // parsing error is expected with streaming response
249- // console.error(`Error parsing JSON string: ${dataStr}`, e);
250- }
220+ for await (const value of streamResponse(response)) {
221+ const lines = value.split("\n");
222+ let generatedChunk = "";
223+ let generatedTextIndex = undefined;
224+ lines.forEach((el: string) => {
225+ // console.log(`${el}`);
226+ if (el.startsWith("id:")) {
227+ generatedTextIndex = parseInt(el.replace(/^id:\s+/, ""));
228+ if (isNaN(generatedTextIndex)) {
229+ console.error(`Unable to parse stream chunk ID: ${el}`);
251230 }
252- });
253- yield generatedChunk
254- }
231+ } else if (el.startsWith("data:")) {
232+ const dataStr = el.replace(/^data:\s+/, "");
233+ try {
234+ const data = JSON.parse(dataStr);
235+ data.results.forEach((result: any) => {
236+ generatedChunk += result.generated_text || "";
237+ });
238+ } catch (e) {
239+ // parsing error is expected with streaming response
240+ // console.error(`Error parsing JSON string: ${dataStr}`, e);
241+ }
242+ }
243+ });
244+ yield generatedChunk;
255245 }
256246 }
257247
@@ -267,7 +257,7 @@
267257 const headers = this._getHeaders();
268258
269259 const payload: any = {
270- messages: messages,
260+ messages: messages,
271261 max_tokens: options.maxTokens ?? 1024,
272262 stop: stopSequences,
273263 frequency_penalty: options.frequencyPenalty || 1,
@@ -281,36 +271,30 @@
281271
282272 if (!!options.temperature) {
283273 payload.temperature = options.temperature;
284- }
274+ }
285275 if (!!options.topP) {
286276 payload.top_p = options.topP;
287277 }
288278 if (!!options.tools) {
289279 payload.tools = options.tools;
290280 if (options.toolChoice) {
291- payload.tool_choice = options.toolChoice;
281+ payload.tool_choice = options.toolChoice;
292282 } else {
293- payload.tool_choice_option = "auto";
283+ payload.tool_choice_option = "auto";
294284 }
295285 }
296286
297- var response = await this.fetch(url, {
287+ const response = await this.fetch(url, {
298288 method: "POST",
299289 headers: headers,
300290 body: JSON.stringify(payload),
301291 signal,
302292 });
303293
304- if (!response.ok || response.body === null) {
305- throw new Error(
306- "Something went wrong. No response received, check your connection",
307- );
308- } else {
309- for await (const value of streamSse(response)) {
310- const chunk = fromChatCompletionChunk(value);
311- if (chunk) {
312- yield chunk;
313- }
294+ for await (const value of streamSse(response)) {
295+ const chunk = fromChatCompletionChunk(value);
296+ if (chunk) {
297+ yield chunk;
314298 }
315299 }
316300 }
modified core/llm/llms/stubs/ContinueProxy.ts +15 −0
@@ -1,6 +1,7 @@
11 import {
22 ContinueProperties,
33 decodeSecretLocation,
4+ parseProxyModelName,
45 SecretType,
56 } from "@continuedev/config-yaml";
67
@@ -27,8 +28,12 @@
2728 // to call whatever LLM API is chosen
2829 private actualApiBase?: string;
2930
31+ // Contains extra properties that we pass along to the proxy. Originally from `env` property on LLMOptions
32+ private configEnv?: Record<string, any>;
33+
3034 constructor(options: LLMOptions) {
3135 super(options);
36+ this.configEnv = options.env;
3237 this.actualApiBase = options.apiBase;
3338 this.apiKeyLocation = options.apiKeyLocation;
3439 this.orgScopeId = options.orgScopeId;
@@ -43,11 +48,17 @@
4348 useLegacyCompletionsEndpoint: false,
4449 };
4550
51+ get underlyingProviderName(): string {
52+ const { provider } = parseProxyModelName(this.model);
53+ return provider;
54+ }
55+
4656 protected extraBodyProperties(): Record<string, any> {
4757 const continueProperties: ContinueProperties = {
4858 apiKeyLocation: this.apiKeyLocation,
4959 apiBase: this.actualApiBase,
5060 orgScopeId: this.orgScopeId ?? null,
61+ env: this.configEnv,
5162 };
5263 return {
5364 continueProperties,
@@ -78,6 +89,10 @@
7889 }
7990
8091 supportsFim(): boolean {
92+ const { provider } = parseProxyModelName(this.model);
93+ if (provider === "vllm") {
94+ return false;
95+ }
8196 return true;
8297 }
8398
added core/llm/llms/test/supportsFim.test.ts +55 −0
@@ -0,0 +1,55 @@
1+import { jest } from "@jest/globals";
2+import Anthropic from "../Anthropic.js";
3+import Deepseek from "../Deepseek.js";
4+import FunctionNetwork from "../FunctionNetwork.js";
5+import Mistral from "../Mistral.js";
6+import OpenAI from "../OpenAI.js";
7+import ContinueProxy from "../stubs/ContinueProxy.js";
8+import Vllm from "../Vllm.js";
9+
10+// Mock the parseProxyModelName function
11+const mockParseProxyModelName = jest.fn();
12+jest.mock("@continuedev/config-yaml", () => ({
13+ parseProxyModelName: mockParseProxyModelName,
14+ decodeSecretLocation: jest.fn(),
15+ SecretType: { NotFound: "not-found" },
16+}));
17+
18+// Test cases: [LLM class, model, expected supportsFim result, description]
19+const testCases: [any, string, boolean, string][] = [
20+ [ContinueProxy, "owner/package/vllm/some-model", false, "vllm provider"],
21+ [ContinueProxy, "owner/package/openai/gpt-4", true, "openai provider"],
22+ [
23+ ContinueProxy,
24+ "owner/package/anthropic/claude-3",
25+ true,
26+ "anthropic provider",
27+ ],
28+ [ContinueProxy, "owner/package/cohere/command-r", true, "cohere provider"],
29+ [
30+ ContinueProxy,
31+ "owner/package/unknown-provider/some-model",
32+ true,
33+ "unknown provider",
34+ ],
35+ [ContinueProxy, "owner/package/groq/llama-model", true, "groq provider"],
36+ [Vllm, "any-model", false, "Vllm"],
37+ [Anthropic, "claude-3-5-sonnet-latest", false, "Anthropic"],
38+ [FunctionNetwork, "any-model", false, "FunctionNetwork"],
39+ [OpenAI, "codestral", false, "OpenAI"],
40+ [Mistral, "codestral", true, "Mistral"],
41+ [Deepseek, "deepseek-chat", true, "Deepseek"],
42+];
43+
44+testCases.forEach(([LLMClass, model, expectedResult, description]) => {
45+ test(`supportsFim returns ${expectedResult} for ${description}`, () => {
46+ const llm = new LLMClass({
47+ model,
48+ apiKey: "test-key",
49+ });
50+
51+ const result = llm.supportsFim();
52+
53+ expect(result).toBe(expectedResult);
54+ });
55+});
deleted core/llm/stream.test.ts +0 −72
@@ -1,72 +0,0 @@
1-import { Readable } from "stream";
2-import { streamSse } from "./stream";
3-
4-function createMockResponse(sseLines: string[]): Response {
5- // Create a Readable stream that emits the SSE lines
6- const stream = new Readable({
7- read() {
8- for (const line of sseLines) {
9- this.push(line + "\n\n");
10- }
11- this.push(null); // End of stream
12- }
13- }) as any;
14-
15- // Minimal Response mock
16- return {
17- status: 200,
18- body: stream,
19- text: async () => "",
20- } as unknown as Response;
21-}
22-
23-describe("streamSse", () => {
24- it("yields parsed SSE data objects that ends with `data:[DONE]`", async () => {
25- const sseLines = [
26- 'data: {"foo": "bar"}',
27- 'data: {"baz": 42}',
28- 'data:[DONE]'
29- ];
30- const response = createMockResponse(sseLines);
31-
32- const results = [];
33- for await (const data of streamSse(response)) {
34- results.push(data);
35- }
36-
37- expect(results).toEqual([
38- { foo: "bar" },
39- { baz: 42 }
40- ]);
41- });
42-
43- it("yields parsed SSE data objects that ends with `data: [DONE]` (with a space before [DONE]", async () => {
44- const sseLines = [
45- 'data: {"foo": "bar"}',
46- 'data: {"baz": 42}',
47- 'data: [DONE]'
48- ];
49- const response = createMockResponse(sseLines);
50-
51- const results = [];
52- for await (const data of streamSse(response)) {
53- results.push(data);
54- }
55-
56- expect(results).toEqual([
57- { foo: "bar" },
58- { baz: 42 }
59- ]);
60- });
61-
62- it("throws on malformed JSON", async () => {
63- const sseLines = [
64- 'data: {"foo": "bar"',
65- 'data:[DONE]'
66- ];
67- const response = createMockResponse(sseLines);
68-
69- const iterator = streamSse(response)[Symbol.asyncIterator]();
70- await expect(iterator.next()).rejects.toThrow(/Malformed JSON/);
71- });
72-});
modified core/llm/stream.ts +1 −1
@@ -1,4 +1,4 @@
1-async function* toAsyncIterable(
1+export async function* toAsyncIterable(
22 nodeReadable: NodeJS.ReadableStream,
33 ): AsyncGenerator<Uint8Array> {
44 for await (const chunk of nodeReadable) {
modified core/llm/streamChat.ts +27 −35
@@ -8,7 +8,7 @@
88
99 export async function* llmStreamChat(
1010 configHandler: ConfigHandler,
11- abortedMessageIds: Set<string>,
11+ abortController: AbortController,
1212 msg: Message<ToCoreProtocol["llm/streamChat"][0]>,
1313 ide: IDE,
1414 messenger: IMessenger<ToCoreProtocol, FromCoreProtocol>,
@@ -75,52 +75,44 @@
7575 selectedCode,
7676 config,
7777 fetch: (url, init) =>
78- fetchwithRequestOptions(url, init, config.requestOptions),
78+ fetchwithRequestOptions(
79+ url,
80+ {
81+ ...init,
82+ signal: abortController.signal,
83+ },
84+ config.requestOptions,
85+ ),
7986 completionOptions,
8087 });
81- const checkActiveInterval = setInterval(() => {
82- if (abortedMessageIds.has(msg.messageId)) {
83- abortedMessageIds.delete(msg.messageId);
84- clearInterval(checkActiveInterval);
85- }
86- }, 100);
87- try {
88- let next = await gen.next();
89- while (!next.done) {
90- if (abortedMessageIds.has(msg.messageId)) {
91- abortedMessageIds.delete(msg.messageId);
92- next = await gen.return(errorPromptLog);
93- clearInterval(checkActiveInterval);
94- break;
95- }
96- if (next.value) {
97- yield {
98- role: "assistant",
99- content: next.value,
100- };
101- }
102- next = await gen.next();
88+ let next = await gen.next();
89+ while (!next.done) {
90+ if (abortController.signal.aborted) {
91+ next = await gen.return(errorPromptLog);
92+ break;
10393 }
104- if (!next.done) {
105- throw new Error("Will never happen");
94+ if (next.value) {
95+ yield {
96+ role: "assistant",
97+ content: next.value,
98+ };
10699 }
107-
108- return next.value;
109- } catch (e) {
110- throw e;
111- } finally {
112- clearInterval(checkActiveInterval);
100+ next = await gen.next();
113101 }
102+ if (!next.done) {
103+ throw new Error("Will never happen");
104+ }
105+
106+ return next.value;
114107 } else {
115108 const gen = model.streamChat(
116109 messages,
117- new AbortController().signal,
110+ abortController.signal,
118111 completionOptions,
119112 );
120113 let next = await gen.next();
121114 while (!next.done) {
122- if (abortedMessageIds.has(msg.messageId)) {
123- abortedMessageIds.delete(msg.messageId);
115+ if (abortController.signal.aborted) {
124116 next = await gen.return(errorPromptLog);
125117 break;
126118 }
modified core/llm/toolSupport.test.ts +76 −40
@@ -6,39 +6,57 @@
66 const supportsFn = PROVIDER_TOOL_SUPPORT["continue-proxy"];
77
88 it("should return true for Claude 3.5 models", () => {
9- expect(supportsFn("claude-3-5-sonnet")).toBe(true);
10- expect(supportsFn("claude-3.5-sonnet")).toBe(true);
9+ expect(
10+ supportsFn("ownerSlug/packageSlug/anthropic/claude-3-5-sonnet"),
11+ ).toBe(true);
12+ expect(
13+ supportsFn("ownerSlug/packageSlug/anthropic/claude-3.5-sonnet"),
14+ ).toBe(true);
1115 });
1216
1317 it("should return true for Claude 3.7 models", () => {
14- expect(supportsFn("claude-3-7-haiku")).toBe(true);
15- expect(supportsFn("claude-3.7-sonnet")).toBe(true);
18+ expect(
19+ supportsFn("ownerSlug/packageSlug/anthropic/claude-3-7-haiku"),
20+ ).toBe(true);
21+ expect(
22+ supportsFn("ownerSlug/packageSlug/anthropic/claude-3.7-sonnet"),
23+ ).toBe(true);
1624 });
1725
1826 it("should return true for GPT-4 models", () => {
19- expect(supportsFn("gpt-4-turbo")).toBe(true);
20- expect(supportsFn("gpt-4-1106-preview")).toBe(true);
27+ expect(supportsFn("ownerSlug/packageSlug/openai/gpt-4-turbo")).toBe(true);
28+ expect(
29+ supportsFn("ownerSlug/packageSlug/openai/gpt-4-1106-preview"),
30+ ).toBe(true);
2131 });
2232
2333 it("should return true for O3 models", () => {
24- expect(supportsFn("o3-preview")).toBe(true);
34+ expect(supportsFn("ownerSlug/packageSlug/openai/o3-preview")).toBe(true);
2535 });
2636
2737 it("should return true for Gemini models", () => {
28- expect(supportsFn("gemini-pro")).toBe(true);
29- expect(supportsFn("gemini-1.5-pro")).toBe(true);
38+ expect(supportsFn("ownerSlug/packageSlug/gemini/gemini-pro")).toBe(true);
39+ expect(supportsFn("ownerSlug/packageSlug/gemini/gemini-1.5-pro")).toBe(
40+ true,
41+ );
3042 });
3143
3244 it("should return false for unsupported models", () => {
33- expect(supportsFn("gpt-3.5-turbo")).toBe(false);
34- expect(supportsFn("claude-2")).toBe(false);
35- expect(supportsFn("llama-3")).toBe(false);
45+ expect(supportsFn("ownerSlug/packageSlug/openai/gpt-3.5-turbo")).toBe(
46+ false,
47+ );
48+ expect(supportsFn("ownerSlug/packageSlug/anthropic/claude-2")).toBe(
49+ false,
50+ );
51+ expect(supportsFn("ownerSlug/packageSlug/together/llama-3")).toBe(false);
3652 });
3753
3854 it("should handle case insensitivity", () => {
39- expect(supportsFn("CLAUDE-3-5-sonnet")).toBe(true);
40- expect(supportsFn("GPT-4-turbo")).toBe(true);
41- expect(supportsFn("GEMINI-pro")).toBe(true);
55+ expect(
56+ supportsFn("ownerSlug/packageSlug/anthropic/CLAUDE-3-5-sonnet"),
57+ ).toBe(true);
58+ expect(supportsFn("ownerSlug/packageSlug/openai/GPT-4-turbo")).toBe(true);
59+ expect(supportsFn("ownerSlug/packageSlug/gemini/GEMINI-pro")).toBe(true);
4260 });
4361 });
4462
@@ -56,8 +74,8 @@
5674 });
5775
5876 it("should return undefined for unsupported models", () => {
59- expect(supportsFn("claude-2")).toBeUndefined();
60- expect(supportsFn("claude-instant")).toBeUndefined();
77+ expect(supportsFn("claude-2")).toBe(false);
78+ expect(supportsFn("claude-instant")).toBe(false);
6179 });
6280
6381 it("should handle case insensitivity", () => {
@@ -81,8 +99,8 @@
8199 });
82100
83101 it("should return undefined for unsupported models", () => {
84- expect(supportsFn("gpt-3.5-turbo")).toBeUndefined();
85- expect(supportsFn("davinci")).toBeUndefined();
102+ expect(supportsFn("gpt-3.5-turbo")).toBe(false);
103+ expect(supportsFn("davinci")).toBe(false);
86104 });
87105
88106 it("should handle case insensitivity", () => {
@@ -115,31 +133,49 @@
115133 const supportsFn = PROVIDER_TOOL_SUPPORT["bedrock"];
116134
117135 it("should return true for Claude 3.5 Sonnet models", () => {
118- expect(supportsFn("anthropic.claude-3-5-sonnet-20240620-v1:0")).toBe(true);
119- expect(supportsFn("anthropic.claude-3.5-sonnet-20240620-v1:0")).toBe(true);
136+ expect(supportsFn("anthropic.claude-3-5-sonnet-20240620-v1:0")).toBe(
137+ true,
138+ );
139+ expect(supportsFn("anthropic.claude-3.5-sonnet-20240620-v1:0")).toBe(
140+ true,
141+ );
120142 });
121143
122144 it("should return true for Claude 3.7 Sonnet models", () => {
123- expect(supportsFn("anthropic.claude-3-7-sonnet-20240620-v1:0")).toBe(true);
124- expect(supportsFn("anthropic.claude-3.7-sonnet-20240620-v1:0")).toBe(true);
145+ expect(supportsFn("anthropic.claude-3-7-sonnet-20240620-v1:0")).toBe(
146+ true,
147+ );
148+ expect(supportsFn("anthropic.claude-3.7-sonnet-20240620-v1:0")).toBe(
149+ true,
150+ );
125151 });
126152
127153 it("should return undefined for Claude Haiku and Opus models", () => {
128- expect(supportsFn("anthropic.claude-3-5-haiku-20240307-v1:0")).toBeUndefined();
129- expect(supportsFn("anthropic.claude-3.5-haiku-20240620-v1:0")).toBeUndefined();
130- expect(supportsFn("anthropic.claude-3-7-haiku-20240620-v1:0")).toBeUndefined();
131- expect(supportsFn("anthropic.claude-3-5-opus-20240620-v1:0")).toBeUndefined();
132- expect(supportsFn("anthropic.claude-3.7-opus-20240620-v1:0")).toBeUndefined();
154+ expect(supportsFn("anthropic.claude-3-5-haiku-20240307-v1:0")).toBe(
155+ false,
156+ );
157+ expect(supportsFn("anthropic.claude-3.5-haiku-20240620-v1:0")).toBe(
158+ false,
159+ );
160+ expect(supportsFn("anthropic.claude-3-7-haiku-20240620-v1:0")).toBe(
161+ false,
162+ );
163+ expect(supportsFn("anthropic.claude-3-5-opus-20240620-v1:0")).toBe(false);
164+ expect(supportsFn("anthropic.claude-3.7-opus-20240620-v1:0")).toBe(false);
133165 });
134166
135167 it("should return undefined for other unsupported models", () => {
136- expect(supportsFn("anthropic.claude-instant-v1")).toBeUndefined();
137- expect(supportsFn("anthropic.titan-text-express-v1")).toBeUndefined();
168+ expect(supportsFn("anthropic.claude-instant-v1")).toBe(false);
169+ expect(supportsFn("anthropic.titan-text-express-v1")).toBe(false);
138170 });
139171
140172 it("should handle case insensitivity", () => {
141- expect(supportsFn("ANTHROPIC.CLAUDE-3-5-SONNET-20240620-v1:0")).toBe(true);
142- expect(supportsFn("ANTHROPIC.CLAUDE-3.7-SONNET-20240620-v1:0")).toBe(true);
173+ expect(supportsFn("ANTHROPIC.CLAUDE-3-5-SONNET-20240620-v1:0")).toBe(
174+ true,
175+ );
176+ expect(supportsFn("ANTHROPIC.CLAUDE-3.7-SONNET-20240620-v1:0")).toBe(
177+ true,
178+ );
143179 });
144180 });
145181
@@ -206,9 +242,9 @@
206242 });
207243
208244 it("should return undefined for other models", () => {
209- expect(supportsFn("llama2")).toBeUndefined();
210- expect(supportsFn("phi-2")).toBeUndefined();
211- expect(supportsFn("falcon")).toBeUndefined();
245+ expect(supportsFn("llama2")).toBe(false);
246+ expect(supportsFn("phi-2")).toBe(false);
247+ expect(supportsFn("falcon")).toBe(false);
212248 });
213249
214250 it("should handle case insensitivity", () => {
@@ -221,16 +257,16 @@
221257 describe("edge cases", () => {
222258 it("should handle empty model names", () => {
223259 expect(PROVIDER_TOOL_SUPPORT["continue-proxy"]("")).toBe(false);
224- expect(PROVIDER_TOOL_SUPPORT["anthropic"]("")).toBeUndefined();
225- expect(PROVIDER_TOOL_SUPPORT["openai"]("")).toBeUndefined();
260+ expect(PROVIDER_TOOL_SUPPORT["anthropic"]("")).toBe(false);
261+ expect(PROVIDER_TOOL_SUPPORT["openai"]("")).toBe(false);
226262 expect(PROVIDER_TOOL_SUPPORT["gemini"]("")).toBe(false);
227- expect(PROVIDER_TOOL_SUPPORT["bedrock"]("")).toBeUndefined();
228- expect(PROVIDER_TOOL_SUPPORT["ollama"]("")).toBeUndefined();
263+ expect(PROVIDER_TOOL_SUPPORT["bedrock"]("")).toBe(false);
264+ expect(PROVIDER_TOOL_SUPPORT["ollama"]("")).toBe(false);
229265 });
230266
231267 it("should handle non-existent provider", () => {
232268 // @ts-ignore - Testing runtime behavior with invalid provider
233- expect(PROVIDER_TOOL_SUPPORT["non-existent"]).toBeUndefined();
269+ expect(PROVIDER_TOOL_SUPPORT["non-existent"]).toBe(undefined);
234270 });
235271 });
236272 });
modified core/llm/toolSupport.ts +259 −222
@@ -1,237 +1,274 @@
1-export const PROVIDER_TOOL_SUPPORT: Record<
2- string,
3- (model: string) => boolean | undefined
4-> = {
5- "continue-proxy": (model) => {
6- // see getContinueProxyModelName
7- const provider = model.split("/")[2];
8- const _model = model.split("/")[3];
9- if (provider && _model && provider !== "continue-proxy") {
10- const fn = PROVIDER_TOOL_SUPPORT[provider];
11- if (fn) {
12- return fn(_model);
1+import { parseProxyModelName } from "@continuedev/config-yaml";
2+
3+export const PROVIDER_TOOL_SUPPORT: Record<string, (model: string) => boolean> =
4+ {
5+ "continue-proxy": (model) => {
6+ try {
7+ const { provider, model: _model } = parseProxyModelName(model);
8+ if (provider && _model && provider !== "continue-proxy") {
9+ const fn = PROVIDER_TOOL_SUPPORT[provider];
10+ if (fn) {
11+ return fn(_model);
12+ }
13+ }
14+ } catch (e) {}
15+
16+ return [
17+ "claude-3-5",
18+ "claude-3.5",
19+ "claude-3-7",
20+ "claude-3.7",
21+ "claude-sonnet-4",
22+ "gpt-4",
23+ "o3",
24+ "gemini",
25+ ].some((part) => model.toLowerCase().startsWith(part));
26+ },
27+ anthropic: (model) => {
28+ if (
29+ [
30+ "claude-3-5",
31+ "claude-3.5",
32+ "claude-3-7",
33+ "claude-3.7",
34+ "claude-sonnet-4",
35+ ].some((part) => model.toLowerCase().startsWith(part))
36+ ) {
37+ return true;
1338 }
14- }
15- return [
16- "claude-3-5",
17- "claude-3.5",
18- "claude-3-7",
19- "claude-3.7",
20- "gpt-4",
21- "o3",
22- "gemini",
23- ].some((part) => model.toLowerCase().startsWith(part));
24- },
25- anthropic: (model) => {
26- if (
27- ["claude-3-5", "claude-3.5", "claude-3-7", "claude-3.7"].some((part) =>
28- model.toLowerCase().startsWith(part),
39+
40+ return false;
41+ },
42+ azure: (model) => {
43+ if (
44+ model.toLowerCase().startsWith("gpt-4") ||
45+ model.toLowerCase().startsWith("o3")
2946 )
30- ) {
31- return true;
32- }
33- },
34- azure: (model) => {
35- if (
36- model.toLowerCase().startsWith("gpt-4") ||
37- model.toLowerCase().startsWith("o3")
38- )
39- return true;
40- return false;
41- },
42- openai: (model) => {
43- // https://platform.openai.com/docs/guides/function-calling#models-supporting-function-calling
44- if (
45- model.toLowerCase().startsWith("gpt-4") ||
46- model.toLowerCase().startsWith("o3")
47- ) {
48- return true;
49- }
50- // firworks-ai https://docs.fireworks.ai/guides/function-calling
51- if (model.startsWith("accounts/fireworks/models/")) {
52- switch (model.substring(26)) {
53- case "llama-v3p1-405b-instruct":
54- case "llama-v3p1-70b-instruct":
55- case "qwen2p5-72b-instruct":
56- case "firefunction-v1":
57- case "firefunction-v2":
58- return true;
59- default:
60- return false;
47+ return true;
48+ return false;
49+ },
50+ openai: (model) => {
51+ // https://platform.openai.com/docs/guides/function-calling#models-supporting-function-calling
52+ if (
53+ model.toLowerCase().startsWith("gpt-4") ||
54+ model.toLowerCase().startsWith("o3")
55+ ) {
56+ return true;
57+ }
58+ // firworks-ai https://docs.fireworks.ai/guides/function-calling
59+ if (model.startsWith("accounts/fireworks/models/")) {
60+ switch (model.substring(26)) {
61+ case "llama-v3p1-405b-instruct":
62+ case "llama-v3p1-70b-instruct":
63+ case "qwen2p5-72b-instruct":
64+ case "firefunction-v1":
65+ case "firefunction-v2":
66+ return true;
67+ default:
68+ return false;
69+ }
6170 }
62- }
63- },
64- gemini: (model) => {
65- // All gemini models support function calling
66- return model.toLowerCase().includes("gemini");
67- },
68- vertexai: (model) => {
69- // All gemini models except flash 2.0 lite support function calling
70- return (
71- model.toLowerCase().includes("gemini") &&
72- !model.toLowerCase().includes("lite")
73- );
74- },
75- bedrock: (model) => {
76- // For Bedrock, only support Claude Sonnet models with versions 3.5/3-5 and 3.7/3-7
77- if (
78- model.toLowerCase().includes("sonnet") &&
79- ["claude-3-5", "claude-3.5", "claude-3-7", "claude-3.7"].some((part) =>
80- model.toLowerCase().includes(part),
81- )
82- ) {
83- return true;
84- }
85- },
86- mistral: (model) => {
87- // https://docs.mistral.ai/capabilities/function_calling/
88- return (
89- !model.toLowerCase().includes("mamba") &&
90- [
91- "devstral",
92- "codestral",
93- "mistral-large",
94- "mistral-small",
95- "pixtral",
96- "ministral",
97- "mistral-nemo",
98- ].some((part) => model.toLowerCase().includes(part))
99- );
100- },
101- // https://ollama.com/search?c=tools
102- ollama: (model) => {
103- let modelName = "";
104- // Extract the model name after the last slash to support other registries
105- if (model.includes("/")) {
106- let parts = model.split("/");
107- modelName = parts[parts.length - 1];
108- } else {
109- modelName = model;
110- }
11171
112- if (
113- ["vision", "math", "guard", "mistrallite", "mistral-openorca"].some(
114- (part) => modelName.toLowerCase().includes(part),
115- )
116- ) {
11772 return false;
118- }
119- if (
120- [
121- "cogito",
122- "llama3.3",
123- "qwq",
124- "llama3.2",
125- "llama3.1",
126- "qwen2",
127- "qwen3",
128- "mixtral",
129- "command-r",
130- "smollm2",
131- "hermes3",
132- "athene-v2",
133- "nemotron",
134- "llama3-groq",
135- "granite3",
136- "granite-3",
137- "aya-expanse",
138- "firefunction-v2",
139- "mistral",
140- "devstral",
141- ].some((part) => modelName.toLowerCase().includes(part))
142- ) {
143- return true;
144- }
145- },
146- sambanova: (model) => {
147- // https://docs.sambanova.ai/cloud/docs/capabilities/function-calling
148- if (
149- model.toLowerCase().startsWith("meta-llama-3") ||
150- model.toLowerCase().includes("llama-4") ||
151- model.toLowerCase().includes("deepseek")
152- ) {
153- return true;
154- }
155- },
156- deepseek: (model) => {
157- if (model !== "deepseek-reasoner") {
158- return true;
159- }
160- },
161- watsonx: (model) => {
162- if (model.toLowerCase().includes("guard")) return false;
163- if (
164- ["llama-3", "llama-4", "mistral", "codestral", "granite-3"].some((part) =>
165- model.toLowerCase().includes(part),
166- )
167- )
168- return true;
169- },
170- openrouter: (model) => {
171- // https://openrouter.ai/models?fmt=cards&supported_parameters=tools
172- if (
173- ["vision", "math", "guard", "mistrallite", "mistral-openorca"].some(
174- (part) => model.toLowerCase().includes(part),
175- )
176- ) {
73+ },
74+ gemini: (model) => {
75+ // All gemini models support function calling
76+ return model.toLowerCase().includes("gemini");
77+ },
78+ vertexai: (model) => {
79+ // All gemini models except flash 2.0 lite support function calling
80+ return (
81+ model.toLowerCase().includes("gemini") &&
82+ !model.toLowerCase().includes("lite")
83+ );
84+ },
85+ bedrock: (model) => {
86+ // For Bedrock, only support Claude Sonnet models with versions 3.5/3-5 and 3.7/3-7
87+ if (
88+ model.toLowerCase().includes("sonnet") &&
89+ [
90+ "claude-3-5",
91+ "claude-3.5",
92+ "claude-3-7",
93+ "claude-3.7",
94+ "claude-sonnet-4",
95+ ].some((part) => model.toLowerCase().includes(part))
96+ ) {
97+ return true;
98+ }
99+
177100 return false;
178- }
101+ },
102+ mistral: (model) => {
103+ // https://docs.mistral.ai/capabilities/function_calling/
104+ return (
105+ !model.toLowerCase().includes("mamba") &&
106+ [
107+ "devstral",
108+ "codestral",
109+ "mistral-large",
110+ "mistral-small",
111+ "pixtral",
112+ "ministral",
113+ "mistral-nemo",
114+ "devstral",
115+ ].some((part) => model.toLowerCase().includes(part))
116+ );
117+ },
118+ // https://ollama.com/search?c=tools
119+ ollama: (model) => {
120+ let modelName = "";
121+ // Extract the model name after the last slash to support other registries
122+ if (model.includes("/")) {
123+ let parts = model.split("/");
124+ modelName = parts[parts.length - 1];
125+ } else {
126+ modelName = model;
127+ }
128+
129+ if (
130+ ["vision", "math", "guard", "mistrallite", "mistral-openorca"].some(
131+ (part) => modelName.toLowerCase().includes(part),
132+ )
133+ ) {
134+ return false;
135+ }
136+ if (
137+ [
138+ "cogito",
139+ "llama3.3",
140+ "qwq",
141+ "llama3.2",
142+ "llama3.1",
143+ "qwen2",
144+ "qwen3",
145+ "mixtral",
146+ "command-r",
147+ "smollm2",
148+ "hermes3",
149+ "athene-v2",
150+ "nemotron",
151+ "llama3-groq",
152+ "granite3",
153+ "granite-3",
154+ "aya-expanse",
155+ "firefunction-v2",
156+ "mistral",
157+ "devstral",
158+ ].some((part) => modelName.toLowerCase().includes(part))
159+ ) {
160+ return true;
161+ }
179162
180- const supportedPrefixes = [
181- "openai/gpt-3.5",
182- "openai/gpt-4",
183- "openai/o1",
184- "openai/o3",
185- "openai/o4",
186- "anthropic/claude-3",
187- "microsoft/phi-3",
188- "google/gemini-flash-1.5",
189- "google/gemini-2",
190- "google/gemini-pro",
191- "x-ai/grok",
192- "qwen/qwen3",
193- "qwen/qwen-",
194- "cohere/command-r",
195- "ai21/jamba-1.6",
196- "mistralai/mistral",
197- "mistralai/ministral",
198- "mistralai/codestral",
199- "mistralai/mixtral",
200- "mistral/ministral",
201- "mistralai/pixtral",
202- "meta-llama/llama-3.3",
203- "amazon/nova",
204- "deepseek/deepseek-r1",
205- "deepseek/deepseek-chat",
206- "meta-llama/llama-4",
207- "all-hands/openhands-lm-32b",
208- ];
209- for (const prefix of supportedPrefixes) {
210- if (model.toLowerCase().startsWith(prefix)) {
163+ return false;
164+ },
165+ sambanova: (model) => {
166+ // https://docs.sambanova.ai/cloud/docs/capabilities/function-calling
167+ if (
168+ model.toLowerCase().startsWith("meta-llama-3") ||
169+ model.toLowerCase().includes("llama-4") ||
170+ model.toLowerCase().includes("deepseek")
171+ ) {
211172 return true;
212173 }
213- }
214174
215- const specificModels = [
216- "qwen/qwq-32b",
217- "qwen/qwen-2.5-72b-instruct",
218- "meta-llama/llama-3.2-3b-instruct",
219- "meta-llama/llama-3-8b-instruct",
220- "meta-llama/llama-3-70b-instruct",
221- "arcee-ai/caller-large",
222- "nousresearch/hermes-3-llama-3.1-70b",
223- ];
224- for (const model of specificModels) {
225- if (model.toLowerCase() === model) {
175+ return false;
176+ },
177+ deepseek: (model) => {
178+ if (model !== "deepseek-reasoner") {
226179 return true;
227180 }
228- }
229181
230- const supportedContains = ["llama-3.1"];
231- for (const model of supportedContains) {
232- if (model.toLowerCase().includes(model)) {
182+ return false;
183+ },
184+ watsonx: (model) => {
185+ if (model.toLowerCase().includes("guard")) {
186+ return false;
187+ }
188+ if (
189+ [
190+ "llama-3",
191+ "llama-4",
192+ "mistral",
193+ "codestral",
194+ "granite-3",
195+ "devstral",
196+ ].some((part) => model.toLowerCase().includes(part))
197+ ) {
233198 return true;
234199 }
235- }
236- },
237-};
200+
201+ return false;
202+ },
203+ openrouter: (model) => {
204+ // https://openrouter.ai/models?fmt=cards&supported_parameters=tools
205+ if (
206+ ["vision", "math", "guard", "mistrallite", "mistral-openorca"].some(
207+ (part) => model.toLowerCase().includes(part),
208+ )
209+ ) {
210+ return false;
211+ }
212+
213+ const supportedPrefixes = [
214+ "openai/gpt-3.5",
215+ "openai/gpt-4",
216+ "openai/o1",
217+ "openai/o3",
218+ "openai/o4",
219+ "anthropic/claude-3",
220+ "anthropic/claude-4",
221+ "microsoft/phi-3",
222+ "google/gemini-flash-1.5",
223+ "google/gemini-2",
224+ "google/gemini-pro",
225+ "x-ai/grok",
226+ "qwen/qwen3",
227+ "qwen/qwen-",
228+ "cohere/command-r",
229+ "ai21/jamba-1.6",
230+ "mistralai/mistral",
231+ "mistralai/ministral",
232+ "mistralai/codestral",
233+ "mistralai/mixtral",
234+ "mistral/ministral",
235+ "mistral/devstral",
236+ "mistralai/pixtral",
237+ "meta-llama/llama-3.3",
238+ "amazon/nova",
239+ "deepseek/deepseek-r1",
240+ "deepseek/deepseek-chat",
241+ "meta-llama/llama-4",
242+ "all-hands/openhands-lm-32b",
243+ ];
244+ for (const prefix of supportedPrefixes) {
245+ if (model.toLowerCase().startsWith(prefix)) {
246+ return true;
247+ }
248+ }
249+
250+ const specificModels = [
251+ "qwen/qwq-32b",
252+ "qwen/qwen-2.5-72b-instruct",
253+ "meta-llama/llama-3.2-3b-instruct",
254+ "meta-llama/llama-3-8b-instruct",
255+ "meta-llama/llama-3-70b-instruct",
256+ "arcee-ai/caller-large",
257+ "nousresearch/hermes-3-llama-3.1-70b",
258+ ];
259+ for (const model of specificModels) {
260+ if (model.toLowerCase() === model) {
261+ return true;
262+ }
263+ }
264+
265+ const supportedContains = ["llama-3.1"];
266+ for (const model of supportedContains) {
267+ if (model.toLowerCase().includes(model)) {
268+ return true;
269+ }
270+ }
271+
272+ return false;
273+ },
274+ };
modified core/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 core/package.json +3 −3
@@ -49,10 +49,10 @@
4949 "@aws-sdk/credential-providers": "^3.778.0",
5050 "@continuedev/config-types": "^1.0.13",
5151 "@continuedev/config-yaml": "file:../packages/config-yaml",
52- "@continuedev/fetch": "^1.0.6",
52+ "@continuedev/fetch": "^1.0.10",
5353 "@continuedev/llm-info": "^1.0.8",
54- "@continuedev/openai-adapters": "^1.0.19",
55- "@modelcontextprotocol/sdk": "^1.5.0",
54+ "@continuedev/openai-adapters": "^1.0.25",
55+ "@modelcontextprotocol/sdk": "^1.12.0",
5656 "@mozilla/readability": "^0.5.0",
5757 "@octokit/rest": "^20.1.1",
5858 "@typescript-eslint/eslint-plugin": "^7.8.0",
modified core/protocol/core.ts +1 −0
@@ -46,6 +46,7 @@
4646 // Special
4747 ping: [string, string];
4848 abort: [undefined, void];
49+ cancelApply: [undefined, void];
4950
5051 // History
5152 "history/list": [ListHistoryOptions, SessionMetadata[]];
modified core/protocol/ideWebview.ts +3 −3
@@ -2,12 +2,12 @@
22 import { ToWebviewFromIdeOrCoreProtocol } from "./webview";
33
44 import {
5+ AcceptOrRejectDiffPayload,
56 ApplyState,
6- SetCodeToEditPayload,
77 HighlightedCodePayload,
88 MessageContent,
99 RangeInFileWithContents,
10- AcceptOrRejectDiffPayload,
10+ SetCodeToEditPayload,
1111 ShowFilePayload,
1212 } from "../";
1313
@@ -42,7 +42,7 @@
4242 vscMediaUrl: string;
4343 },
4444 ];
45- "jetbrains/getColors": [undefined, Record<string, string>];
45+ "jetbrains/getColors": [undefined, Record<string, string | null | undefined>];
4646 "vscode/openMoveRightMarkdown": [undefined, void];
4747 setGitHubAuthToken: [{ token: string }, void];
4848 acceptDiff: [AcceptOrRejectDiffPayload, void];
modified core/protocol/webview.ts +1 −1
@@ -40,7 +40,7 @@
4040 setTTSActive: [boolean, void];
4141 getWebviewHistoryLength: [undefined, number];
4242 getCurrentSessionId: [undefined, string];
43- "jetbrains/setColors": [Record<string, string>, void];
43+ "jetbrains/setColors": [Record<string, string | null | undefined>, void];
4444 sessionUpdate: [{ sessionInfo: ControlPlaneSessionInfo | undefined }, void];
4545 toolCallPartialOutput: [{ toolCallId: string; contextItems: any[] }, void];
4646 };
modified core/tools/definitions/createRuleBlock.ts +4 −0
@@ -28,6 +28,10 @@
2828 description:
2929 "Clear, imperative instruction for future code generation (e.g. 'Use named exports', 'Add Python type hints'). Each rule should focus on one specific standard.",
3030 },
31+ description: {
32+ type: "string",
33+ description: "Short description of the rule",
34+ },
3135 globs: {
3236 type: "string",
3337 description:
modified core/tools/implementations/createRuleBlock.test.ts +54 −36
@@ -1,4 +1,4 @@
1-import * as YAML from "yaml";
1+import { parseMarkdownRule } from "../../config/markdown/parseMarkdownRule";
22 import { createRuleBlockImpl } from "./createRuleBlock";
33
44 // Mock the extras parameter with necessary functions
@@ -17,33 +17,6 @@
1717 jest.clearAllMocks();
1818 });
1919
20- it("should create a basic rule with name and rule content", async () => {
21- const args = {
22- name: "Test Rule",
23- rule: "Always write tests",
24- };
25-
26- const result = await createRuleBlockImpl(args, mockExtras as any);
27-
28- // Verify that writeFile was called with the correct YAML
29- expect(mockIde.writeFile).toHaveBeenCalled();
30- const yamlContent = mockIde.writeFile.mock.calls[0][1];
31- const parsedYaml = YAML.parse(yamlContent);
32-
33- // Verify the structure of the YAML
34- expect(parsedYaml).toEqual({
35- name: "Test Rule",
36- version: "0.0.1",
37- schema: "v1",
38- rules: [
39- {
40- name: "Test Rule",
41- rule: "Always write tests",
42- },
43- ],
44- });
45- });
46-
4720 it("should create a rule with glob pattern", async () => {
4821 const args = {
4922 name: "TypeScript Rule",
@@ -53,14 +26,16 @@
5326
5427 await createRuleBlockImpl(args, mockExtras as any);
5528
56- // Verify the YAML structure with globs
57- const yamlContent = mockIde.writeFile.mock.calls[0][1];
58- const parsedYaml = YAML.parse(yamlContent);
59- expect(parsedYaml.rules[0]).toEqual({
60- name: "TypeScript Rule",
61- rule: "Use interfaces for object shapes",
29+ const fileContent = mockIde.writeFile.mock.calls[0][1];
30+
31+ const { frontmatter, markdown } = parseMarkdownRule(fileContent);
32+
33+ expect(frontmatter).toEqual({
6234 globs: "**/*.{ts,tsx}",
6335 });
36+
37+ expect(markdown).toContain("# TypeScript Rule");
38+ expect(markdown).toContain("Use interfaces for object shapes");
6439 });
6540
6641 it("should create a filename based on sanitized rule name", async () => {
@@ -71,8 +46,51 @@
7146
7247 await createRuleBlockImpl(args, mockExtras as any);
7348
74- // Check that the filename is sanitized
7549 const fileUri = mockIde.writeFile.mock.calls[0][0];
76- expect(fileUri).toContain("special-chracters-spaces.yaml");
50+ expect(fileUri).toContain("special-chracters-spaces.md");
51+ });
52+
53+ it("should create a rule with description pattern", async () => {
54+ const args = {
55+ name: "Description Test",
56+ rule: "This is the rule content",
57+ description: "This is a detailed explanation of the rule",
58+ };
59+
60+ await createRuleBlockImpl(args, mockExtras as any);
61+
62+ const fileContent = mockIde.writeFile.mock.calls[0][1];
63+
64+ const { frontmatter, markdown } = parseMarkdownRule(fileContent);
65+
66+ expect(frontmatter).toEqual({
67+ description: "This is a detailed explanation of the rule",
68+ });
69+
70+ expect(markdown).toContain("# Description Test");
71+ expect(markdown).toContain("This is the rule content");
72+ });
73+
74+ it("should include both globs and description in frontmatter", async () => {
75+ const args = {
76+ name: "Complete Rule",
77+ rule: "Follow this standard",
78+ description: "This rule enforces our team standards",
79+ globs: "**/*.js",
80+ };
81+
82+ await createRuleBlockImpl(args, mockExtras as any);
83+
84+ const fileContent = mockIde.writeFile.mock.calls[0][1];
85+
86+ const { frontmatter, markdown } = parseMarkdownRule(fileContent);
87+
88+ expect(frontmatter).toEqual({
89+ description: "This rule enforces our team standards",
90+ globs: "**/*.js",
91+ });
92+
93+ expect(markdown).toContain("# Complete Rule");
94+ expect(markdown).toContain("Follow this standard");
7795 });
7896 });
modified core/tools/implementations/createRuleBlock.ts +16 −36
@@ -1,4 +1,3 @@
1-import { ConfigYaml } from "@continuedev/config-yaml";
21 import * as YAML from "yaml";
32 import { ToolImpl } from ".";
43 import { joinPathsToUri } from "../../util/uri";
@@ -6,8 +5,8 @@
65 export interface CreateRuleBlockArgs {
76 name: string;
87 rule: string;
8+ description: string;
99 globs?: string;
10- format?: "yaml" | "markdown"; // Add format option with yaml as default
1110 }
1211
1312 export const createRuleBlockImpl: ToolImpl = async (
@@ -20,26 +19,19 @@
2019 .replace(/[^a-z0-9\s-]/g, "")
2120 .replace(/\s+/g, "-");
2221
23- // Default to YAML format
24- const format = args.format ?? "yaml";
25- const fileExtension = format === "markdown" ? "md" : "yaml";
26-
27- const ruleObject = {
28- name: args.name,
29- rule: args.rule,
30- ...(args.globs ? { globs: args.globs.trim() } : {}),
31- };
32-
33- let fileContent: string;
34-
35- if (format === "markdown") {
36- // Generate markdown format with frontmatter
37- const frontmatter = {
38- ...(args.globs ? { globs: args.globs.trim() } : {}),
39- };
40-
41- const frontmatterYaml = YAML.stringify(frontmatter).trim();
42- fileContent = `---
22+ const fileExtension = "md";
23+
24+ const frontmatter: Record<string, string> = {};
25+
26+ if (args.globs) {
27+ frontmatter.globs = args.globs.trim();
28+ }
29+
30+ if (args.description) {
31+ frontmatter.description = args.description.trim();
32+ }
33+ const frontmatterYaml = YAML.stringify(frontmatter).trim();
34+ let fileContent = `---
4335 ${frontmatterYaml}
4436 ---
4537
@@ -47,18 +39,6 @@
4739
4840 ${args.rule}
4941 `;
50- } else {
51- // Generate YAML format
52- const ruleBlock: ConfigYaml = {
53- name: args.name,
54- version: "0.0.1",
55- schema: "v1",
56- rules: [ruleObject],
57- };
58-
59- fileContent = YAML.stringify(ruleBlock);
60- }
61-
6242 const [localContinueDir] = await extras.ide.getWorkspaceDirs();
6343 const rulesDirUri = joinPathsToUri(
6444 localContinueDir,
@@ -73,12 +53,12 @@
7353 return [
7454 {
7555 name: "New Rule Block",
76- description: "", // No description throws an error in the GUI
56+ description: args.description || "",
7757 uri: {
7858 type: "file",
7959 value: rulesDirUri,
8060 },
81- content: `Rule created successfully in ${format} format`,
61+ content: `Rule created successfully`,
8262 },
8363 ];
8464 };
added core/util/abortManager.ts +37 −0
@@ -0,0 +1,37 @@
1+export class StreamAbortManager {
2+ private static instance: StreamAbortManager;
3+ private controllers: Map<string, AbortController>;
4+
5+ private constructor() {
6+ this.controllers = new Map();
7+ }
8+
9+ public static getInstance(): StreamAbortManager {
10+ if (!StreamAbortManager.instance) {
11+ StreamAbortManager.instance = new StreamAbortManager();
12+ }
13+ return StreamAbortManager.instance;
14+ }
15+
16+ public get(id: string): AbortController {
17+ let controller = this.controllers.get(id);
18+ if (!controller) {
19+ controller = new AbortController();
20+ this.controllers.set(id, controller);
21+ }
22+ return controller;
23+ }
24+
25+ public abort(id: string): void {
26+ const controller = this.controllers.get(id);
27+ if (controller) {
28+ controller.abort();
29+ this.controllers.delete(id);
30+ }
31+ }
32+
33+ public clear(): void {
34+ this.controllers.forEach((controller) => controller.abort());
35+ this.controllers.clear();
36+ }
37+}
modified core/vendor/.gitignore +1 −1
@@ -1,1 +1,1 @@
1-!node_modules
No newline at the end of the file
1+node_modules
No newline at the end of the file
modified core/vendor/package-lock.json +105 −17
@@ -10,6 +10,9 @@
1010 "license": "Apache-2.0",
1111 "dependencies": {
1212 "@xenova/transformers": "^2.14.0"
13+ },
14+ "engines": {
15+ "node": ">=20.19.0"
1316 }
1417 },
1518 "node_modules/@huggingface/jinja": {
@@ -105,6 +108,78 @@
105108 "resolved": "https://registry.npmjs.org/b4a/-/b4a-1.6.4.tgz",
106109 "integrity": "sha512-fpWrvyVHEKyeEvbKZTVOeZF3VSKKWtJxFIxX/jaVPf+cLbGUSitjb49pHLqPV2BUNNZ0LcoeEGfE/YCpyDYHIw=="
107110 },
111+ "node_modules/bare-events": {
112+ "version": "2.5.4",
113+ "resolved": "https://registry.npmjs.org/bare-events/-/bare-events-2.5.4.tgz",
114+ "integrity": "sha512-+gFfDkR8pj4/TrWCGUGWmJIkBwuxPS5F+a5yWjOHQt2hHvNZd5YLzadjmDUtFmMM4y429bnKLa8bYBMHcYdnQA==",
115+ "license": "Apache-2.0",
116+ "optional": true
117+ },
118+ "node_modules/bare-fs": {
119+ "version": "4.1.5",
120+ "resolved": "https://registry.npmjs.org/bare-fs/-/bare-fs-4.1.5.tgz",
121+ "integrity": "sha512-1zccWBMypln0jEE05LzZt+V/8y8AQsQQqxtklqaIyg5nu6OAYFhZxPXinJTSG+kU5qyNmeLgcn9AW7eHiCHVLA==",
122+ "license": "Apache-2.0",
123+ "optional": true,
124+ "dependencies": {
125+ "bare-events": "^2.5.4",
126+ "bare-path": "^3.0.0",
127+ "bare-stream": "^2.6.4"
128+ },
129+ "engines": {
130+ "bare": ">=1.16.0"
131+ },
132+ "peerDependencies": {
133+ "bare-buffer": "*"
134+ },
135+ "peerDependenciesMeta": {
136+ "bare-buffer": {
137+ "optional": true
138+ }
139+ }
140+ },
141+ "node_modules/bare-os": {
142+ "version": "3.6.1",
143+ "resolved": "https://registry.npmjs.org/bare-os/-/bare-os-3.6.1.tgz",
144+ "integrity": "sha512-uaIjxokhFidJP+bmmvKSgiMzj2sV5GPHaZVAIktcxcpCyBFFWO+YlikVAdhmUo2vYFvFhOXIAlldqV29L8126g==",
145+ "license": "Apache-2.0",
146+ "optional": true,
147+ "engines": {
148+ "bare": ">=1.14.0"
149+ }
150+ },
151+ "node_modules/bare-path": {
152+ "version": "3.0.0",
153+ "resolved": "https://registry.npmjs.org/bare-path/-/bare-path-3.0.0.tgz",
154+ "integrity": "sha512-tyfW2cQcB5NN8Saijrhqn0Zh7AnFNsnczRcuWODH0eYAXBsJ5gVxAUuNr7tsHSC6IZ77cA0SitzT+s47kot8Mw==",
155+ "license": "Apache-2.0",
156+ "optional": true,
157+ "dependencies": {
158+ "bare-os": "^3.0.1"
159+ }
160+ },
161+ "node_modules/bare-stream": {
162+ "version": "2.6.5",
163+ "resolved": "https://registry.npmjs.org/bare-stream/-/bare-stream-2.6.5.tgz",
164+ "integrity": "sha512-jSmxKJNJmHySi6hC42zlZnq00rga4jjxcgNZjY9N5WlOe/iOoGRtdwGsHzQv2RlH2KOYMwGUXhf2zXd32BA9RA==",
165+ "license": "Apache-2.0",
166+ "optional": true,
167+ "dependencies": {
168+ "streamx": "^2.21.0"
169+ },
170+ "peerDependencies": {
171+ "bare-buffer": "*",
172+ "bare-events": "*"
173+ },
174+ "peerDependenciesMeta": {
175+ "bare-buffer": {
176+ "optional": true
177+ },
178+ "bare-events": {
179+ "optional": true
180+ }
181+ }
182+ },
108183 "node_modules/base64-js": {
109184 "version": "1.5.1",
110185 "resolved": "https://registry.npmjs.org/base64-js/-/base64-js-1.5.1.tgz",
@@ -444,9 +519,10 @@
444519 }
445520 },
446521 "node_modules/prebuild-install/node_modules/tar-fs": {
447- "version": "2.1.1",
448- "resolved": "https://registry.npmjs.org/tar-fs/-/tar-fs-2.1.1.tgz",
449- "integrity": "sha512-V0r2Y9scmbDRLCNex/+hYzvp/zyYjvFbHPNgVTKfQvVrb6guiE/fxP+XblDNR011utopbkex2nM4dHNV6GDsng==",
522+ "version": "2.1.2",
523+ "resolved": "https://registry.npmjs.org/tar-fs/-/tar-fs-2.1.2.tgz",
524+ "integrity": "sha512-EsaAXwxmx8UB7FRKqeozqEPop69DXcmYwTQwXvyAPF352HJsPdkVhvTaDPYqfNgruveJIJy3TA2l+2zj8LJIJA==",
525+ "license": "MIT",
450526 "dependencies": {
451527 "chownr": "^1.1.1",
452528 "mkdirp-classic": "^0.5.2",
@@ -503,11 +579,6 @@
503579 "once": "^1.3.1"
504580 }
505581 },
506- "node_modules/queue-tick": {
507- "version": "1.0.1",
508- "resolved": "https://registry.npmjs.org/queue-tick/-/queue-tick-1.0.1.tgz",
509- "integrity": "sha512-kJt5qhMxoszgU/62PLP1CJytzd2NKetjSRnyuj31fDd3Rlcz3fzlFdFLD1SItunPwyqEOkca6GbV612BWfaBag=="
510- },
511582 "node_modules/rc": {
512583 "version": "1.2.8",
513584 "resolved": "https://registry.npmjs.org/rc/-/rc-1.2.8.tgz",
@@ -642,12 +713,16 @@
642713 }
643714 },
644715 "node_modules/streamx": {
645- "version": "2.15.6",
646- "resolved": "https://registry.npmjs.org/streamx/-/streamx-2.15.6.tgz",
647- "integrity": "sha512-q+vQL4AAz+FdfT137VF69Cc/APqUbxy+MDOImRrMvchJpigHj9GksgDU2LYbO9rx7RX6osWgxJB2WxhYv4SZAw==",
716+ "version": "2.22.0",
717+ "resolved": "https://registry.npmjs.org/streamx/-/streamx-2.22.0.tgz",
718+ "integrity": "sha512-sLh1evHOzBy/iWRiR6d1zRcLao4gGZr3C1kzNz4fopCOKJb6xD9ub8Mpi9Mr1R6id5o43S+d93fI48UC5uM9aw==",
719+ "license": "MIT",
648720 "dependencies": {
649- "fast-fifo": "^1.1.0",
650- "queue-tick": "^1.0.1"
721+ "fast-fifo": "^1.3.2",
722+ "text-decoder": "^1.1.0"
723+ },
724+ "optionalDependencies": {
725+ "bare-events": "^2.2.0"
651726 }
652727 },
653728 "node_modules/string_decoder": {
@@ -667,13 +742,17 @@
667742 }
668743 },
669744 "node_modules/tar-fs": {
670- "version": "3.0.4",
671- "resolved": "https://registry.npmjs.org/tar-fs/-/tar-fs-3.0.4.tgz",
672- "integrity": "sha512-5AFQU8b9qLfZCX9zp2duONhPmZv0hGYiBPJsyUdqMjzq/mqVpy/rEUSeHk1+YitmxugaptgBh5oDGU3VsAJq4w==",
745+ "version": "3.0.8",
746+ "resolved": "https://registry.npmjs.org/tar-fs/-/tar-fs-3.0.8.tgz",
747+ "integrity": "sha512-ZoROL70jptorGAlgAYiLoBLItEKw/fUxg9BSYK/dF/GAGYFJOJJJMvjPAKDJraCXFwadD456FCuvLWgfhMsPwg==",
748+ "license": "MIT",
673749 "dependencies": {
674- "mkdirp-classic": "^0.5.2",
675750 "pump": "^3.0.0",
676751 "tar-stream": "^3.1.5"
752+ },
753+ "optionalDependencies": {
754+ "bare-fs": "^4.0.1",
755+ "bare-path": "^3.0.0"
677756 }
678757 },
679758 "node_modules/tar-stream": {
@@ -686,6 +765,15 @@
686765 "streamx": "^2.15.0"
687766 }
688767 },
768+ "node_modules/text-decoder": {
769+ "version": "1.2.3",
770+ "resolved": "https://registry.npmjs.org/text-decoder/-/text-decoder-1.2.3.tgz",
771+ "integrity": "sha512-3/o9z3X0X0fTupwsYvR03pJ/DjWuqqrfwBgTQzdWDiQSm9KitAyz/9WqsT2JQW7KV2m+bC2ol/zqpW37NHxLaA==",
772+ "license": "Apache-2.0",
773+ "dependencies": {
774+ "b4a": "^1.6.4"
775+ }
776+ },
689777 "node_modules/tunnel-agent": {
690778 "version": "0.6.0",
691779 "resolved": "https://registry.npmjs.org/tunnel-agent/-/tunnel-agent-0.6.0.tgz",
modified docs/docs/reference.md +2 −1
@@ -188,6 +188,7 @@
188188 not currently used.
189189 - `capabilities`: Array of strings denoting model capabilities, which will overwrite Continue's autodetection based on
190190 provider and model. Supported capabilities include `tool_use` and `image_input`.
191+- `maxStopWords`: Maximum number of stop words allowed, to avoid API errors with extensive lists.
191192 - `promptTemplates`: Can be used to override the default prompt templates for different model roles. Valid values are
192193 `chat`, [`edit`](./customize/model-roles/edit.mdx#prompt-templating), [
193194 `apply`](./customize/model-roles/apply.mdx#prompt-templating) and [
@@ -406,7 +407,7 @@
406407 - `destination` (**required**): The destination/endpoint that will receive the data. Can be:
407408 - an HTTP endpoint that will receive a POST request with a JSON blob
408409 - a file URL to a directory in which events will be dumpted to `.jsonl` files
409-- `schema` (**required**): the schema version of the JSON blobs to be sent
410+- `schema` (**required**): the schema version of the JSON blobs to be sent. Options include `0.1.0` and `0.2.0`
410411 - `events`: an array of event names to include. Defaults to all events if not specified.
411412 - `level`: a pre-defined filter for event fields. Options include `all` and `noCode`; the latter excludes data like file
412413 contents, prompts, and completions. Defaults to `all`
modified docs/docs/troubleshooting.mdx +2 −0
@@ -120,6 +120,8 @@
120120
121121 You may also set `requestOptions.caBundlePath` to an array of paths to multiple certificates.
122122
123+***Windows VS Code Users***: Installing the [win-ca](https://marketplace.visualstudio.com/items?itemName=ukoloff.win-ca) extension should also correct this issue.
124+
123125 #### VS Code Proxy Settings
124126
125127 If you are using VS Code and require requests to be made through a proxy, you are likely already set up through VS Code's [Proxy Server Support](https://code.visualstudio.com/docs/setup/network#_proxy-server-support). To double-check that this is enabled, use <kbd>cmd/ctrl</kbd> + <kbd>,</kbd> to open settings and search for "Proxy Support". Unless it is set to "off", then VS Code is responsible for making the request to the proxy.
modified docs/docusaurus.config.js +3 −1
@@ -66,7 +66,9 @@
6666 ],
6767
6868 scripts: [
69- '!function(){var e,t,n;e="7aa28ed11570734",t=function(){Reo.init({clientID:"7aa28ed11570734"})},(n=document.createElement("script")).src="https://static.reo.dev/"+e+"/reo.js",n.defer=!0,n.onload=t,document.head.appendChild(n)}();',
69+ {
70+ src: "/scripts/custom-reo.js", // it references from static folder
71+ },
7072 ],
7173
7274 themeConfig:
added docs/static/scripts/custom-reo.js +1 −0
@@ -0,0 +1,1 @@
1+!function(){var e,t,n;e="7aa28ed11570734",t=function(){Reo.init({clientID:"7aa28ed11570734"})},(n=document.createElement("script")).src="https://static.reo.dev/"+e+"/reo.js",n.async=!0,n.onload=t,document.head.appendChild(n)}();
No newline at the end of the file
modified extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/continue/Diffs.kt +1 −1
@@ -108,7 +108,7 @@
108108 )
109109 continuePluginService.ideProtocolClient?.deleteAtIndex(diffInfo.stepIndex)
110110 continuePluginService.ideProtocolClient?.sendAcceptRejectDiff(false, diffInfo.stepIndex)
111-
111+ continuePluginService.coreMessenger?.request("cancelApply", null, null) {}
112112 cleanUpFile(file)
113113 }
114114
modified extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/continue/GetTheme.kt +146 −35
@@ -2,11 +2,13 @@
22
33 import com.intellij.openapi.editor.colors.EditorColors
44 import com.intellij.openapi.editor.colors.EditorColorsManager
5+import com.intellij.openapi.editor.colors.CodeInsightColors
56 import java.awt.Color
67 import kotlin.math.max
78 import kotlin.math.min
89 import com.intellij.ui.JBColor
910 import com.intellij.ui.ColorUtil
11+import kotlin.math.roundToInt
1012
1113 class GetTheme {
1214 fun getSecondaryDark(): Color {
@@ -38,64 +40,173 @@
3840 return globalScheme.getColor(EditorColors.MODIFIED_TAB_ICON_COLOR) ?: globalScheme.defaultForeground
3941 }
4042
41- fun getTheme(): Map<String, String> {
42- fun toHex(color: Color): String {
43- return String.format("#%02x%02x%02x", color.red, color.green, color.blue)
43+ fun toHex(color: Color?): String? {
44+ if(color == null) {
45+ return null
4446 }
47+ return String.format("#%02x%02x%02x", color.red, color.green, color.blue)
48+ }
49+
50+ fun namedColor(name: String): Color? {
51+ // JB Color named color will fall back to a default unless we give it a fallback
52+ // We want defaults to be handled on the GUI side, so we give it this filler color
53+ // Which has a very low chance of conflicting with a real one
54+ // And return undefined if it gets the skip color
55+ val SKIP_COLOR = Color (18, 52, 86) // Hex #123456
56+ val color = JBColor.namedColor(name, SKIP_COLOR)
57+ if(toHex(color) == "#123456") {
58+ return null
59+ }
60+ return color
61+ }
62+
63+ fun lighten(color: Color, percentage: Int = 5): Color {
64+ // Increase each RGB component slightly
65+ val factor = 1 + percentage / 100f;
66+ fun lightenInt(value: Int): Int {
67+ return (value * factor).roundToInt().coerceAtMost(255)
68+ }
69+ return Color(
70+ lightenInt(color.red),
71+ lightenInt (color.green),
72+ lightenInt(color.blue),
73+ color.alpha
74+ )
75+ }
76+
77+ fun darken(color: Color, percentage: Int = 5): Color {
78+ // Decrease each RGB component slightly
79+ val factor = 1 - percentage / 100f;
80+ fun darkenInt(value: Int): Int {
81+ return (value * factor).roundToInt().coerceAtLeast(0)
82+ }
83+ return Color(
84+ darkenInt(color.red),
85+ darkenInt(color.green),
86+ darkenInt(color.blue),
87+ color.alpha
88+ )
89+ }
90+
91+ fun slightChange(color: Color?, percentage: Int = 5): Color? {
92+ if(color == null){
93+ return null
94+ }
95+ // If dark, make slightly lighter. If light, make slightly darker
96+ val averageRgb = (color.red + color.green + color.blue) / 3
97+ return if (averageRgb > 128) darken(color, percentage) else lighten(color, percentage)
98+ }
99+
100+ fun getTheme(): Map<String, String?> {
45101 try {
102+ val editorScheme = EditorColorsManager.getInstance().globalScheme
103+
46104 val background = JBColor.background()
47105 val foreground = JBColor.foreground()
48106
49- val buttonBackground = JBColor.namedColor("Button.background", Color(230, 230, 230))
50- val buttonForeground = JBColor.namedColor("Button.foreground", Color(0, 0, 0))
107+ val border = JBColor.border()
108+ val focusBorder = namedColor("Focus.borderColor") ?: namedColor("Component.focusedBorderColor")
51109
52- val badgeBackground = JBColor.namedColor("Badge.background", Color(150, 150, 150))
53- val badgeForeground = JBColor.namedColor("Badge.foreground", Color(0, 0, 0))
110+ val buttonBackground = namedColor("Button.default.startBackground")
111+ ?: namedColor("Button.default.background")
54112
55- val inputBackground = JBColor.namedColor("TextField.background", Color(255, 255, 255))
113+ val buttonForeground = namedColor("Button.default.startForeground")
114+ ?: namedColor("Button.default.foreground")
56115
57- val border = JBColor.border()
58- val focusBorder = JBColor.namedColor("Focus.borderColor", Color(100, 100, 255))
59- val editorScheme = EditorColorsManager.getInstance().globalScheme
116+ val buttonHoverBackground = namedColor("Button.default.hoverStartBackground")
117+ ?: namedColor("Button.default.hoverBackground")
118+ ?: namedColor("Button.default.startHoverBackground")
119+ ?: slightChange(buttonBackground)
60120
61- val editorBackground = editorScheme.defaultBackground
62- val editorForeground = editorScheme.defaultForeground
121+ val secondaryBackground = namedColor("Button.background") ?: background
122+ val secondaryHoverBackground = namedColor("Button.hoverBackground") ?: slightChange(secondaryBackground)
63123
64- val actionHoverBackground = JBColor.namedColor("ActionButton.hoverBackground", Color(220, 220, 220))
124+ val badgeBackground = namedColor("Badge.background")
125+ val badgeForeground = namedColor("Badge.foreground")
65126
66- val findMatchBackground = editorScheme.getAttributes(EditorColors.SEARCH_RESULT_ATTRIBUTES)?.backgroundColor ?: Color(255, 221, 0)
127+ val commandBackground = namedColor("CommandButton.background") ?: namedColor("ToolWindow.background")
128+ val commandForeground = namedColor("CommandButton.foreground") ?: namedColor("ToolWindow.foreground")
67129
68- val theme = mapOf(
69- "--vscode-editor-foreground" to toHex(editorForeground),
70- "--vscode-editor-background" to toHex(editorBackground),
130+ val inputBackground = namedColor("TextField.background")
131+ val inputForeground = namedColor("TextField.foreground")
132+ val inputPlaceholder = namedColor("TextField.inactiveForeground")
133+
134+ val listHoverBackground = namedColor("List.hoverBackground") ?: slightChange(background)
135+ val actionHoverBackground = namedColor("ActionButton.hoverBackground") ?: namedColor("Button.darcula.hoverBackground")
136+
137+ val tableOddRow = namedColor("Table.hoverBackground") ?: namedColor("Table.stripeColor")
138+ val listSelectionForeground = namedColor("List.selectionForeground")
71139
72- "--vscode-button-background" to toHex(buttonBackground),
73- "--vscode-button-foreground" to toHex(buttonForeground),
140+ val description = namedColor("Label.disabledForeground") ?: namedColor("Label.infoForeground")
74141
75- "--vscode-list-activeSelectionBackground" to toHex(actionHoverBackground) + "50",
142+ val mutedDescription = namedColor("Component.infoForeground")
143+ ?: namedColor("ContextHelp.foreground")
144+ ?: namedColor("TextField.placeholderForeground")
145+ ?: namedColor("Label.disabledForeground")
146+ ?: namedColor("ToolTip.foreground")
76147
77- "--vscode-quickInputList-focusForeground" to toHex(foreground),
78- "--vscode-quickInput-background" to toHex(inputBackground),
148+ val link = namedColor("Link.activeForeground")
79149
80- "--vscode-badge-background" to toHex(badgeBackground),
81- "--vscode-badge-foreground" to toHex(badgeForeground),
150+ val successColor = namedColor("ValidationSuccess.successColor")
151+ ?: namedColor("Component.successForeground")
152+ ?: namedColor("Label.successForeground")
153+ val warningColor = namedColor("ValidationWarning.warningColor")
154+ ?: EditorColorsManager.getInstance().globalScheme.getAttributes(CodeInsightColors.WARNINGS_ATTRIBUTES)?.effectColor
155+ ?: namedColor("Component.warningForeground")
156+ ?: namedColor("Label.warningForeground")
157+ val errorColor = namedColor("ValidationError.errorColor") ?: namedColor("Component.errorForeground") ?: namedColor("Label.errorForeground")
82158
83- "--vscode-input-background" to toHex(inputBackground),
84- "--vscode-input-border" to toHex(border),
85- "--vscode-sideBar-background" to toHex(background),
86- "--vscode-sideBar-border" to toHex(border),
87- "--vscode-focusBorder" to toHex(focusBorder),
159+ val accentColor = namedColor("Focus.defaultButtonBorderColor") ?: namedColor("Button.default.focusedBorderColor") ?: namedColor("Button.focusedBorderColor")
88160
89- "--vscode-commandCenter-activeBorder" to toHex(focusBorder),
90- "--vscode-commandCenter-inactiveBorder" to toHex(border),
161+ val editorBackground = editorScheme.defaultBackground
162+ val editorForeground = editorScheme.defaultForeground
91163
92- "--vscode-editor-findMatchHighlightBackground" to toHex(findMatchBackground) + "40"
93- )
164+ val findMatchBackground = editorScheme.getAttributes(EditorColors.SEARCH_RESULT_ATTRIBUTES)?.backgroundColor
94165
166+ val findMatchSelectedBackground = namedColor("SearchMatch.selectedBackground") ?:
167+ editorScheme.getAttributes(EditorColors.SEARCH_RESULT_ATTRIBUTES)?.backgroundColor
168+
169+ // These should match the keys in GUI's theme.ts
170+ val theme = mapOf(
171+ "background" to background,
172+ "foreground" to foreground,
173+ "editor-background" to editorBackground,
174+ "editor-foreground" to editorForeground,
175+ "primary-background" to buttonBackground,
176+ "primary-foreground" to buttonForeground,
177+ "primary-hover" to buttonHoverBackground,
178+ "secondary-background" to secondaryBackground,
179+ "secondary-foreground" to foreground,
180+ "secondary-hover" to secondaryHoverBackground,
181+ "border" to border,
182+ "border-focus" to focusBorder,
183+ "command-background" to commandBackground,
184+ "command-foreground" to commandForeground,
185+ "command-border" to border,
186+ "command-border-focus" to focusBorder,
187+ "description" to description,
188+ "description-muted" to mutedDescription,
189+ "input-background" to inputBackground,
190+ "input-foreground" to inputForeground,
191+ "input-border" to border,
192+ "input-placeholder" to inputPlaceholder,
193+ "table-oddRow" to tableOddRow,
194+ "badge-background" to badgeBackground,
195+ "badge-foreground" to badgeForeground,
196+ "success" to successColor,
197+ "warning" to warningColor,
198+ "error" to errorColor,
199+ "link" to link,
200+ "accent" to accentColor,
201+ "find-match" to findMatchBackground,
202+ "find-match-selected" to findMatchSelectedBackground,
203+ "list-hover" to listHoverBackground,
204+ "list-active" to actionHoverBackground,
205+ "list-active-foreground" to listSelectionForeground
206+ ).mapValues { toHex(it.value) }
95207 return theme
96208 } catch (error: Error) {
97209 return mapOf()
98210 }
99-
100211 }
101212 }
No newline at the end of the file
modified extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/editor/DiffStreamHandler.kt +2 −2
@@ -111,7 +111,8 @@
111111 suffix = suffix,
112112 language = virtualFile?.fileType?.name,
113113 modelTitle = modelTitle,
114- includeRulesInSystemMessage = includeRulesInSystemMessage
114+ includeRulesInSystemMessage = includeRulesInSystemMessage,
115+ fileUri = virtualFile?.url
115116 ),
116117 null
117118 ) { response ->
@@ -289,7 +290,6 @@
289290 }
290291 }
291292
292-
293293 private fun handleFinishedResponse() {
294294 ApplicationManager.getApplication().invokeLater {
295295 // Since we only call onLastDiffLine() when we reach a "same" line, we need to handle the case where
modified extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/types.kt +2 −1
@@ -244,7 +244,8 @@
244244 val input: String,
245245 val language: String?,
246246 val modelTitle: String?,
247- val includeRulesInSystemMessage: Boolean
247+ val includeRulesInSystemMessage: Boolean,
248+ val fileUri: String?
248249 )
249250
250251 data class AcceptOrRejectDiffPayload(
modified extensions/vscode/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/vscode/package.json +3 −3
@@ -2,7 +2,7 @@
22 "name": "continue",
33 "icon": "media/icon.png",
44 "author": "Continue Dev, Inc",
5- "version": "1.1.38",
5+ "version": "1.1.40",
66 "repository": {
77 "type": "git",
88 "url": "https://github.com/continuedev/continue"
@@ -631,7 +631,7 @@
631631 "devDependencies": {
632632 "@biomejs/biome": "1.6.4",
633633 "@nestjs/common": "^11.0.16",
634- "@openapitools/openapi-generator-cli": "^2.5.2",
634+ "@openapitools/openapi-generator-cli": "^2.20.0",
635635 "@types/chai": "^5.0.1",
636636 "@types/cors": "^2.8.17",
637637 "@types/express": "^4.17.21",
@@ -661,7 +661,7 @@
661661 },
662662 "dependencies": {
663663 "@continuedev/config-types": "^1.0.14",
664- "@continuedev/fetch": "^1.0.3",
664+ "@continuedev/fetch": "^1.0.10",
665665 "@electron/rebuild": "^3.2.10",
666666 "@reduxjs/toolkit": "^1.9.3",
667667 "@types/node-fetch": "^2.6.11",
modified extensions/vscode/src/commands.ts +14 −4
@@ -97,6 +97,7 @@
9797 action: "accept" | "reject",
9898 sidebar: ContinueGUIWebviewViewProvider,
9999 ide: VsCodeIde,
100+ core: Core,
100101 verticalDiffManager: VerticalDiffManager,
101102 newFileUri?: string,
102103 streamId?: string,
@@ -121,6 +122,9 @@
121122
122123 // Clear vertical diffs depending on action
123124 verticalDiffManager.clearForfileUri(newOrCurrentUri, action === "accept");
125+ if (action === "reject") {
126+ core.invoke("cancelApply", undefined);
127+ }
124128
125129 if (streamId) {
126130 const fileContent = await ide.readFile(newOrCurrentUri);
@@ -236,18 +240,20 @@
236240 "accept",
237241 sidebar,
238242 ide,
243+ core,
239244 verticalDiffManager,
240245 newFileUri,
241246 streamId,
242247 ),
243248
244- "continue.rejectDiff": async (newFilepath?: string, streamId?: string) =>
249+ "continue.rejectDiff": async (newFileUri?: string, streamId?: string) =>
245250 processDiff(
246251 "reject",
247252 sidebar,
248253 ide,
254+ core,
249255 verticalDiffManager,
250- newFilepath,
256+ newFileUri,
251257 streamId,
252258 ),
253259 "continue.acceptVerticalDiffBlock": (fileUri?: string, index?: number) => {
@@ -573,11 +579,15 @@
573579 await addEntireFileToContext(
574580 vscode.Uri.parse(fileUri),
575581 sidebar.webviewProtocol,
576- ide.ideUtils
582+ ide.ideUtils,
577583 );
578584 }
579585 } else {
580- await addEntireFileToContext(uri, sidebar.webviewProtocol, ide.ideUtils);
586+ await addEntireFileToContext(
587+ uri,
588+ sidebar.webviewProtocol,
589+ ide.ideUtils,
590+ );
581591 }
582592 }
583593 },
modified extensions/vscode/src/diff/vertical/manager.ts +3 −4
@@ -1,5 +1,4 @@
11 import { ChatMessage, DiffLine, ILLM, RuleWithSource } from "core";
2-import { ConfigHandler } from "core/config/ConfigHandler";
32 import { streamDiffLines } from "core/edit/streamDiffLines";
43 import { pruneLinesFromBottom, pruneLinesFromTop } from "core/llm/countTokens";
54 import { getMarkdownLanguageTagForFile } from "core/util";
@@ -31,7 +30,6 @@
3130 logDiffs: DiffLine[] | undefined;
3231
3332 constructor(
34- private readonly configHandler: ConfigHandler,
3533 private readonly webviewProtocol: VsCodeWebviewProtocol,
3634 private readonly editDecorationManager: EditDecorationManager,
3735 ) {
@@ -43,12 +41,12 @@
4341 startLine: number,
4442 endLine: number,
4543 options: VerticalDiffHandlerOptions,
46- ) {
44+ ): VerticalDiffHandler | undefined {
4745 if (this.fileUriToHandler.has(fileUri)) {
4846 this.fileUriToHandler.get(fileUri)?.clear(false);
4947 this.fileUriToHandler.delete(fileUri);
5048 }
51- const editor = vscode.window.activeTextEditor; // TODO
49+ const editor = vscode.window.activeTextEditor; // TODO might cause issues if user switches files
5250 if (editor && URI.equal(editor.document.uri.toString(), fileUri)) {
5351 const handler = new VerticalDiffHandler(
5452 startLine,
@@ -453,6 +451,7 @@
453451 language: getMarkdownLanguageTagForFile(fileUri),
454452 onlyOneInsertion: !!onlyOneInsertion,
455453 overridePrompt,
454+ abortControllerId: fileUri,
456455 });
457456
458457 for await (const line of stream) {
modified extensions/vscode/src/extension/VsCodeExtension.ts +0 −1
@@ -130,7 +130,6 @@
130130 this.configHandler.loadConfig();
131131
132132 this.verticalDiffManager = new VerticalDiffManager(
133- this.configHandler,
134133 this.sidebar.webviewProtocol,
135134 this.editDecorationManager,
136135 );
modified extensions/vscode/src/extension/VsCodeMessenger.ts +2 −1
@@ -236,8 +236,9 @@
236236 data: {
237237 prompt: stripImages(prompt),
238238 completion: fileAfterEdit ?? "",
239- modelProvider: model.providerName,
239+ modelProvider: model.underlyingProviderName,
240240 modelTitle: model.title ?? "",
241+ filepath: msg.data.range.filepath,
241242 },
242243 });
243244
modified gui/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 gui/src/App.tsx +5 −0
@@ -9,6 +9,7 @@
99 import Chat from "./pages/gui";
1010 import History from "./pages/history";
1111 import Stats from "./pages/stats";
12+import ThemePage from "./styles/ThemePage";
1213 import { ROUTES } from "./util/navigation";
1314
1415 const router = createMemoryRouter([
@@ -37,6 +38,10 @@
3738 path: ROUTES.CONFIG,
3839 element: <ConfigPage />,
3940 },
41+ {
42+ path: ROUTES.THEME,
43+ element: <ThemePage />,
44+ },
4045 ],
4146 },
4247 ]);
modified gui/src/components/AcceptRejectDiffButtons.tsx +15 −28
@@ -3,7 +3,7 @@
33 import { useContext } from "react";
44 import { IdeMessengerContext } from "../context/IdeMessenger";
55 import { getMetaKeyLabel } from "../util";
6-import { useFontSize } from "./ui/font";
6+import { ToolTip } from "./gui/Tooltip";
77
88 export interface AcceptRejectAllButtonsProps {
99 applyStates: ApplyState[];
@@ -21,8 +21,6 @@
2121 );
2222 const ideMessenger = useContext(IdeMessengerContext);
2323
24- const tinyFont = useFontSize(-3);
25-
2624 async function handleAcceptOrReject(status: AcceptOrRejectOutcome) {
2725 for (const { filepath = "", streamId } of pendingApplyStates) {
2826 ideMessenger.post(status, {
@@ -36,54 +34,43 @@
3634 }
3735 }
3836
39- if (!pendingApplyStates.length) {
40- return null;
41- }
37+ const rejectShortcut = `${getMetaKeyLabel()}⇧⌫`;
38+ const acceptShortcut = `${getMetaKeyLabel()}⇧⏎`;
4239
4340 return (
4441 <div
45- className="flex flex-row items-center justify-evenly gap-2 p-1 px-3"
42+ className="flex flex-row items-center justify-evenly gap-3 px-3"
4643 data-testid="accept-reject-all-buttons"
4744 >
4845 <button
49- className="flex cursor-pointer flex-row flex-wrap justify-center gap-1 border-none bg-transparent px-2 py-1 text-xs text-gray-300 opacity-80 hover:opacity-100 hover:brightness-125"
46+ className="text-foreground flex cursor-pointer flex-row flex-wrap justify-center gap-1 border-none bg-transparent p-0 text-xs opacity-80 hover:opacity-100 hover:brightness-125"
5047 onClick={() => handleAcceptOrReject("rejectDiff")}
5148 data-testid="edit-reject-button"
49+ data-tooltip-id="reject-shortcut"
50+ data-tooltip-content={`Reject All (${rejectShortcut})`}
5251 >
5352 <div className="flex flex-row items-center gap-1">
54- <XMarkIcon className="h-4 w-4 text-red-600" />
53+ <XMarkIcon className="text-error h-4 w-4" />
5554 <span>Reject</span>
5655 <span className="xs:inline-block hidden">All</span>
5756 </div>
58-
59- <span
60- className="xs:inline-block hidden text-gray-400"
61- style={{
62- fontSize: tinyFont,
63- }}
64- >
65- ({getMetaKeyLabel()}⇧⌫)
66- </span>
6757 </button>
58+ <ToolTip id="reject-shortcut" />
59+
6860 <button
69- className="flex cursor-pointer flex-row flex-wrap justify-center gap-1 border-none bg-transparent px-2 py-1 text-xs text-gray-300 opacity-80 hover:opacity-100 hover:brightness-125"
61+ className="text-foreground flex cursor-pointer flex-row flex-wrap justify-center gap-1 border-none bg-transparent p-0 text-xs opacity-80 hover:opacity-100 hover:brightness-125"
7062 onClick={() => handleAcceptOrReject("acceptDiff")}
7163 data-testid="edit-accept-button"
64+ data-tooltip-id="accept-shortcut"
65+ data-tooltip-content={`Accept All (${acceptShortcut})`}
7266 >
7367 <div className="flex flex-row items-center gap-1">
74- <CheckIcon className="h-4 w-4 text-green-600" />
68+ <CheckIcon className="text-success h-4 w-4" />
7569 <span>Accept</span>
7670 <span className="xs:inline-block hidden">All</span>
7771 </div>
78- <span
79- className="xs:inline-block hidden text-gray-400"
80- style={{
81- fontSize: tinyFont,
82- }}
83- >
84- ({getMetaKeyLabel()}⇧⏎)
85- </span>
8672 </button>
73+ <ToolTip id="accept-shortcut" />
8774 </div>
8875 );
8976 }
modified gui/src/components/History/HistoryTableRow.tsx +2 −2
@@ -6,7 +6,7 @@
66 import { Input } from "..";
77 import { IdeMessengerContext } from "../../context/IdeMessenger";
88 import { useAppDispatch, useAppSelector } from "../../redux/hooks";
9-import { exitEditMode } from "../../redux/thunks/editMode";
9+import { exitEdit } from "../../redux/thunks/edit";
1010 import {
1111 deleteSession,
1212 getSession,
@@ -69,7 +69,7 @@
6969 data-testid={`history-row-${index}`}
7070 className="hover:bg-vsc-editor-background relative box-border flex cursor-pointer overflow-hidden rounded-lg p-3"
7171 onClick={async () => {
72- await dispatch(exitEditMode({}));
72+ await dispatch(exitEdit({}));
7373 if (sessionMetadata.sessionId !== currentSessionId) {
7474 await dispatch(
7575 loadSession({
modified gui/src/components/Layout.tsx +12 −12
@@ -7,9 +7,9 @@
77 import { LocalStorageProvider } from "../context/LocalStorage";
88 import { useWebviewListener } from "../hooks/useWebviewListener";
99 import { useAppDispatch, useAppSelector } from "../redux/hooks";
10-import { setCodeToEdit } from "../redux/slices/editModeState";
10+import { setCodeToEdit } from "../redux/slices/editState";
1111 import { setShowDialog } from "../redux/slices/uiSlice";
12-import { enterEditMode, exitEditMode } from "../redux/thunks/editMode";
12+import { enterEdit, exitEdit } from "../redux/thunks/edit";
1313 import { saveCurrentSession } from "../redux/thunks/session";
1414 import { fontSize, isMetaEquivalentKeyPressed } from "../util";
1515 import { incrementFreeTrialCount } from "../util/freeTrial";
@@ -48,14 +48,14 @@
4848 const dialogMessage = useAppSelector((state) => state.ui.dialogMessage);
4949
5050 const showDialog = useAppSelector((state) => state.ui.showDialog);
51- const mode = useAppSelector((state) => state.session.mode);
51+ const isInEdit = useAppSelector((store) => store.session.isInEdit);
5252
5353 useWebviewListener(
5454 "newSession",
5555 async () => {
5656 navigate(ROUTES.HOME);
57- if (mode === "edit") {
58- await dispatch(exitEditMode({}));
57+ if (isInEdit) {
58+ await dispatch(exitEdit({}));
5959 } else {
6060 await dispatch(
6161 saveCurrentSession({
@@ -65,7 +65,7 @@
6565 );
6666 }
6767 },
68- [mode],
68+ [isInEdit],
6969 );
7070
7171 useWebviewListener(
@@ -81,9 +81,9 @@
8181 "focusContinueInputWithNewSession",
8282 async () => {
8383 navigate(ROUTES.HOME);
84- if (mode === "edit") {
84+ if (isInEdit) {
8585 await dispatch(
86- exitEditMode({
86+ exitEdit({
8787 openNewSession: true,
8888 }),
8989 );
@@ -96,7 +96,7 @@
9696 );
9797 }
9898 },
99- [location.pathname, mode],
99+ [location.pathname, isInEdit],
100100 location.pathname === ROUTES.HOME,
101101 );
102102
@@ -148,7 +148,7 @@
148148 "focusEdit",
149149 async () => {
150150 await ideMessenger.request("edit/addCurrentSelection", undefined);
151- await dispatch(enterEditMode({}));
151+ await dispatch(enterEdit({ editorContent: mainEditor?.getJSON() }));
152152 mainEditor?.commands.focus();
153153 },
154154 [ideMessenger, mainEditor],
@@ -169,7 +169,7 @@
169169 useWebviewListener(
170170 "exitEditMode",
171171 async () => {
172- await dispatch(exitEditMode({}));
172+ await dispatch(exitEdit({}));
173173 },
174174 [],
175175 );
@@ -181,7 +181,7 @@
181181 if (selection) {
182182 // Copy to clipboard
183183 setTimeout(() => {
184- navigator.clipboard.writeText(selection);
184+ void navigator.clipboard.writeText(selection);
185185 }, 100);
186186 }
187187 }
added gui/src/components/ModeSelect/ModeIcon.tsx +19 −0
@@ -0,0 +1,19 @@
1+import { ChatBubbleLeftIcon, SparklesIcon } from "@heroicons/react/24/outline";
2+import { MessageModes } from "core";
3+
4+interface ModeIconProps {
5+ mode: MessageModes;
6+ className?: string;
7+}
8+
9+export function ModeIcon({
10+ mode,
11+ className = "xs:h-3 xs:w-3 h-3 w-3",
12+}: ModeIconProps) {
13+ switch (mode) {
14+ case "agent":
15+ return <SparklesIcon className={className} />;
16+ case "chat":
17+ return <ChatBubbleLeftIcon className={className} />;
18+ }
19+}
added gui/src/components/ModeSelect/ModeSelect.tsx +123 −0
@@ -0,0 +1,123 @@
1+import { CheckIcon, ChevronDownIcon } from "@heroicons/react/24/outline";
2+import { MessageModes } from "core";
3+import { modelSupportsTools } from "core/llm/autodetect";
4+import { useCallback, useEffect, useMemo } from "react";
5+import { useAppDispatch, useAppSelector } from "../../redux/hooks";
6+import { selectSelectedChatModel } from "../../redux/slices/configSlice";
7+import { setMode } from "../../redux/slices/sessionSlice";
8+import { getFontSize, getMetaKeyLabel } from "../../util";
9+import { useMainEditor } from "../mainInput/TipTapEditor";
10+import {
11+ Listbox,
12+ ListboxButton,
13+ ListboxOption,
14+ ListboxOptions,
15+} from "../ui/Listbox";
16+import { ModeIcon } from "./ModeIcon";
17+
18+export function ModeSelect() {
19+ const dispatch = useAppDispatch();
20+ const mode = useAppSelector((store) => store.session.mode);
21+ const selectedModel = useAppSelector(selectSelectedChatModel);
22+ const agentModeSupported = useMemo(() => {
23+ return selectedModel && modelSupportsTools(selectedModel);
24+ }, [selectedModel]);
25+ const { mainEditor } = useMainEditor();
26+ const metaKeyLabel = useMemo(() => {
27+ return getMetaKeyLabel();
28+ }, []);
29+
30+ // Switch to chat mode if agent mode is selected but not supported
31+ useEffect(() => {
32+ if (!selectedModel) {
33+ return;
34+ }
35+ if (mode === "agent" && !agentModeSupported) {
36+ dispatch(setMode("chat"));
37+ }
38+ }, [mode, agentModeSupported, dispatch, selectedModel]);
39+
40+ const cycleMode = useCallback(() => {
41+ dispatch(setMode(mode === "chat" ? "agent" : "chat"));
42+ mainEditor?.commands.focus();
43+ }, [mode, mainEditor]);
44+
45+ const selectMode = useCallback(
46+ (newMode: MessageModes) => {
47+ if (newMode === mode) {
48+ return;
49+ }
50+
51+ dispatch(setMode(newMode));
52+
53+ mainEditor?.commands.focus();
54+ },
55+ [mode, mainEditor],
56+ );
57+
58+ useEffect(() => {
59+ const handleKeyDown = (e: KeyboardEvent) => {
60+ if (e.key === "." && (e.metaKey || e.ctrlKey)) {
61+ e.preventDefault();
62+ void cycleMode();
63+ }
64+ };
65+
66+ document.addEventListener("keydown", handleKeyDown);
67+ return () => document.removeEventListener("keydown", handleKeyDown);
68+ }, [cycleMode]);
69+
70+ return (
71+ <Listbox value={mode} onChange={selectMode}>
72+ <div className="relative">
73+ <ListboxButton
74+ data-testid="mode-select-button"
75+ className="xs:px-2 text-description-muted bg-table-oddRow gap-1 rounded-full border-none px-1.5 py-0.5 transition-colors duration-200 hover:brightness-110"
76+ >
77+ <ModeIcon mode={mode} />
78+ <span className="hidden sm:block">
79+ {mode.charAt(0).toUpperCase() + mode.slice(1)}
80+ </span>
81+ <ChevronDownIcon
82+ className="h-2 w-2 flex-shrink-0"
83+ aria-hidden="true"
84+ />
85+ </ListboxButton>
86+ <ListboxOptions className="min-w-32 max-w-48">
87+ <ListboxOption value="chat">
88+ <div className="flex flex-row items-center gap-1.5">
89+ <ModeIcon mode="chat" />
90+ <span className="">Chat</span>
91+ <span
92+ className={`text-description-muted text-[${getFontSize() - 3}px] mr-auto`}
93+ >
94+ {getMetaKeyLabel()}L
95+ </span>
96+ </div>
97+ {mode === "chat" && <CheckIcon className="ml-auto h-3 w-3" />}
98+ </ListboxOption>
99+
100+ <ListboxOption
101+ value="agent"
102+ disabled={!agentModeSupported}
103+ className={"gap-1"}
104+ >
105+ <div className="flex flex-row items-center gap-1.5">
106+ <ModeIcon mode="agent" />
107+ <span className="">Agent</span>
108+ </div>
109+ {agentModeSupported ? (
110+ mode === "agent" && <CheckIcon className="ml-auto h-3 w-3" />
111+ ) : (
112+ <span>(Not supported)</span>
113+ )}
114+ </ListboxOption>
115+
116+ <div className="text-description-muted px-2 py-1">
117+ {`${metaKeyLabel} . for next mode`}
118+ </div>
119+ </ListboxOptions>
120+ </div>
121+ </Listbox>
122+ );
123+}
added gui/src/components/ModeSelect/index.ts +1 −0
@@ -0,0 +1,1 @@
1+export * from "./ModeSelect";
modified gui/src/components/OnboardingCard/components/BestExperienceConfigForm.tsx +3 −0
@@ -40,6 +40,7 @@
4040 const chatModelConfig = {
4141 model: chatModel.params.model,
4242 provider: chatProvider.provider,
43+ underlyingProviderName: chatProvider.provider,
4344 apiKey: chatApiKey,
4445 title: chatModel.params.title,
4546 };
@@ -47,6 +48,7 @@
4748 const repoMapConfig = {
4849 model: repoMapModel.params.model,
4950 provider: chatProvider.provider,
51+ underlyingProviderName: chatProvider.provider,
5052 apiKey: chatApiKey,
5153 title: repoMapModel.params.title,
5254 };
@@ -54,6 +56,7 @@
5456 const autocompleteModelConfig = {
5557 title: autocompleteModel.params.title,
5658 provider: autocompleteProvider.provider,
59+ underlyingProviderName: autocompleteProvider.provider,
5760 model: autocompleteModel.params.model,
5861 apiKey: autocompleteApiKey,
5962 };
modified gui/src/components/StyledMarkdownPreview/SymbolLink.tsx +1 −8
@@ -44,14 +44,7 @@
4444 data-tooltip-id={id}
4545 data-tooltip-delay-show={500}
4646 >
47- <code
48- className="align-middle"
49- style={{
50- color: "var(--vscode-textLink-foreground)",
51- }}
52- >
53- {content}
54- </code>
47+ <code className="text-link align-middle">{content}</code>
5548 </span>
5649 <ToolTip id={id} place="top" className="m-0 p-0">
5750 <pre className="text-left">{processedContent ?? symbol.filepath}</pre>
modified gui/src/components/TabBar/TabBar.tsx +35 −50
@@ -1,5 +1,5 @@
11 import { XMarkIcon } from "@heroicons/react/24/outline";
2-import { useCallback, useEffect } from "react";
2+import React, { useCallback, useEffect } from "react";
33 import { useDispatch, useSelector } from "react-redux";
44 import styled from "styled-components";
55 import { defaultBorderRadius } from "..";
@@ -13,16 +13,30 @@
1313 } from "../../redux/slices/tabsSlice";
1414 import { AppDispatch, RootState } from "../../redux/store";
1515 import { loadSession, saveCurrentSession } from "../../redux/thunks/session";
16+import { varWithFallback } from "../../styles/theme";
17+
18+// Haven't set up theme colors for tabs yet
19+// Will keep it simple and choose from existing ones. Comments show vars we could use
20+const tabBorderVar = varWithFallback("border"); // --vscode-tab-border
21+const tabBackgroundVar = varWithFallback("background"); // --vscode-tab-inactiveBackground
22+const tabForegroundVar = varWithFallback("foreground"); // --vscode-tab-inactiveForeground
23+const tabHoverBackgroundVar = varWithFallback("list-hover"); // --vscode-tab-hoverBackground
24+const tabHoverForegroundVar = varWithFallback("foreground"); // --vscode-tab-hoverForeground
25+const tabSelectedBackgroundVar = varWithFallback("background"); // --vscode-tab-activeBackground
26+const tabSelectedForegroundVar = varWithFallback("foreground"); // --vscode-tab-activeForeground
27+const tabAccentVar = varWithFallback("accent"); // --vscode-tab-activeBorderTop
1628
1729 const TabBarContainer = styled.div`
1830 display: flex;
1931 flex-wrap: wrap;
2032 flex-shrink: 0;
2133 flex-grow: 0;
22- background-color: var(--vscode-tab-inactiveBackground);
34+ background-color: ${tabBackgroundVar};
2335 border-bottom: none;
2436 position: relative;
2537 margin-top: 2px;
38+ max-height: 100px;
39+ overflow: auto;
2640
2741 /* Hide scrollbar but keep functionality */
2842 scrollbar-width: none;
@@ -41,24 +55,18 @@
4155 max-width: 150px;
4256 height: 25px;
4357 background-color: ${(props) =>
44- props.isActive
45- ? "var(--vscode-tab-activeBackground)"
46- : "var(--vscode-tab-inactiveBackground)"};
58+ props.isActive ? tabSelectedBackgroundVar : tabBackgroundVar};
4759 color: ${(props) =>
48- props.isActive
49- ? "var(--vscode-tab-activeForeground)"
50- : "var(--vscode-tab-inactiveForeground)"};
60+ props.isActive ? tabSelectedForegroundVar : tabForegroundVar};
5161 cursor: pointer;
52- border: 1px solid var(--vscode-tab-border);
62+ border: 1px solid ${tabBorderVar};
5363 border-bottom: ${(props) =>
54- props.isActive ? "none" : `1px solid var(--vscode-tab-border)`};
64+ props.isActive ? "none" : `1px solid ${tabBorderVar}`};
5565 user-select: none;
5666 position: relative;
5767 transition: background-color 0.2s;
5868 border-top: ${(props) =>
59- props.isActive
60- ? `1px solid var(--vscode-tab-activeBorderTop, --vscode-tab-border)`
61- : `1px solid var(--vscode-tab-border)`};
69+ props.isActive ? `1px solid ${tabAccentVar}` : `1px solid ${tabBorderVar}`};
6270 &:first-child {
6371 border-left: none;
6472 }
@@ -68,13 +76,9 @@
6876
6977 &:hover {
7078 background-color: ${(props) =>
71- props.isActive
72- ? "var(--vscode-tab-activeBackground)"
73- : "var(--vscode-tab-hoverBackground)"};
79+ props.isActive ? tabSelectedBackgroundVar : tabHoverBackgroundVar};
7480 color: ${(props) =>
75- props.isActive
76- ? "var(--vscode-tab-activeForeground)"
77- : "var(--vscode-tab-hoverForeground)"};
81+ props.isActive ? tabSelectedForegroundVar : tabHoverForegroundVar};
7882 }
7983 `;
8084
@@ -104,7 +108,7 @@
104108
105109 &:hover {
106110 opacity: 1;
107- background-color: var(--vscode-tab-hoverBackground);
111+ background-color: ${tabHoverBackgroundVar};
108112 }
109113
110114 ${Tab}:hover & {
@@ -119,33 +123,12 @@
119123 const TabBarSpace = styled.div`
120124 flex: 1;
121125 display: flex;
122- border-bottom: 1px solid var(--vscode-tab-border);
123- background-color: var(--vscode-tab-inactiveBackground);
126+ border-bottom: 1px solid ${tabBorderVar};
127+ background-color: ${tabBackgroundVar};
124128 `;
125129
126-const NewTabButton = styled.button`
127- display: flex;
128- align-items: center;
129- justify-content: center;
130- width: 35px;
131- height: 100%;
132- border: none;
133- background: transparent;
134- color: var(--vscode-tab-inactiveForeground);
135- cursor: pointer;
136- opacity: 0.7;
137- transition: opacity 0.2s;
138-
139- &:hover {
140- opacity: 1;
141- background-color: var(--vscode-tab-hoverBackground);
142- color: var(--vscode-tab-hoverForeground);
143- }
144-`;
145-
146-export function TabBar() {
130+export const TabBar = React.forwardRef<HTMLDivElement>((_, ref) => {
147131 const dispatch = useDispatch<AppDispatch>();
148- const currentSession = useSelector((state: RootState) => state.session);
149132 const currentSessionId = useSelector((state: RootState) => state.session.id);
150133 const currentSessionTitle = useSelector(
151134 (state: RootState) => state.session.title,
@@ -160,7 +143,6 @@
160143 return Date.now().toString(36) + Math.random().toString(36).substring(2);
161144 }, []);
162145
163- // Handle session changes
164146 useEffect(() => {
165147 if (!currentSessionId) return;
166148
@@ -243,10 +225,13 @@
243225 }
244226 };
245227
246- return tabs.length === 1 ? (
247- <></>
248- ) : (
249- <TabBarContainer>
228+ return (
229+ <TabBarContainer
230+ ref={ref}
231+ style={{
232+ display: tabs.length === 1 ? "none" : "flex",
233+ }}
234+ >
250235 {tabs.map((tab) => (
251236 <Tab
252237 key={tab.id}
@@ -272,4 +257,4 @@
272257 </TabBarSpace>
273258 </TabBarContainer>
274259 );
275-}
260+});
modified gui/src/components/dialogs/index.tsx +2 −3
@@ -4,12 +4,11 @@
44 import styled from "styled-components";
55 import {
66 CloseButton,
7- VSC_BACKGROUND_VAR,
87 defaultBorderRadius,
9- parseColorForHex,
108 vscBackground,
119 vscForeground,
1210 } from "..";
11+import { varWithFallback } from "../../styles/theme";
1312
1413 interface TextDialogProps {
1514 showDialog: boolean;
@@ -22,7 +21,7 @@
2221 position: fixed;
2322 width: 100%;
2423 height: 100%;
25- background-color: ${parseColorForHex(VSC_BACKGROUND_VAR)}aa;
24+ background-color: ${varWithFallback("background")}aa;
2625 z-index: 100000;
2726 flex-direction: column;
2827 `;
modified gui/src/components/find/FindWidget.tsx +126 −292
@@ -13,35 +13,24 @@
1313 } from "react";
1414 import { HeaderButton, Input } from "..";
1515 import HeaderButtonWithToolTip from "../gui/HeaderButtonWithToolTip";
16-import { useAppSelector } from "../../redux/hooks";
17-
18-interface SearchMatch {
19- index: number;
20- textNode: Text;
21- overlayRectangle: Rectangle;
22-}
23-
24-type ScrollToMatchOption = "closest" | "first" | "none";
25-
26-const SEARCH_DEBOUNCE = 300;
27-const RESIZE_DEBOUNCE = 200;
28-
29-interface Rectangle {
30- top: number;
31- left: number;
32- width: number;
33- height: number;
34-}
35-
36-interface HighlightOverlayProps extends Rectangle {
16+import {
17+ Rectangle,
18+ SearchMatch,
19+ searchWithinContainer,
20+} from "./findWidgetSearch";
21+import useDebounceValue from "./useDebounce";
22+import { useElementSize } from "./useElementSize";
23+
24+interface HighlightOverlayProps {
25+ rectangle: Rectangle;
3726 isCurrent: boolean;
3827 }
3928
4029 const HighlightOverlay = (props: HighlightOverlayProps) => {
41- const { isCurrent, top, left, width, height } = props;
30+ const { top, left, width, height } = props.rectangle;
4231 return (
4332 <div
44- className={isCurrent ? "bg-find-match-selected" : "bg-blue-200/30"} // bg-vsc-find-match can"t get to work
33+ className={props.isCurrent ? "bg-findMatch-selected" : "bg-findMatch"}
4534 key={`highlight-${top}-${left}`}
4635 style={{
4736 position: "absolute",
@@ -56,6 +45,8 @@
5645 );
5746 };
5847
48+type ScrollToMatchOption = "closest" | "first" | "none";
49+
5950 /*
6051 useFindWidget takes a container ref and returns
6152 1. A widget that can be placed anywhere to search the contents of that container
@@ -64,18 +55,22 @@
6455
6556 Container must have relative positioning
6657 */
67-export const useFindWidget = (searchRef: RefObject<HTMLDivElement>) => {
58+export const useFindWidget = (
59+ searchRef: RefObject<HTMLDivElement>,
60+ headerRef: RefObject<HTMLDivElement>,
61+ disabled: boolean,
62+) => {
6863 // Search input, debounced
69- const [input, setInput] = useState<string>("");
70- const debouncedInput = useRef<string>("");
7164 const inputRef = useRef<HTMLInputElement>(null);
65+ const [currentValue, setCurrentValue] = useState<string>("");
66+ const searchTerm = useDebounceValue(currentValue, 300);
7267
7368 // Widget open/closed state
7469 const [open, setOpen] = useState<boolean>(false);
7570 const openWidget = useCallback(() => {
7671 setOpen(true);
7772 inputRef?.current?.select();
78- }, [setOpen, inputRef]);
73+ }, [inputRef]);
7974
8075 // Search settings and results
8176 const [caseSensitive, setCaseSensitive] = useState<boolean>(false);
@@ -97,7 +92,7 @@
9792 behavior: "smooth",
9893 });
9994 },
100- [searchRef.current],
95+ [searchRef],
10196 );
10297
10398 const nextMatch = useCallback(() => {
@@ -143,327 +138,166 @@
143138 }, [inputRef, matches, nextMatch]);
144139
145140 // Handle container resize changes - highlight positions must adjust
146- const [isResizing, setIsResizing] = useState(false);
147- useEffect(() => {
148- let timeoutId: NodeJS.Timeout | null = null;
149- if (!searchRef?.current) return;
150-
151- const resizeObserver = new ResizeObserver((entries) => {
152- if (timeoutId) {
153- clearTimeout(timeoutId);
154- }
155- setIsResizing(true);
156- timeoutId = setTimeout(() => {
157- setIsResizing(false);
158- }, RESIZE_DEBOUNCE);
159- });
160-
161- resizeObserver.observe(searchRef.current);
162- return () => {
163- if (timeoutId) {
164- clearTimeout(timeoutId);
165- }
166- if (searchRef.current) resizeObserver.unobserve(searchRef.current);
167- };
168- }, [searchRef.current]);
141+ const { clientHeight: headerHeight, isResizing: headerResizing } =
142+ useElementSize(headerRef);
143+ const { isResizing: containerResizing } = useElementSize(searchRef);
144+ const isResizing = useMemo(() => {
145+ return containerResizing || headerResizing;
146+ }, [containerResizing, headerResizing]);
169147
170148 // Main function for finding matches and generating highlight overlays
171149 const refreshSearch = useCallback(
172- (scrollTo: ScrollToMatchOption = "none", clearFirst = false) => {
173- if (clearFirst) setMatches([]);
174-
175- const searchContainer = searchRef.current;
176-
177- const _query = debouncedInput.current; // trimStart - decided no because spaces should be fully searchable
178- if (!searchContainer || !_query) {
179- setMatches([]);
180- return;
181- }
182- const query = caseSensitive ? _query : _query.toLowerCase();
183-
184- // First grab all text nodes
185- // Skips any elements with the "find-widget-skip" class
186- const textNodes: Text[] = [];
187- const walker = document.createTreeWalker(
188- searchRef.current,
189- NodeFilter.SHOW_ALL,
150+ (scrollTo: ScrollToMatchOption = "none") => {
151+ const { results, closestToMiddle } = searchWithinContainer(
152+ searchRef,
153+ searchTerm,
190154 {
191- acceptNode: (node) => {
192- if (node.nodeType === Node.ELEMENT_NODE) {
193- if ((node as Element).classList.contains("find-widget-skip"))
194- return NodeFilter.FILTER_REJECT;
195- return NodeFilter.FILTER_ACCEPT;
196- } else if (node.nodeType === Node.TEXT_NODE) {
197- if (!node.nodeValue) return NodeFilter.FILTER_REJECT;
198- const nodeValue = caseSensitive
199- ? node.nodeValue
200- : node.nodeValue.toLowerCase();
201- if (nodeValue.includes(query)) return NodeFilter.FILTER_ACCEPT;
202- }
203- return NodeFilter.FILTER_REJECT;
204- },
155+ caseSensitive,
156+ useRegex,
157+ offsetHeight: headerHeight,
205158 },
206159 );
207-
208- while (walker.nextNode()) {
209- if (walker.currentNode.nodeType === Node.ELEMENT_NODE) continue;
210- textNodes.push(walker.currentNode as Text);
211- }
212-
213- // Now walk through each node match and extract search results
214- // One node can have several matches
215- const newMatches: SearchMatch[] = [];
216- textNodes.forEach((textNode, idx) => {
217- // Hacky way to detect code blocks that be wider than client and cause absolute positioning to fail
218- const highlightFullLine =
219- textNode.parentElement?.className.includes("hljs");
220-
221- let nodeTextValue = caseSensitive
222- ? textNode.nodeValue
223- : textNode.nodeValue.toLowerCase();
224- let startIndex = 0;
225- while ((startIndex = nodeTextValue.indexOf(query, startIndex)) !== -1) {
226- // Create a range to measure the size and position of the match
227- const range = document.createRange();
228- range.setStart(textNode, startIndex);
229- const endIndex = startIndex + query.length;
230- range.setEnd(textNode, endIndex);
231- const rect = range.getBoundingClientRect();
232- range.detach();
233- startIndex = endIndex;
234-
235- const top =
236- rect.top + searchContainer.clientTop + searchContainer.scrollTop;
237- const left =
238- rect.left + searchContainer.clientLeft + searchContainer.scrollLeft;
239-
240- // Build a match result and push to matches
241- const newMatch: SearchMatch = {
242- index: 0, // will set later
243- textNode,
244- overlayRectangle: {
245- top,
246- left: highlightFullLine ? 2 : left,
247- width: highlightFullLine
248- ? searchContainer.clientWidth - 4
249- : rect.width, // equivalent of adding 2 px x padding
250- height: rect.height,
251- },
252- };
253- newMatches.push(newMatch);
254-
255- if (highlightFullLine) {
256- break; // Since highlighting full line no need for multiple overlays, will cause darker highlight
257- }
258- }
259- });
260-
261- // There will still be duplicate full lines when multiple text nodes are in the same line (e.g. Code highlights)
262- // Filter them out by using the overlay rectangle as a hash key
263- const matchHash = Object.fromEntries(
264- newMatches.map((match) => [
265- JSON.stringify(match.overlayRectangle),
266- match,
267- ]),
268- );
269- const filteredMatches = Object.values(matchHash).map((match, index) => ({
270- ...match,
271- index,
272- }));
273-
160+ setMatches(results);
274161 // Find match closest to the middle of the view
275- const verticalMiddle =
276- searchRef.current.scrollTop + searchRef.current.clientHeight / 2;
277- let closestDist = Infinity;
278- let closestMatchToMiddle: SearchMatch | null = null;
279- filteredMatches.forEach((match) => {
280- const dist = Math.abs(verticalMiddle - match.overlayRectangle.top);
281- if (dist < closestDist) {
282- closestDist = dist;
283- closestMatchToMiddle = match;
284- }
285- });
286-
287- // Update matches and scroll to the closest or first match
288- setMatches(filteredMatches);
289- if (query.length > 1 && filteredMatches.length) {
162+ if (searchTerm.length > 1 && results.length) {
290163 if (scrollTo === "first") {
291- scrollToMatch(filteredMatches[0]);
164+ scrollToMatch(results[0]);
292165 }
293166 if (scrollTo === "closest") {
294- if (closestMatchToMiddle) {
295- scrollToMatch(closestMatchToMiddle);
167+ if (closestToMiddle) {
168+ scrollToMatch(closestToMiddle);
296169 }
297170 }
298171 if (scrollTo === "none") {
299- if (closestMatchToMiddle) {
300- setCurrentMatch(closestMatchToMiddle);
172+ if (closestToMiddle) {
173+ setCurrentMatch(closestToMiddle);
301174 } else {
302- setCurrentMatch(filteredMatches[0]);
175+ setCurrentMatch(results[0]);
303176 }
304177 }
305178 }
306179 },
307- [searchRef.current, debouncedInput, scrollToMatch, caseSensitive, useRegex],
180+ [
181+ searchTerm,
182+ caseSensitive,
183+ useRegex,
184+ searchRef,
185+ headerHeight,
186+ scrollToMatch,
187+ ],
308188 );
309189
310190 // Triggers that should cause immediate refresh of results to closest search value:
311- // Input change (debounced) and window click
312- const lastUpdateRef = useRef(0);
313191 useEffect(() => {
314- const debounce = () => {
315- debouncedInput.current = input;
316- lastUpdateRef.current = Date.now();
317- refreshSearch("closest");
318- };
319- const timeSinceLastUpdate = Date.now() - lastUpdateRef.current;
320- if (timeSinceLastUpdate >= SEARCH_DEBOUNCE) {
321- debounce();
192+ if (disabled || isResizing || !open) {
193+ setMatches([]);
322194 } else {
323- const handler = setTimeout(() => {
324- debounce();
325- }, SEARCH_DEBOUNCE - timeSinceLastUpdate);
326- return () => {
327- clearTimeout(handler);
328- };
195+ refreshSearch("closest");
329196 }
330- }, [refreshSearch, input]);
197+ }, [refreshSearch, open, disabled, isResizing]);
331198
332- // Could consider doing any window click but I only handled search div here
333- // Since usually only clicks in search div will cause content changes in search div
199+ // Clicks in search div can cause content changes that for some reason don't trigger resize
200+ // Refresh clicking within container
334201 useEffect(() => {
335202 const searchContainer = searchRef.current;
336203 if (!open || !searchContainer) return;
337204 const handleSearchRefClick = () => {
338- refreshSearch("none");
205+ setTimeout(() => {
206+ refreshSearch("none");
207+ }, 150);
339208 };
340209 searchContainer.addEventListener("click", handleSearchRefClick);
341210 return () => {
342211 searchContainer.removeEventListener("click", handleSearchRefClick);
343212 };
344- }, [searchRef.current, refreshSearch, open]);
345-
346- // Triggers that should cause results to temporarily disappear and then reload
347- // Active = LLM is generating, etc.
348- const active = useAppSelector((state) => state.session.isStreaming);
349-
350- useEffect(() => {
351- if (active || isResizing) setMatches([]);
352- else refreshSearch("none");
353- }, [refreshSearch, active]);
354-
355- useEffect(() => {
356- if (!open) setMatches([]);
357- else refreshSearch("closest");
358- }, [refreshSearch, open]);
359-
360- useEffect(() => {
361- refreshSearch("closest");
362- }, [refreshSearch, caseSensitive, useRegex]);
213+ }, [searchRef, refreshSearch, open]);
363214
364215 // Find widget component
365- const widget = useMemo(() => {
366- return (
367- <div
368- className={`fixed top-0 z-50 transition-all ${open ? "" : "-translate-y-full"} bg-vsc-background right-0 flex flex-row items-center gap-1.5 rounded-bl-lg border-0 border-b border-l border-solid border-zinc-700 pl-[3px] pr-3 sm:gap-2`}
369- >
370- <Input
371- disabled={active}
372- type="text"
373- ref={inputRef}
374- value={input}
375- onChange={(e) => {
376- setInput(e.target.value);
377- }}
378- placeholder="Search..."
379- />
380- <p className="xs:block hidden min-w-12 whitespace-nowrap px-1 text-center text-xs">
381- {matches.length === 0
382- ? "No results"
383- : `${(currentMatch?.index ?? 0) + 1} of ${matches.length}`}
384- </p>
385- <div className="hidden flex-row gap-0.5 sm:flex">
386- <HeaderButtonWithToolTip
387- tooltipPlacement="top-end"
388- text={"Previous Match"}
389- onClick={(e) => {
390- e.stopPropagation();
391- previousMatch();
392- }}
393- className="h-4 w-4 focus:ring"
394- disabled={matches.length < 2 || active}
395- >
396- <ArrowUpIcon className="h-4 w-4" />
397- </HeaderButtonWithToolTip>
398- <HeaderButtonWithToolTip
399- tooltipPlacement="top-end"
400- text={"Next Match"}
401- onClick={(e) => {
402- e.stopPropagation();
403- nextMatch();
404- }}
405- className="h-4 w-4 focus:ring"
406- disabled={matches.length < 2 || active}
407- >
408- <ArrowDownIcon className="h-4 w-4" />
409- </HeaderButtonWithToolTip>
410- </div>
216+ const widget = (
217+ <div
218+ className={`fixed top-0 z-50 transition-all ${open ? "" : "-translate-y-full"} bg-vsc-background right-0 flex flex-row items-center gap-1.5 rounded-bl-lg border-0 border-b border-l border-solid border-zinc-700 pl-[3px] pr-3 sm:gap-2`}
219+ >
220+ <Input
221+ disabled={disabled}
222+ type="text"
223+ ref={inputRef}
224+ value={currentValue}
225+ onChange={(e) => {
226+ setCurrentValue(e.target.value);
227+ }}
228+ placeholder="Search..."
229+ />
230+ <p className="xs:block hidden min-w-12 whitespace-nowrap px-1 text-center text-xs">
231+ {matches.length === 0
232+ ? "No results"
233+ : `${(currentMatch?.index ?? 0) + 1} of ${matches.length}`}
234+ </p>
235+ <div className="hidden flex-row gap-0.5 sm:flex">
411236 <HeaderButtonWithToolTip
412- disabled={active}
413- inverted={caseSensitive}
414237 tooltipPlacement="top-end"
415- text={
416- caseSensitive
417- ? "Turn off case sensitivity"
418- : "Turn on case sensitivity"
419- }
238+ text={"Previous Match"}
420239 onClick={(e) => {
421240 e.stopPropagation();
422- setCaseSensitive((curr) => !curr);
241+ previousMatch();
423242 }}
424- className="h-5 w-6 rounded-full border text-xs focus:outline-none focus:ring"
243+ className="h-4 w-4 focus:ring"
244+ disabled={matches.length < 2 || disabled}
425245 >
426- Aa
246+ <ArrowUpIcon className="h-4 w-4" />
427247 </HeaderButtonWithToolTip>
428- {/* TODO - add useRegex functionality */}
429- <HeaderButton
430- inverted={false}
431- onClick={() => setOpen(false)}
432- className="focus:ring"
248+ <HeaderButtonWithToolTip
249+ tooltipPlacement="top-end"
250+ text={"Next Match"}
251+ onClick={(e) => {
252+ e.stopPropagation();
253+ nextMatch();
254+ }}
255+ className="h-4 w-4 focus:ring"
256+ disabled={matches.length < 2 || disabled}
433257 >
434- <XMarkIcon className="h-4 w-4" />
435- </HeaderButton>
258+ <ArrowDownIcon className="h-4 w-4" />
259+ </HeaderButtonWithToolTip>
436260 </div>
437- );
438- }, [
439- open,
440- input,
441- inputRef,
442- caseSensitive,
443- matches,
444- currentMatch,
445- previousMatch,
446- nextMatch,
447- ]);
261+ <HeaderButtonWithToolTip
262+ disabled={disabled}
263+ inverted={caseSensitive}
264+ tooltipPlacement="top-end"
265+ text={
266+ caseSensitive
267+ ? "Turn off case sensitivity"
268+ : "Turn on case sensitivity"
269+ }
270+ onClick={(e) => {
271+ e.stopPropagation();
272+ setCaseSensitive((curr) => !curr);
273+ }}
274+ className="h-5 w-6 rounded-full border text-xs focus:outline-none focus:ring"
275+ >
276+ Aa
277+ </HeaderButtonWithToolTip>
278+ {/* TODO - add useRegex functionality */}
279+ <HeaderButton
280+ inverted={false}
281+ onClick={() => setOpen(false)}
282+ className="focus:ring"
283+ >
284+ <XMarkIcon className="h-4 w-4" />
285+ </HeaderButton>
286+ </div>
287+ );
448288
449289 // Generate the highlight overlay elements
450290 const highlights = useMemo(() => {
451291 return matches.map((match) => (
452292 <HighlightOverlay
453- {...match.overlayRectangle}
293+ rectangle={match.overlayRectangle}
454294 isCurrent={currentMatch?.index === match.index}
455295 />
456296 ));
457297 }, [matches, currentMatch]);
458298
459299 return {
460- matches,
461300 highlights,
462- inputRef,
463- input: debouncedInput,
464- setInput,
465- open,
466- setOpen,
467301 widget,
468302 };
469303 };
added gui/src/components/find/findWidgetSearch.ts +146 −0
@@ -0,0 +1,146 @@
1+export interface Rectangle {
2+ top: number;
3+ left: number;
4+ width: number;
5+ height: number;
6+}
7+
8+export interface SearchMatch {
9+ index: number;
10+ textNode: Text;
11+ overlayRectangle: Rectangle;
12+}
13+
14+interface SearchOptions {
15+ caseSensitive: boolean;
16+ useRegex: boolean;
17+ offsetHeight: number;
18+}
19+
20+export const searchWithinContainer = (
21+ containerRef: React.RefObject<HTMLDivElement>,
22+ searchQuery: string,
23+ options: SearchOptions,
24+): {
25+ results: SearchMatch[];
26+ closestToMiddle: SearchMatch | null;
27+} => {
28+ const searchContainer = containerRef.current;
29+
30+ if (!searchContainer || !searchQuery) {
31+ return {
32+ results: [],
33+ closestToMiddle: null,
34+ };
35+ }
36+ const query = options.caseSensitive ? searchQuery : searchQuery.toLowerCase();
37+
38+ // First grab all text nodes
39+ // Skips any elements with the "find-widget-skip" class
40+ const textNodes: Text[] = [];
41+ const walker = document.createTreeWalker(
42+ searchContainer,
43+ NodeFilter.SHOW_ALL,
44+ {
45+ acceptNode: (node) => {
46+ if (node.nodeType === Node.ELEMENT_NODE) {
47+ if ((node as Element).classList.contains("find-widget-skip"))
48+ return NodeFilter.FILTER_REJECT;
49+ return NodeFilter.FILTER_ACCEPT;
50+ } else if (node.nodeType === Node.TEXT_NODE) {
51+ if (!node.nodeValue) return NodeFilter.FILTER_REJECT;
52+ const nodeValue = options.caseSensitive
53+ ? node.nodeValue
54+ : node.nodeValue.toLowerCase();
55+ if (nodeValue.includes(query)) return NodeFilter.FILTER_ACCEPT;
56+ }
57+ return NodeFilter.FILTER_REJECT;
58+ },
59+ },
60+ );
61+
62+ while (walker.nextNode()) {
63+ if (walker.currentNode.nodeType === Node.ELEMENT_NODE) continue;
64+ textNodes.push(walker.currentNode as Text);
65+ }
66+
67+ // Now walk through each node match and extract search results
68+ // One node can have several matches
69+ const newMatches: SearchMatch[] = [];
70+ textNodes.forEach((textNode, idx) => {
71+ // Hacky way to detect code blocks that be wider than client and cause absolute positioning to fail
72+ const highlightFullLine =
73+ textNode.parentElement?.className.includes("hljs");
74+
75+ let nodeTextValue = options.caseSensitive
76+ ? textNode.nodeValue
77+ : textNode.nodeValue.toLowerCase();
78+ let startIndex = 0;
79+ while ((startIndex = nodeTextValue.indexOf(query, startIndex)) !== -1) {
80+ // Create a range to measure the size and position of the match
81+ const range = document.createRange();
82+ range.setStart(textNode, startIndex);
83+ const endIndex = startIndex + query.length;
84+ range.setEnd(textNode, endIndex);
85+ const rect = range.getBoundingClientRect();
86+ range.detach();
87+ startIndex = endIndex;
88+
89+ const top =
90+ rect.top +
91+ searchContainer.clientTop +
92+ searchContainer.scrollTop -
93+ options.offsetHeight;
94+
95+ const left =
96+ rect.left + searchContainer.clientLeft + searchContainer.scrollLeft;
97+
98+ // Build a match result and push to matches
99+ const newMatch: SearchMatch = {
100+ index: 0, // will set later
101+ textNode,
102+ overlayRectangle: {
103+ top,
104+ left: highlightFullLine ? 2 : left,
105+ width: highlightFullLine
106+ ? searchContainer.clientWidth - 4
107+ : rect.width, // equivalent of adding 2 px x padding
108+ height: rect.height,
109+ },
110+ };
111+ newMatches.push(newMatch);
112+
113+ if (highlightFullLine) {
114+ break; // Since highlighting full line no need for multiple overlays, will cause darker highlight
115+ }
116+ }
117+ });
118+
119+ // There will still be duplicate full lines when multiple text nodes are in the same line (e.g. Code highlights)
120+ // Filter them out by using the overlay rectangle as a hash key
121+ const matchHash = Object.fromEntries(
122+ newMatches.map((match) => [JSON.stringify(match.overlayRectangle), match]),
123+ );
124+ const filteredMatches = Object.values(matchHash).map((match, index) => ({
125+ ...match,
126+ index,
127+ }));
128+
129+ // Find the match closest to the vertical middle of the container
130+ const verticalMiddle =
131+ searchContainer.scrollTop + searchContainer.clientHeight / 2;
132+ let closestDist = Infinity;
133+ let closestMatchToMiddle: SearchMatch | null = null;
134+ filteredMatches.forEach((match) => {
135+ const dist = Math.abs(verticalMiddle - match.overlayRectangle.top);
136+ if (dist < closestDist) {
137+ closestDist = dist;
138+ closestMatchToMiddle = match;
139+ }
140+ });
141+
142+ return {
143+ results: filteredMatches,
144+ closestToMiddle: closestMatchToMiddle,
145+ };
146+};
added gui/src/components/find/useDebounce.ts +19 −0
@@ -0,0 +1,19 @@
1+import { useEffect, useState } from "react";
2+
3+function useDebounceValue<T>(value: T, delay: number = 500): T {
4+ const [debouncedValue, setDebouncedValue] = useState<T>(value);
5+
6+ useEffect(() => {
7+ const timer = setTimeout(() => {
8+ setDebouncedValue(value);
9+ }, delay);
10+
11+ return () => {
12+ clearTimeout(timer);
13+ };
14+ }, [value, delay]);
15+
16+ return debouncedValue;
17+}
18+
19+export default useDebounceValue;
added gui/src/components/find/useElementSize.ts +81 −0
@@ -0,0 +1,81 @@
1+import { RefObject, useCallback, useEffect, useState } from "react";
2+
3+interface ElementSize {
4+ clientWidth: number;
5+ clientHeight: number;
6+ scrollWidth: number;
7+ scrollHeight: number;
8+ isResizing: boolean;
9+}
10+
11+interface UseElementSizeOptions {
12+ debounceMs?: number;
13+}
14+
15+export const useElementSize = (
16+ ref: RefObject<HTMLElement>,
17+ debounceMs = 250,
18+): ElementSize => {
19+ const [size, setSize] = useState<ElementSize>({
20+ clientWidth: 0,
21+ clientHeight: 0,
22+ scrollWidth: 0,
23+ scrollHeight: 0,
24+ isResizing: false,
25+ });
26+
27+ // Debounced update function
28+ const debouncedSetSize = useCallback(
29+ (measurements: Omit<ElementSize, "isResizing">) => {
30+ let timeoutId: NodeJS.Timeout;
31+
32+ setSize((prev) => ({ ...prev, isResizing: true }));
33+
34+ timeoutId = setTimeout(() => {
35+ setSize({
36+ ...measurements,
37+ isResizing: false,
38+ });
39+ }, debounceMs);
40+
41+ return () => clearTimeout(timeoutId);
42+ },
43+ [debounceMs],
44+ );
45+
46+ useEffect(() => {
47+ if (!ref.current) return;
48+
49+ const updateSize = () => {
50+ const element = ref.current;
51+ if (!element) return;
52+
53+ const measurements = {
54+ clientWidth: element.clientWidth,
55+ clientHeight: element.clientHeight,
56+ scrollWidth: element.scrollWidth,
57+ scrollHeight: element.scrollHeight,
58+ };
59+
60+ debouncedSetSize(measurements);
61+ };
62+
63+ // Create ResizeObserver instance
64+ const resizeObserver = new ResizeObserver(() => {
65+ updateSize();
66+ });
67+
68+ // Start observing the element
69+ resizeObserver.observe(ref.current);
70+
71+ // Initial size calculation
72+ updateSize();
73+
74+ // Cleanup
75+ return () => {
76+ resizeObserver.disconnect();
77+ };
78+ }, [ref, debouncedSetSize]);
79+
80+ return size;
81+};
modified gui/src/components/gui/Alert.tsx +1 −1
@@ -39,7 +39,7 @@
3939 const { Icon } = ALERT_CONFIGS[type];
4040
4141 return (
42- <div className="rounded-lg border-l-4 bg-[color:var(--vscode-editor-foreground)] p-4 opacity-70 shadow-none">
42+ <div className="bg-editor-foreground rounded-lg border-l-4 p-4 opacity-70 shadow-none">
4343 <div className="flex items-start">
4444 <Icon
4545 className="h-6 min-h-5 w-6 min-w-5"
modified gui/src/components/index.ts +22 −109
@@ -1,114 +1,31 @@
11 import styled from "styled-components";
2-import { getFontSize } from "../util";
3-
4-export const VSC_INPUT_BACKGROUND_VAR = "--vscode-input-background";
5-export const VSC_BACKGROUND_VAR = "--vscode-sideBar-background";
6-export const VSC_FOREGROUND_VAR = "--vscode-editor-foreground";
7-export const VSC_BUTTON_BACKGROUND_VAR = "--vscode-button-background";
8-export const VSC_BUTTON_FOREGROUND_VAR = "--vscode-button-foreground";
9-export const VSC_EDITOR_BACKGROUND_VAR = "--vscode-editor-background";
10-export const VSC_LIST_SELECTION_BACKGROUND_VAR =
11- "--vscode-list-activeSelectionBackground";
12-export const VSC_FOCUS_BORDER_VAR = "--vscode-focusBorder";
13-export const VSC_LIST_ACTIVE_FOREGROUND_VAR =
14- "--vscode-quickInputList-focusForeground";
15-export const VSC_QUICK_INPUT_BACKGROUND_VAR = "--vscode-quickInput-background";
16-export const VSC_INPUT_BORDER_VAR = "--vscode-input-border";
17-export const VSC_BADGE_BACKGROUND_VAR = "--vscode-badge-background";
18-export const VSC_BADGE_FOREGROUND_VAR = "--vscode-badge-foreground";
19-export const VSC_COMMAND_CENTER_ACTIVE_BORDER_VAR =
20- "--vscode-commandCenter-activeBorder";
21-export const VSC_COMMAND_CENTER_INACTIVE_BORDER_VAR =
22- "--vscode-commandCenter-inactiveBorder";
23-export const VSC_FIND_MATCH_SELECTED_VAR =
24- "--vscode-editor-findMatchHighlightBackground";
25-
26-export const VSC_THEME_COLOR_VARS = [
27- VSC_INPUT_BACKGROUND_VAR,
28- VSC_BACKGROUND_VAR,
29- VSC_FOREGROUND_VAR,
30- VSC_BUTTON_BACKGROUND_VAR,
31- VSC_BUTTON_FOREGROUND_VAR,
32- VSC_EDITOR_BACKGROUND_VAR,
33- VSC_LIST_SELECTION_BACKGROUND_VAR,
34- VSC_FOCUS_BORDER_VAR,
35- VSC_LIST_ACTIVE_FOREGROUND_VAR,
36- VSC_QUICK_INPUT_BACKGROUND_VAR,
37- VSC_INPUT_BORDER_VAR,
38- VSC_BADGE_BACKGROUND_VAR,
39- VSC_BADGE_FOREGROUND_VAR,
40- VSC_COMMAND_CENTER_ACTIVE_BORDER_VAR,
41- VSC_COMMAND_CENTER_INACTIVE_BORDER_VAR,
42- VSC_FIND_MATCH_SELECTED_VAR,
43-];
2+import { varWithFallback } from "../styles/theme";
443
4+// DEPRECATED - avoid using these where possible, use tailwind classes instead
455 export const defaultBorderRadius = "5px";
466 export const lightGray = "#999998";
477 export const greenButtonColor = "#189e72";
488
49-export const vscInputBackground = `var(${VSC_INPUT_BACKGROUND_VAR}, rgb(45 45 45))`;
50-export const vscQuickInputBackground = `var(${VSC_QUICK_INPUT_BACKGROUND_VAR}, ${VSC_INPUT_BACKGROUND_VAR}, rgb(45 45 45))`;
51-export const vscBackground = `var(${VSC_BACKGROUND_VAR}, rgb(30 30 30))`;
52-export const vscForeground = `var(${VSC_FOREGROUND_VAR}, #fff)`;
53-export const vscButtonBackground = `var(${VSC_BUTTON_BACKGROUND_VAR}, #1bbe84)`;
54-export const vscButtonForeground = `var(${VSC_BUTTON_FOREGROUND_VAR}, #ffffff)`;
55-export const vscEditorBackground = `var(${VSC_EDITOR_BACKGROUND_VAR}, ${VSC_BACKGROUND_VAR}, rgb(30 30 30))`;
56-export const vscListActiveBackground = `var(${VSC_LIST_SELECTION_BACKGROUND_VAR}, #1bbe84)`;
57-export const vscFocusBorder = `var(${VSC_FOCUS_BORDER_VAR}, #1bbe84)`;
58-export const vscListActiveForeground = `var(${VSC_LIST_ACTIVE_FOREGROUND_VAR}, ${VSC_FOREGROUND_VAR})`;
59-export const vscInputBorder = `var(${VSC_INPUT_BORDER_VAR}, ${lightGray})`;
60-export const vscInputBorderFocus = `var(${VSC_FOCUS_BORDER_VAR}, ${lightGray})`;
61-export const vscBadgeBackground = `var(${VSC_BADGE_BACKGROUND_VAR}, #1bbe84)`;
62-export const vscBadgeForeground = `var(${VSC_BADGE_FOREGROUND_VAR}, #ffffff)`;
63-export const vscCommandCenterActiveBorder = `var(${VSC_COMMAND_CENTER_ACTIVE_BORDER_VAR}, #1bbe84)`;
64-export const vscCommandCenterInactiveBorder = `var(${VSC_COMMAND_CENTER_INACTIVE_BORDER_VAR}, #1bbe84)`;
65-export const vscFindMatchSelected = `var(${VSC_FIND_MATCH_SELECTED_VAR}, rgba(255, 223, 0))`;
66-
67-export function parseHexColor(hexColor: string): {
68- r: number;
69- g: number;
70- b: number;
71-} {
72- if (hexColor.startsWith("#")) {
73- hexColor = hexColor.slice(1);
74- }
75-
76- if (hexColor.length > 6) {
77- hexColor = hexColor.slice(0, 6);
78- }
79-
80- const r = parseInt(hexColor.substring(0, 2), 16);
81- const g = parseInt(hexColor.substring(2, 4), 16);
82- const b = parseInt(hexColor.substring(4, 6), 16);
83-
84- return { r, g, b };
85-}
86-
87-export function parseColorForHex(colorVar: string): string {
88- const value = getComputedStyle(document.documentElement).getPropertyValue(
89- colorVar,
90- );
91- if (value.startsWith("#")) {
92- return value.slice(0, 7);
93- }
94-
95- // Parse rgb/rgba
96- const rgbValues = value
97- .slice(value.startsWith("rgba") ? 5 : 4, -1)
98- .split(",")
99- .map((x) => x.trim())
100- .filter((_, i) => i < 3) // Only take the first 3 values (RGB, ignore alpha)
101- .map((x) => parseInt(x, 10));
102-
103- let hex =
104- "#" +
105- rgbValues
106- .map((x) => x.toString(16))
107- .map((x) => (x.length === 1 ? "0" + x : x))
108- .join("");
109-
110- return hex;
111-}
9+export const vscInputBackground = varWithFallback("input-background");
10+export const vscQuickInputBackground = varWithFallback("input-background");
11+export const vscBackground = varWithFallback("background");
12+export const vscForeground = varWithFallback("foreground");
13+export const vscButtonBackground = varWithFallback("primary-background");
14+export const vscButtonForeground = varWithFallback("primary-foreground");
15+export const vscEditorBackground = varWithFallback("editor-background");
16+export const vscListActiveBackground = varWithFallback("list-active");
17+export const vscFocusBorder = varWithFallback("border-focus");
18+export const vscListActiveForeground = varWithFallback(
19+ "list-active-foreground",
20+);
21+export const vscInputBorder = varWithFallback("input-border");
22+export const vscInputBorderFocus = varWithFallback("border-focus");
23+export const vscBadgeBackground = varWithFallback("badge-background");
24+export const vscBadgeForeground = varWithFallback("badge-foreground");
25+export const vscCommandCenterActiveBorder = varWithFallback(
26+ "command-border-focus",
27+);
28+export const vscCommandCenterInactiveBorder = varWithFallback("command-border");
11229
11330 export const Button = styled.button`
11431 padding: 6px 12px;
@@ -226,10 +143,6 @@
226143 }
227144 `;
228145
229-export const Label = styled.label<{ fontSize?: number }>`
230- font-size: ${(props) => props.fontSize || getFontSize()}px;
231-`;
232-
233146 export const HeaderButton = styled.button<{
234147 inverted: boolean | undefined;
235148 backgroundColor?: string;
deleted gui/src/components/mainInput/CodeToEditCard.tsx +0 −181
@@ -1,181 +0,0 @@
1-import { ChevronRightIcon, XMarkIcon } from "@heroicons/react/24/outline";
2-import { SetCodeToEditPayload } from "core";
3-import { getMarkdownLanguageTagForFile } from "core/util";
4-import { getUriPathBasename } from "core/util/uri";
5-import { useContext, useMemo, useState } from "react";
6-import { useDispatch } from "react-redux";
7-import styled from "styled-components";
8-import { IdeMessengerContext } from "../../context/IdeMessenger";
9-import { useAppSelector } from "../../redux/hooks";
10-import { clearCodeToEdit } from "../../redux/slices/editModeState";
11-import { getMetaKeyLabel } from "../../util";
12-import FileIcon from "../FileIcon";
13-import StyledMarkdownPreview from "../StyledMarkdownPreview";
14-import { useFontSize } from "../ui/font";
15-
16-const NoPaddingWrapper = styled.div`
17- > * {
18- margin: 0 !important;
19- padding: 0 !important;
20- }
21-
22- pre {
23- margin: 0 !important;
24- padding: 0px 0px 0px 10px !important;
25- }
26-`;
27-
28-interface CodeToEditItemProps {
29- code: SetCodeToEditPayload;
30-}
31-
32-function CodeToEditItem({ code }: CodeToEditItemProps) {
33- const dispatch = useDispatch();
34- const ideMessenger = useContext(IdeMessengerContext);
35- const [showCodeSnippet, setShowCodeSnippet] = useState(false);
36-
37- function onDelete() {
38- dispatch(clearCodeToEdit());
39- ideMessenger.post("edit/clearDecorations", undefined);
40- }
41-
42- const fileName = getUriPathBasename(code.filepath);
43-
44- let isInsertion = false;
45- let title = fileName;
46-
47- if ("range" in code) {
48- const start = code.range.start.line + 1;
49- const end = code.range.end.line + 1;
50-
51- isInsertion = start === end;
52-
53- title += isInsertion
54- ? ` - Inserting at line ${start}`
55- : ` (${start} - ${end})`;
56- }
57-
58- const source =
59- "```" +
60- getMarkdownLanguageTagForFile(code.filepath) +
61- "\n" +
62- code.contents +
63- "\n" +
64- "```";
65-
66- async function onClickFilename() {
67- if ("range" in code) {
68- await ideMessenger.ide.showLines(
69- code.filepath,
70- code.range.start.line,
71- code.range.end.line,
72- );
73- } else {
74- await ideMessenger.ide.openFile(code.filepath);
75- }
76- }
77-
78- const smallFont = useFontSize(-3);
79-
80- const iconClass =
81- "text-lightgray hover:bg-lightgray hover:text-vsc-foreground h-3.5 w-3.5 cursor-pointer rounded-sm p-0.5 hover:bg-opacity-20";
82-
83- return (
84- <div className="flex flex-col gap-1 py-0.5">
85- <div className="group flex flex-row items-center justify-start gap-1.5 px-1">
86- <span
87- className="hidden flex-shrink-0 pl-2 font-semibold text-gray-400 sm:flex"
88- style={{
89- fontSize: smallFont,
90- }}
91- >
92- Code to edit
93- </span>
94- {/* <CodeBracketIcon className="h-3 w-3 flex-shrink-0 text-gray-400 sm:hidden" /> */}
95- <div
96- className={`hover:bg-lightgray flex flex-1 cursor-pointer items-center justify-between rounded transition-colors hover:bg-opacity-20 ${showCodeSnippet && "bg-lightgray bg-opacity-20"}`}
97- onClick={() => {
98- if (!isInsertion) {
99- setShowCodeSnippet((showCodeSnippet) => !showCodeSnippet);
100- }
101- }}
102- >
103- <div className="flex items-center gap-0.5">
104- <FileIcon filename={code.filepath} height={"18px"} width={"18px"} />
105- <span
106- className="line-clamp-1 text-xs hover:underline"
107- onClick={(e) => {
108- e.stopPropagation();
109- void onClickFilename();
110- }}
111- >
112- {title}
113- </span>
114- </div>
115-
116- <div className="invisible flex items-center group-hover:visible">
117- <ChevronRightIcon
118- onClick={(e) => {
119- e.stopPropagation();
120- setShowCodeSnippet((val) => !val);
121- }}
122- className={`text-lightgray hover:bg-lightgray hover:text-vsc-foreground h-3.5 w-3.5 cursor-pointer rounded-sm p-0.5 hover:bg-opacity-20 ${showCodeSnippet ? "rotate-90" : ""} ${isInsertion ? "hidden" : ""}`}
123- />
124- <div className="flex items-center">
125- <XMarkIcon
126- onClick={(e) => {
127- e.stopPropagation();
128- void onDelete();
129- }}
130- className={iconClass}
131- />
132- </div>
133- </div>
134- </div>
135- </div>
136- {showCodeSnippet && (
137- <div className="!m-0 max-h-48 overflow-y-auto !p-0">
138- <NoPaddingWrapper>
139- <StyledMarkdownPreview source={source} />
140- </NoPaddingWrapper>
141- </div>
142- )}
143- </div>
144- );
145-}
146-
147-export default function CodeToEditCard() {
148- // Array from previous multi-file edit
149- const codeToEditArray = useAppSelector(
150- (state) => state.editModeState.codeToEdit,
151- );
152- const codeToEdit = useMemo(() => {
153- return codeToEditArray[0];
154- }, [codeToEditArray]);
155-
156- const metaKeyLabel = useMemo(() => {
157- return getMetaKeyLabel();
158- }, []);
159-
160- const tinyFont = useFontSize(-3);
161-
162- return (
163- <div className="bg-vsc-editor-background mx-3 flex flex-col rounded-t-lg py-1">
164- {codeToEdit ? (
165- <CodeToEditItem code={codeToEdit} />
166- ) : (
167- <>
168- <span
169- className="text-balance px-3 text-center font-semibold text-gray-400"
170- style={{
171- fontSize: tinyFont,
172- }}
173- >
174- {`To edit code, highlight it and press `}
175- <kbd>{metaKeyLabel}</kbd> <kbd>I</kbd>
176- </span>
177- </>
178- )}
179- </div>
180- );
181-}
modified gui/src/components/mainInput/ContinueInputBox.tsx +17 −18
@@ -83,15 +83,15 @@
8383 const availableContextProviders = useAppSelector(
8484 (state) => state.config.config.contextProviders,
8585 );
86- const mode = useAppSelector((store) => store.session.mode);
86+ const isInEdit = useAppSelector((store) => store.session.isInEdit);
8787 const editModeState = useAppSelector((state) => state.editModeState);
8888
8989 const filteredSlashCommands = useMemo(() => {
90- return mode === "edit" ? [] : availableSlashCommands;
91- }, [mode, availableSlashCommands]);
90+ return isInEdit ? [] : availableSlashCommands;
91+ }, [isInEdit, availableSlashCommands]);
9292
9393 const filteredContextProviders = useMemo(() => {
94- if (mode === "edit") {
94+ if (isInEdit) {
9595 return (
9696 availableContextProviders?.filter(
9797 (provider) =>
@@ -101,22 +101,21 @@
101101 }
102102
103103 return availableContextProviders ?? [];
104- }, [availableContextProviders, mode]);
104+ }, [availableContextProviders, isInEdit]);
105105
106- const historyKey = mode === "edit" ? "edit" : "chat";
107- const placeholder = mode === "edit" ? "Describe changes" : undefined;
106+ const historyKey = isInEdit ? "edit" : "chat";
107+ const placeholder = isInEdit ? "Edit selected code" : undefined;
108108
109- const toolbarOptions: ToolbarOptions =
110- mode === "edit"
111- ? {
112- hideAddContext: false,
113- hideImageUpload: false,
114- hideUseCodebase: true,
115- hideSelectModel: false,
116- enterText:
117- editModeState.applyState.status === "done" ? "Retry" : "Edit",
118- }
119- : {};
109+ const toolbarOptions: ToolbarOptions = isInEdit
110+ ? {
111+ hideAddContext: false,
112+ hideImageUpload: false,
113+ hideUseCodebase: true,
114+ hideSelectModel: false,
115+ enterText:
116+ editModeState.applyState.status === "done" ? "Retry" : "Edit",
117+ }
118+ : {};
120119
121120 const { appliedRules = [], contextItems = [] } = props;
122121
deleted gui/src/components/mainInput/EditModeDetails.tsx +0 −59
@@ -1,59 +0,0 @@
1-import { useContext } from "react";
2-import { IdeMessengerContext } from "../../context/IdeMessenger";
3-import { useAppDispatch, useAppSelector } from "../../redux/hooks";
4-import { exitEditMode } from "../../redux/thunks/editMode";
5-import AcceptRejectDiffButtons from "../AcceptRejectDiffButtons";
6-import { useMainEditor } from "./TipTapEditor";
7-
8-const EditModeDetails = () => {
9- const isStreaming = useAppSelector((store) => store.session.isStreaming);
10- const mode = useAppSelector((store) => store.session.mode);
11- const dispatch = useAppDispatch();
12- const editApplyState = useAppSelector(
13- (store) => store.editModeState.applyState,
14- );
15- const { mainEditor } = useMainEditor();
16- const ideMessenger = useContext(IdeMessengerContext);
17-
18- if (mode !== "edit") {
19- return null;
20- }
21- if (isStreaming) {
22- return null;
23- }
24- if (editApplyState.status === "done") {
25- const plural = editApplyState.numDiffs === 1 ? "" : "s";
26- return (
27- <>
28- <div className="flex flex-col items-center justify-center pb-1 pt-3 text-xs italic text-gray-400">
29- <span className="">{`${editApplyState.numDiffs} diff${plural} remaining`}</span>
30- </div>
31- <AcceptRejectDiffButtons
32- applyStates={[editApplyState]}
33- onAcceptOrReject={async (outcome) => {
34- if (outcome === "acceptDiff") {
35- await dispatch(exitEditMode({}));
36- ideMessenger.post("focusEditor", undefined);
37- } else {
38- mainEditor?.commands.focus();
39- }
40- }}
41- />
42- </>
43- );
44- }
45-
46- // Will only still show if not all accepted
47- if (editApplyState.status === "closed") {
48- return (
49- <div>
50- <span></span>
51- </div>
52- );
53- }
54-
55- // Not started/streaming
56- return null;
57-};
58-
59-export default EditModeDetails;
modified gui/src/components/mainInput/InputToolbar.tsx +18 −16
@@ -10,7 +10,7 @@
1010 selectCurrentToolCallApplyState,
1111 } from "../../redux/selectors/selectCurrentToolCall";
1212 import { selectSelectedChatModel } from "../../redux/slices/configSlice";
13-import { exitEditMode } from "../../redux/thunks/editMode";
13+import { exitEdit } from "../../redux/thunks/edit";
1414 import {
1515 getAltKeyLabel,
1616 getMetaKeyLabel,
@@ -18,7 +18,7 @@
1818 } from "../../util";
1919 import { ToolTip } from "../gui/Tooltip";
2020 import ModelSelect from "../modelSelection/ModelSelect";
21-import ModeSelect from "../modelSelection/ModeSelect";
21+import { ModeSelect } from "../ModeSelect";
2222 import { useFontSize } from "../ui/font";
2323 import { EnterButton } from "./InputToolbar/EnterButton";
2424 import HoverItem from "./InputToolbar/HoverItem";
@@ -49,7 +49,7 @@
4949 const fileInputRef = useRef<HTMLInputElement | null>(null);
5050 const defaultModel = useAppSelector(selectSelectedChatModel);
5151 const useActiveFile = useAppSelector(selectUseActiveFile);
52- const mode = useAppSelector((store) => store.session.mode);
52+ const isInEdit = useAppSelector((store) => store.session.isInEdit);
5353 const codeToEdit = useAppSelector((store) => store.editModeState.codeToEdit);
5454 const toolCallState = useAppSelector(selectCurrentToolCall);
5555 const currentToolCallApplyState = useAppSelector(
@@ -58,7 +58,7 @@
5858
5959 const isEnterDisabled =
6060 props.disabled ||
61- (mode === "edit" && codeToEdit.length === 0) ||
61+ (isInEdit && codeToEdit.length === 0) ||
6262 toolCallState?.status === "generated" ||
6363 (currentToolCallApplyState &&
6464 currentToolCallApplyState.status !== "closed");
@@ -87,19 +87,21 @@
8787 }}
8888 >
8989 <div className="xs:gap-1.5 flex flex-row items-center gap-1">
90- <HoverItem data-tooltip-id="mode-select-tooltip" className="!p-0">
91- <ModeSelect />
92- <ToolTip id="mode-select-tooltip" place="top">
93- Select Mode
94- </ToolTip>
95- </HoverItem>
90+ {!isInEdit && (
91+ <HoverItem data-tooltip-id="mode-select-tooltip" className="!p-0">
92+ <ModeSelect />
93+ <ToolTip id="mode-select-tooltip" place="top">
94+ Select Mode
95+ </ToolTip>
96+ </HoverItem>
97+ )}
9698 <HoverItem data-tooltip-id="model-select-tooltip" className="!p-0">
9799 <ModelSelect />
98100 <ToolTip id="model-select-tooltip" place="top">
99101 Select Model
100102 </ToolTip>
101103 </HoverItem>
102- <div className="xs:flex -mb-1 hidden items-center text-gray-400 transition-colors duration-200">
104+ <div className="xs:flex text-description -mb-1 hidden items-center transition-colors duration-200">
103105 {props.toolbarOptions?.hideImageUpload ||
104106 (supportsImages && (
105107 <>
@@ -149,12 +151,12 @@
149151 </div>
150152
151153 <div
152- className="flex items-center gap-2 whitespace-nowrap text-gray-400"
154+ className="text-description flex items-center gap-2 whitespace-nowrap"
153155 style={{
154156 fontSize: tinyFont,
155157 }}
156158 >
157- {!props.toolbarOptions?.hideUseCodebase && mode !== "edit" && (
159+ {!props.toolbarOptions?.hideUseCodebase && !isInEdit && (
158160 <div
159161 className={`${toolsSupported ? "md:flex" : "int:flex"} hover:underline" hidden transition-colors duration-200`}
160162 >
@@ -184,16 +186,16 @@
184186 </div>
185187 )}
186188
187- {mode === "edit" && (
189+ {isInEdit && (
188190 <HoverItem
189191 className="hidden hover:underline sm:flex"
190192 onClick={async () => {
191- dispatch(exitEditMode({}));
193+ void dispatch(exitEdit({}));
192194 ideMessenger.post("focusEditor", undefined);
193195 }}
194196 >
195197 <span>
196- <i>Esc</i> to exit
198+ <i>Esc</i> to exit Edit
197199 </span>
198200 </HoverItem>
199201 )}
deleted gui/src/components/mainInput/Lump/BlockSettingsTopToolbar.tsx +0 −206
@@ -1,206 +0,0 @@
1-import {
2- BookOpenIcon,
3- ChatBubbleLeftIcon,
4- ChevronLeftIcon,
5- CubeIcon,
6- EllipsisHorizontalIcon,
7- ExclamationTriangleIcon,
8- PencilIcon,
9- Squares2X2Icon,
10- WrenchScrewdriverIcon,
11-} from "@heroicons/react/24/outline";
12-import { ReactNode } from "react";
13-import { vscBadgeForeground } from "../..";
14-import { useAppSelector } from "../../../redux/hooks";
15-import { ToolTip } from "../../gui/Tooltip";
16-import AssistantSelect from "../../modelSelection/platform/AssistantSelect";
17-import { useFontSize } from "../../ui/font";
18-import HoverItem from "../InputToolbar/HoverItem";
19-import { useLump } from "./LumpContext";
20-import { ErrorsSectionTooltip } from "./sections/errors/ErrorsSectionTooltip";
21-import { McpSectionTooltip } from "./sections/mcp/MCPTooltip";
22-import { ToolsSectionTooltip } from "./sections/tool-policies/ToolPoliciesSectionTooltip";
23-
24-interface BlockSettingsToolbarIcon {
25- title: string;
26- tooltip: ReactNode;
27- icon: React.ComponentType<any>;
28- itemCount?: number;
29- onClick: () => void;
30- isSelected?: boolean;
31- className?: string;
32-}
33-
34-interface Section {
35- id: string;
36- title: string;
37- tooltip: ReactNode;
38- icon: React.ComponentType<any>;
39-}
40-
41-const sections: Section[] = [
42- { id: "models", title: "Models", tooltip: "Models", icon: CubeIcon },
43- { id: "rules", title: "Rules", tooltip: "Rules", icon: PencilIcon },
44- { id: "docs", title: "Docs", tooltip: "Docs", icon: BookOpenIcon },
45- {
46- id: "prompts",
47- title: "Prompts",
48- tooltip: "Prompts",
49- icon: ChatBubbleLeftIcon,
50- },
51- {
52- id: "tools",
53- title: "Tools",
54- tooltip: <ToolsSectionTooltip />,
55- icon: WrenchScrewdriverIcon,
56- },
57- {
58- id: "mcp",
59- title: "MCP",
60- tooltip: <McpSectionTooltip />,
61- icon: Squares2X2Icon,
62- },
63- {
64- id: "error",
65- title: "Errors",
66- tooltip: <ErrorsSectionTooltip />,
67- icon: ExclamationTriangleIcon,
68- },
69-];
70-
71-function BlockSettingsToolbarIcon(
72- props: BlockSettingsToolbarIcon & { sectionId?: string },
73-) {
74- const isErrorSection = props.sectionId === "error";
75-
76- const id = `block-settings-toolbar-icon-${props.sectionId}`;
77-
78- const fontSize = useFontSize(-3);
79- return (
80- <>
81- <HoverItem
82- px={0}
83- onClick={props.onClick}
84- data-testid={id}
85- data-tooltip-id={id}
86- >
87- <div
88- role="button"
89- tabIndex={0}
90- onKeyDown={(e) => {
91- if (e.key === "Enter" || e.key === " ") {
92- e.preventDefault();
93- props.onClick();
94- }
95- }}
96- className={`${
97- props.isSelected
98- ? isErrorSection
99- ? "bg-red-600"
100- : "bg-badge"
101- : undefined
102- } relative flex select-none items-center rounded-full px-[3px] transition-all duration-200 focus:outline-none focus-visible:ring-2 focus-visible:ring-blue-500/50 sm:px-1 ${props.className || ""}`}
103- >
104- <props.icon
105- className={`h-[13px] w-[13px] flex-shrink-0 hover:brightness-125 ${
106- isErrorSection ? "text-red-600" : ""
107- }`}
108- style={{
109- color: props.isSelected ? vscBadgeForeground : undefined,
110- }}
111- aria-hidden="true"
112- />
113- <div
114- style={{ fontSize }}
115- className={`overflow-hidden transition-all duration-200 ${
116- props.isSelected ? "ml-1 w-auto opacity-100" : "w-0 opacity-0"
117- }`}
118- >
119- <span
120- className="whitespace-nowrap"
121- style={{ color: vscBadgeForeground }}
122- >
123- {props.title}
124- </span>
125- </div>
126- </div>
127- </HoverItem>
128- <ToolTip delayShow={700} id={id}>
129- {props.tooltip}
130- </ToolTip>
131- </>
132- );
133-}
134-
135-export function BlockSettingsTopToolbar() {
136- const {
137- isToolbarExpanded,
138- toggleToolbar,
139- selectedSection,
140- setSelectedSection,
141- } = useLump();
142-
143- const configError = useAppSelector((store) => store.config.configError);
144-
145- const handleEllipsisClick = () => {
146- if (isToolbarExpanded) {
147- setSelectedSection(null);
148- }
149- toggleToolbar();
150- };
151-
152- const visibleSections = sections.filter(
153- (section) =>
154- section.id !== "error" ||
155- (section.id === "error" && configError && configError?.length > 0),
156- );
157-
158- return (
159- <div className="flex flex-1 items-center justify-between gap-2">
160- <div className="flex flex-row">
161- <div className="xs:flex hidden items-center justify-center text-gray-400">
162- <BlockSettingsToolbarIcon
163- className="-ml-1.5"
164- icon={isToolbarExpanded ? ChevronLeftIcon : EllipsisHorizontalIcon}
165- tooltip={isToolbarExpanded ? "Collapse Toolbar" : "Expand Toolbar"}
166- title=""
167- isSelected={false}
168- onClick={handleEllipsisClick}
169- />
170- <div
171- className={`${isToolbarExpanded ? "w-min" : "w-0"} flex overflow-hidden transition-all duration-200`}
172- >
173- <div className="flex">
174- {visibleSections.map((section) => (
175- <BlockSettingsToolbarIcon
176- key={section.id}
177- sectionId={section.id}
178- icon={section.icon}
179- tooltip={section.tooltip}
180- title={section.title}
181- isSelected={selectedSection === section.id}
182- onClick={() =>
183- setSelectedSection(
184- selectedSection === section.id ? null : section.id,
185- )
186- }
187- />
188- ))}
189- </div>
190- </div>
191- </div>
192- </div>
193- <div className="flex gap-0.5">
194- <HoverItem
195- data-tooltip-id="assistant-select-tooltip"
196- className="!m-0 !p-0"
197- >
198- <AssistantSelect />
199- <ToolTip id="assistant-select-tooltip" place="top">
200- Select Assistant
201- </ToolTip>
202- </HoverItem>
203- </div>
204- </div>
205- );
206-}
deleted gui/src/components/mainInput/Lump/LumpToolbar.tsx +0 −139
@@ -1,139 +0,0 @@
1-import { useContext, useEffect } from "react";
2-import { useSelector } from "react-redux";
3-import styled from "styled-components";
4-import { AnimatedEllipsis } from "../..";
5-import { IdeMessengerContext } from "../../../context/IdeMessenger";
6-import { useAppDispatch, useAppSelector } from "../../../redux/hooks";
7-import { selectCurrentToolCall } from "../../../redux/selectors/selectCurrentToolCall";
8-import { callCurrentTool } from "../../../redux/thunks/callCurrentTool";
9-import { cancelCurrentToolCall } from "../../../redux/thunks/cancelCurrentToolCall";
10-import { cancelStream } from "../../../redux/thunks/cancelStream";
11-import {
12- getAltKeyLabel,
13- getFontSize,
14- getMetaKeyLabel,
15- isJetBrains,
16-} from "../../../util";
17-import { EnterButton } from "../InputToolbar/EnterButton";
18-import { BlockSettingsTopToolbar } from "./BlockSettingsTopToolbar";
19-
20-const Container = styled.div`
21- display: flex;
22- justify-content: space-between;
23- align-items: center;
24- width: 100%;
25-`;
26-
27-const StopButton = styled.div`
28- font-size: ${getFontSize() - 3}px;
29- padding: 2px;
30- padding-right: 4px;
31- cursor: pointer;
32-`;
33-
34-function GeneratingIndicator() {
35- return (
36- <div className="text-xs text-gray-400">
37- <span>Generating</span>
38- <AnimatedEllipsis />
39- </div>
40- );
41-}
42-
43-export function LumpToolbar() {
44- const dispatch = useAppDispatch();
45- const ideMessenger = useContext(IdeMessengerContext);
46- const ttsActive = useAppSelector((state) => state.ui.ttsActive);
47- const isStreaming = useAppSelector((state) => state.session.isStreaming);
48- const jetbrains = isJetBrains();
49-
50- const toolCallState = useSelector(selectCurrentToolCall);
51-
52- const handleKeyDown = (event: KeyboardEvent) => {
53- if (toolCallState?.status === "generated") {
54- const metaKey = event.metaKey || event.ctrlKey;
55- const altKey = event.altKey;
56-
57- if (metaKey && event.key === "Enter") {
58- event.preventDefault();
59- event.stopPropagation();
60- dispatch(callCurrentTool());
61- } else if ((jetbrains ? altKey : metaKey) && event.key === "Backspace") {
62- event.preventDefault();
63- event.stopPropagation();
64- dispatch(cancelCurrentToolCall());
65- }
66- }
67- };
68-
69- useEffect(() => {
70- document.addEventListener("keydown", handleKeyDown);
71- return () => {
72- document.removeEventListener("keydown", handleKeyDown);
73- };
74- }, [toolCallState]);
75-
76- if (ttsActive) {
77- return (
78- <Container>
79- <GeneratingIndicator />
80- <StopButton
81- className="text-gray-400"
82- onClick={() => {
83- ideMessenger.post("tts/kill", undefined);
84- }}
85- >
86- ■ Stop TTS
87- </StopButton>
88- </Container>
89- );
90- }
91-
92- if (isStreaming) {
93- return (
94- <Container>
95- <GeneratingIndicator />
96- <StopButton
97- className="text-gray-400"
98- onClick={() => {
99- dispatch(cancelStream());
100- }}
101- >
102- {/* JetBrains overrides cmd+backspace, so we have to use another shortcut */}
103- {jetbrains ? getAltKeyLabel() : getMetaKeyLabel()} ⌫ Cancel
104- </StopButton>
105- </Container>
106- );
107- }
108-
109- if (toolCallState?.status === "generated") {
110- return (
111- <Container>
112- <div className="flex flex-row items-center pb-0.5 pr-1 text-xs text-gray-400">
113- <span className="hidden sm:flex">Pending tool call</span>
114- </div>
115-
116- <div className="flex gap-2 pb-0.5">
117- <StopButton
118- className="text-gray-400"
119- onClick={() => dispatch(cancelCurrentToolCall())}
120- data-testid="reject-tool-call-button"
121- >
122- {/* JetBrains overrides cmd+backspace, so we have to use another shortcut */}
123- {jetbrains ? getAltKeyLabel() : getMetaKeyLabel()} ⌫ Cancel
124- </StopButton>
125- <EnterButton
126- isPrimary={true}
127- className="text-gray-400"
128- onClick={() => dispatch(callCurrentTool())}
129- data-testid="accept-tool-call-button"
130- >
131- {getMetaKeyLabel()} ⏎ Continue
132- </EnterButton>
133- </div>
134- </Container>
135- );
136- }
137-
138- return <BlockSettingsTopToolbar />;
139-}
added gui/src/components/mainInput/Lump/LumpToolbar/BlockSettingsTopToolbar.tsx +206 −0
@@ -0,0 +1,206 @@
1+import {
2+ BookOpenIcon,
3+ ChatBubbleLeftIcon,
4+ ChevronLeftIcon,
5+ CubeIcon,
6+ EllipsisHorizontalIcon,
7+ ExclamationTriangleIcon,
8+ PencilIcon,
9+ Squares2X2Icon,
10+ WrenchScrewdriverIcon,
11+} from "@heroicons/react/24/outline";
12+import { ReactNode } from "react";
13+import { vscBadgeForeground } from "../../..";
14+import { useAppSelector } from "../../../../redux/hooks";
15+import { ToolTip } from "../../../gui/Tooltip";
16+import AssistantSelect from "../../../modelSelection/platform/AssistantSelect";
17+import { useFontSize } from "../../../ui/font";
18+import HoverItem from "../../InputToolbar/HoverItem";
19+import { useLump } from "../LumpContext";
20+import { ErrorsSectionTooltip } from "../sections/errors/ErrorsSectionTooltip";
21+import { McpSectionTooltip } from "../sections/mcp/MCPTooltip";
22+import { ToolsSectionTooltip } from "../sections/tool-policies/ToolPoliciesSectionTooltip";
23+
24+interface BlockSettingsToolbarIcon {
25+ title: string;
26+ tooltip: ReactNode;
27+ icon: React.ComponentType<any>;
28+ itemCount?: number;
29+ onClick: () => void;
30+ isSelected?: boolean;
31+ className?: string;
32+}
33+
34+interface Section {
35+ id: string;
36+ title: string;
37+ tooltip: ReactNode;
38+ icon: React.ComponentType<any>;
39+}
40+
41+const sections: Section[] = [
42+ { id: "models", title: "Models", tooltip: "Models", icon: CubeIcon },
43+ { id: "rules", title: "Rules", tooltip: "Rules", icon: PencilIcon },
44+ { id: "docs", title: "Docs", tooltip: "Docs", icon: BookOpenIcon },
45+ {
46+ id: "prompts",
47+ title: "Prompts",
48+ tooltip: "Prompts",
49+ icon: ChatBubbleLeftIcon,
50+ },
51+ {
52+ id: "tools",
53+ title: "Tools",
54+ tooltip: <ToolsSectionTooltip />,
55+ icon: WrenchScrewdriverIcon,
56+ },
57+ {
58+ id: "mcp",
59+ title: "MCP",
60+ tooltip: <McpSectionTooltip />,
61+ icon: Squares2X2Icon,
62+ },
63+ {
64+ id: "error",
65+ title: "Errors",
66+ tooltip: <ErrorsSectionTooltip />,
67+ icon: ExclamationTriangleIcon,
68+ },
69+];
70+
71+function BlockSettingsToolbarIcon(
72+ props: BlockSettingsToolbarIcon & { sectionId?: string },
73+) {
74+ const isErrorSection = props.sectionId === "error";
75+
76+ const id = `block-settings-toolbar-icon-${props.sectionId}`;
77+
78+ const fontSize = useFontSize(-3);
79+ return (
80+ <>
81+ <HoverItem
82+ px={0}
83+ onClick={props.onClick}
84+ data-testid={id}
85+ data-tooltip-id={id}
86+ >
87+ <div
88+ role="button"
89+ tabIndex={0}
90+ onKeyDown={(e) => {
91+ if (e.key === "Enter" || e.key === " ") {
92+ e.preventDefault();
93+ props.onClick();
94+ }
95+ }}
96+ className={`${
97+ props.isSelected
98+ ? isErrorSection
99+ ? "bg-error"
100+ : "bg-badge"
101+ : undefined
102+ } relative flex select-none items-center rounded-full px-[3px] transition-all duration-200 focus:outline-none focus-visible:ring-2 focus-visible:ring-blue-500/50 sm:px-1 ${props.className || ""}`}
103+ >
104+ <props.icon
105+ className={`h-[13px] w-[13px] flex-shrink-0 hover:brightness-125 ${
106+ isErrorSection ? "text-error" : ""
107+ }`}
108+ style={{
109+ color: props.isSelected ? vscBadgeForeground : undefined,
110+ }}
111+ aria-hidden="true"
112+ />
113+ <div
114+ style={{ fontSize }}
115+ className={`overflow-hidden transition-all duration-200 ${
116+ props.isSelected ? "ml-1 w-auto opacity-100" : "w-0 opacity-0"
117+ }`}
118+ >
119+ <span
120+ className="whitespace-nowrap"
121+ style={{ color: vscBadgeForeground }}
122+ >
123+ {props.title}
124+ </span>
125+ </div>
126+ </div>
127+ </HoverItem>
128+ <ToolTip delayShow={700} id={id}>
129+ {props.tooltip}
130+ </ToolTip>
131+ </>
132+ );
133+}
134+
135+export function BlockSettingsTopToolbar() {
136+ const {
137+ isToolbarExpanded,
138+ toggleToolbar,
139+ selectedSection,
140+ setSelectedSection,
141+ } = useLump();
142+
143+ const configError = useAppSelector((store) => store.config.configError);
144+
145+ const handleEllipsisClick = () => {
146+ if (isToolbarExpanded) {
147+ setSelectedSection(null);
148+ }
149+ toggleToolbar();
150+ };
151+
152+ const visibleSections = sections.filter(
153+ (section) =>
154+ section.id !== "error" ||
155+ (section.id === "error" && configError && configError?.length > 0),
156+ );
157+
158+ return (
159+ <div className="flex flex-1 items-center justify-between gap-2">
160+ <div className="flex flex-row">
161+ <div className="xs:flex text-description hidden items-center justify-center">
162+ <BlockSettingsToolbarIcon
163+ className="-ml-1.5"
164+ icon={isToolbarExpanded ? ChevronLeftIcon : EllipsisHorizontalIcon}
165+ tooltip={isToolbarExpanded ? "Collapse Toolbar" : "Expand Toolbar"}
166+ title=""
167+ isSelected={false}
168+ onClick={handleEllipsisClick}
169+ />
170+ <div
171+ className={`${isToolbarExpanded ? "w-min" : "w-0"} flex overflow-hidden transition-all duration-200`}
172+ >
173+ <div className="flex">
174+ {visibleSections.map((section) => (
175+ <BlockSettingsToolbarIcon
176+ key={section.id}
177+ sectionId={section.id}
178+ icon={section.icon}
179+ tooltip={section.tooltip}
180+ title={section.title}
181+ isSelected={selectedSection === section.id}
182+ onClick={() =>
183+ setSelectedSection(
184+ selectedSection === section.id ? null : section.id,
185+ )
186+ }
187+ />
188+ ))}
189+ </div>
190+ </div>
191+ </div>
192+ </div>
193+ <div className="flex gap-0.5">
194+ <HoverItem
195+ data-tooltip-id="assistant-select-tooltip"
196+ className="!m-0 !p-0"
197+ >
198+ <AssistantSelect />
199+ <ToolTip id="assistant-select-tooltip" place="top">
200+ Select Assistant
201+ </ToolTip>
202+ </HoverItem>
203+ </div>
204+ </div>
205+ );
206+}
added gui/src/components/mainInput/Lump/LumpToolbar/EditOutcomeToolbar.tsx +34 −0
@@ -0,0 +1,34 @@
1+import { useContext } from "react";
2+import { IdeMessengerContext } from "../../../../context/IdeMessenger";
3+import { useAppDispatch, useAppSelector } from "../../../../redux/hooks";
4+import { exitEdit } from "../../../../redux/thunks/edit";
5+import AcceptRejectDiffButtons from "../../../AcceptRejectDiffButtons";
6+import { useMainEditor } from "../../TipTapEditor";
7+
8+export function EditOutcomeToolbar() {
9+ const dispatch = useAppDispatch();
10+ const editApplyState = useAppSelector(
11+ (store) => store.editModeState.applyState,
12+ );
13+ const { mainEditor } = useMainEditor();
14+ const ideMessenger = useContext(IdeMessengerContext);
15+
16+ return (
17+ <div className="text-description-muted flex items-center justify-between py-0.5 text-xs">
18+ <div className="bg-badge rounded px-1.5">
19+ <span>{`${editApplyState.numDiffs} diff${editApplyState.numDiffs !== 1 ? "s" : ""}`}</span>
20+ </div>
21+ <AcceptRejectDiffButtons
22+ applyStates={[editApplyState]}
23+ onAcceptOrReject={async (outcome) => {
24+ if (outcome === "acceptDiff") {
25+ await dispatch(exitEdit({}));
26+ ideMessenger.post("focusEditor", undefined);
27+ } else {
28+ mainEditor?.commands.focus();
29+ }
30+ }}
31+ />
32+ </div>
33+ );
34+}
added gui/src/components/mainInput/Lump/LumpToolbar/EditToolbar.tsx +38 −0
@@ -0,0 +1,38 @@
1+import { ArrowLeftIcon } from "@heroicons/react/24/outline";
2+import { useContext } from "react";
3+import { IdeMessengerContext } from "../../../../context/IdeMessenger";
4+import { useAppDispatch, useAppSelector } from "../../../../redux/hooks";
5+import { exitEdit } from "../../../../redux/thunks";
6+import { getEditFilenameAndRangeText } from "../../util";
7+
8+export function EditToolbar() {
9+ const dispatch = useAppDispatch();
10+ const ideMessenger = useContext(IdeMessengerContext);
11+ const mode = useAppSelector((state) => state.session.mode);
12+ const codeToEdit = useAppSelector(
13+ (state) => state.editModeState.codeToEdit[0],
14+ );
15+
16+ const handleBackClick = async () => {
17+ void dispatch(exitEdit({}));
18+ ideMessenger.post("focusEditor", undefined);
19+ };
20+
21+ return (
22+ <div className="text-description-muted flex items-center justify-between gap-3 text-xs">
23+ <span
24+ className="flex cursor-pointer items-center whitespace-nowrap hover:brightness-125"
25+ onClick={handleBackClick}
26+ >
27+ <ArrowLeftIcon className="mr-1 h-2.5 w-2.5" />
28+ Back to {mode.charAt(0).toUpperCase() + mode.slice(1)}
29+ </span>
30+ <span className="truncate">
31+ Editing{" "}
32+ <span className="italic">
33+ {getEditFilenameAndRangeText(codeToEdit)}
34+ </span>
35+ </span>
36+ </div>
37+ );
38+}
added gui/src/components/mainInput/Lump/LumpToolbar/GeneratingIndicator.tsx +14 −0
@@ -0,0 +1,14 @@
1+import { AnimatedEllipsis } from "../../..";
2+
3+export function GeneratingIndicator({
4+ text = "Generating",
5+}: {
6+ text?: string;
7+}) {
8+ return (
9+ <div className="text-description-muted text-xs">
10+ <span>{text}</span>
11+ <AnimatedEllipsis />
12+ </div>
13+ );
14+}
added gui/src/components/mainInput/Lump/LumpToolbar/IsApplyingToolbar.tsx +29 −0
@@ -0,0 +1,29 @@
1+import { useContext } from "react";
2+import { IdeMessengerContext } from "../../../../context/IdeMessenger";
3+import { getAltKeyLabel, getMetaKeyLabel } from "../../../../util";
4+import { Container, StopButton } from "./components";
5+import { GeneratingIndicator } from "./GeneratingIndicator";
6+
7+export const IsApplyingToolbar = () => {
8+ const ideMessenger = useContext(IdeMessengerContext);
9+
10+ const jetbrains = window.location.protocol === "jb-api:";
11+
12+ return (
13+ <Container>
14+ <GeneratingIndicator text="Applying" />
15+ <StopButton
16+ className="text-description"
17+ onClick={() => {
18+ // Note that this will NOT stop generation but once apply is cancelled will show the Generating/cancel option
19+ // Apply is prioritized because it can be more catastrophic
20+ // Intentional to be more WYSIWYG for now
21+ ideMessenger.post("cancelApply", undefined);
22+ }}
23+ >
24+ {/* JetBrains overrides cmd+backspace, so we have to use another shortcut */}
25+ {jetbrains ? getAltKeyLabel() : getMetaKeyLabel()} ⌫ Cancel
26+ </StopButton>
27+ </Container>
28+ );
29+};
added gui/src/components/mainInput/Lump/LumpToolbar/LumpToolbar.tsx +96 −0
@@ -0,0 +1,96 @@
1+import { useEffect } from "react";
2+import { useSelector } from "react-redux";
3+import { useAppDispatch, useAppSelector } from "../../../../redux/hooks";
4+import { selectCurrentToolCall } from "../../../../redux/selectors/selectCurrentToolCall";
5+import {
6+ callCurrentTool,
7+ cancelCurrentToolCall,
8+} from "../../../../redux/thunks";
9+import { isJetBrains } from "../../../../util";
10+import { BlockSettingsTopToolbar } from "./BlockSettingsTopToolbar";
11+import { EditOutcomeToolbar } from "./EditOutcomeToolbar";
12+import { EditToolbar } from "./EditToolbar";
13+import { IsApplyingToolbar } from "./IsApplyingToolbar";
14+import { PendingApplyStatesToolbar } from "./PendingApplyStatesToolbar";
15+import { PendingToolCallToolbar } from "./PendingToolCallToolbar";
16+import { StreamingToolbar } from "./StreamingToolbar";
17+import { TtsActiveToolbar } from "./TtsActiveToolbar";
18+
19+export function LumpToolbar() {
20+ const dispatch = useAppDispatch();
21+ const ttsActive = useAppSelector((state) => state.ui.ttsActive);
22+ const isStreaming = useAppSelector((state) => state.session.isStreaming);
23+ const isInEdit = useAppSelector((state) => state.session.isInEdit);
24+ const jetbrains = isJetBrains();
25+ const toolCallState = useSelector(selectCurrentToolCall);
26+ const editApplyState = useAppSelector(
27+ (state) => state.editModeState.applyState,
28+ );
29+ const applyStates = useAppSelector(
30+ (state) => state.session.codeBlockApplyStates.states,
31+ );
32+
33+ const pendingApplyStates = applyStates.filter(
34+ (state) => state.status === "done",
35+ );
36+
37+ const isApplying = applyStates.some((state) => state.status === "streaming");
38+
39+ useEffect(() => {
40+ if (toolCallState?.status !== "generated") {
41+ return;
42+ }
43+
44+ const handleKeyDown = (event: KeyboardEvent) => {
45+ const metaKey = event.metaKey || event.ctrlKey;
46+ const altKey = event.altKey;
47+
48+ if (metaKey && event.key === "Enter") {
49+ event.preventDefault();
50+ event.stopPropagation();
51+ void dispatch(callCurrentTool());
52+ } else if ((jetbrains ? altKey : metaKey) && event.key === "Backspace") {
53+ event.preventDefault();
54+ event.stopPropagation();
55+ void dispatch(cancelCurrentToolCall());
56+ }
57+ };
58+
59+ document.addEventListener("keydown", handleKeyDown);
60+ return () => {
61+ document.removeEventListener("keydown", handleKeyDown);
62+ };
63+ }, [toolCallState]);
64+
65+ if (isApplying) {
66+ return <IsApplyingToolbar />;
67+ }
68+
69+ if (isInEdit) {
70+ if (editApplyState.status === "done") {
71+ return <EditOutcomeToolbar />;
72+ }
73+
74+ return <EditToolbar />;
75+ }
76+
77+ if (ttsActive) {
78+ return <TtsActiveToolbar />;
79+ }
80+
81+ if (isStreaming) {
82+ return <StreamingToolbar />;
83+ }
84+
85+ if (toolCallState?.status === "generated") {
86+ return <PendingToolCallToolbar />;
87+ }
88+
89+ if (pendingApplyStates.length > 0) {
90+ return (
91+ <PendingApplyStatesToolbar pendingApplyStates={pendingApplyStates} />
92+ );
93+ }
94+
95+ return <BlockSettingsTopToolbar />;
96+}
added gui/src/components/mainInput/Lump/LumpToolbar/PendingApplyStatesToolbar.tsx +44 −0
@@ -0,0 +1,44 @@
1+import { ApplyState } from "core";
2+import { getUriPathBasename } from "core/util/uri";
3+import AcceptRejectDiffButtons from "../../../AcceptRejectDiffButtons";
4+import FileIcon from "../../../FileIcon";
5+
6+interface PendingApplyStatesToolbarProps {
7+ pendingApplyStates: ApplyState[];
8+}
9+
10+export function PendingApplyStatesToolbar({
11+ pendingApplyStates,
12+}: PendingApplyStatesToolbarProps) {
13+ // Group apply states by filepath
14+ const applyStatesByFilepath = pendingApplyStates.reduce(
15+ (acc, state) => {
16+ const filepath = state.filepath || ""; // Use empty string as fallback
17+ if (!acc[filepath]) {
18+ acc[filepath] = [];
19+ }
20+ acc[filepath].push(state);
21+ return acc;
22+ },
23+ {} as Record<string, ApplyState[]>,
24+ );
25+
26+ return (
27+ <div className="flex flex-col gap-2">
28+ {Object.entries(applyStatesByFilepath).map(([filepath, states]) => (
29+ <div key={filepath} className="flex justify-between gap-3">
30+ {filepath && (
31+ <span className="bg-badge flex items-center gap-1 rounded px-0.5">
32+ <FileIcon filename={filepath} height="18px" width="18px" />
33+ {getUriPathBasename(filepath)}
34+ </span>
35+ )}
36+ <AcceptRejectDiffButtons
37+ applyStates={states}
38+ onAcceptOrReject={async () => {}}
39+ />
40+ </div>
41+ ))}
42+ </div>
43+ );
44+}
added gui/src/components/mainInput/Lump/LumpToolbar/PendingToolCallToolbar.tsx +59 −0
@@ -0,0 +1,59 @@
1+import styled from "styled-components";
2+import { useAppDispatch } from "../../../../redux/hooks";
3+import {
4+ callCurrentTool,
5+ cancelCurrentToolCall,
6+} from "../../../../redux/thunks";
7+import {
8+ getAltKeyLabel,
9+ getFontSize,
10+ getMetaKeyLabel,
11+ isJetBrains,
12+} from "../../../../util";
13+import { EnterButton } from "../../InputToolbar/EnterButton";
14+
15+const Container = styled.div`
16+ display: flex;
17+ justify-content: space-between;
18+ align-items: center;
19+ width: 100%;
20+`;
21+
22+const StopButton = styled.div`
23+ font-size: ${getFontSize() - 3}px;
24+ padding: 2px;
25+ padding-right: 4px;
26+ cursor: pointer;
27+`;
28+
29+export function PendingToolCallToolbar() {
30+ const dispatch = useAppDispatch();
31+ const jetbrains = isJetBrains();
32+
33+ return (
34+ <Container>
35+ <div className="text-description flex flex-row items-center pb-0.5 pr-1 text-xs">
36+ <span className="hidden sm:flex">Pending tool call</span>
37+ </div>
38+
39+ <div className="flex gap-2 pb-0.5">
40+ <StopButton
41+ className="text-description"
42+ onClick={() => dispatch(cancelCurrentToolCall())}
43+ data-testid="reject-tool-call-button"
44+ >
45+ {/* JetBrains overrides cmd+backspace, so we have to use another shortcut */}
46+ {jetbrains ? getAltKeyLabel() : getMetaKeyLabel()} ⌫ Cancel
47+ </StopButton>
48+ <EnterButton
49+ isPrimary={true}
50+ className="text-description"
51+ onClick={() => dispatch(callCurrentTool())}
52+ data-testid="accept-tool-call-button"
53+ >
54+ {getMetaKeyLabel()} ⏎ Continue
55+ </EnterButton>
56+ </div>
57+ </Container>
58+ );
59+}
added gui/src/components/mainInput/Lump/LumpToolbar/StreamingToolbar.tsx +24 −0
@@ -0,0 +1,24 @@
1+import { useAppDispatch } from "../../../../redux/hooks";
2+import { cancelStream } from "../../../../redux/thunks";
3+import { getAltKeyLabel, getMetaKeyLabel, isJetBrains } from "../../../../util";
4+import { Container, StopButton } from "./components";
5+import { GeneratingIndicator } from "./GeneratingIndicator";
6+
7+export function StreamingToolbar() {
8+ const dispatch = useAppDispatch();
9+ const jetbrains = isJetBrains();
10+
11+ return (
12+ <Container>
13+ <GeneratingIndicator />
14+ <StopButton
15+ className="text-description"
16+ onClick={() => {
17+ void dispatch(cancelStream());
18+ }}
19+ >
20+ {jetbrains ? getAltKeyLabel() : getMetaKeyLabel()} ⌫ Cancel
21+ </StopButton>
22+ </Container>
23+ );
24+}
added gui/src/components/mainInput/Lump/LumpToolbar/TtsActiveToolbar.tsx +37 −0
@@ -0,0 +1,37 @@
1+import { useContext } from "react";
2+import styled from "styled-components";
3+import { IdeMessengerContext } from "../../../../context/IdeMessenger";
4+import { getFontSize } from "../../../../util";
5+import { GeneratingIndicator } from "./GeneratingIndicator";
6+
7+const Container = styled.div`
8+ display: flex;
9+ justify-content: space-between;
10+ align-items: center;
11+ width: 100%;
12+`;
13+
14+const StopButton = styled.div`
15+ font-size: ${getFontSize() - 3}px;
16+ padding: 2px;
17+ padding-right: 4px;
18+ cursor: pointer;
19+`;
20+
21+export function TtsActiveToolbar() {
22+ const ideMessenger = useContext(IdeMessengerContext);
23+
24+ return (
25+ <Container>
26+ <GeneratingIndicator />
27+ <StopButton
28+ className="text-description"
29+ onClick={() => {
30+ ideMessenger.post("tts/kill", undefined);
31+ }}
32+ >
33+ ■ Stop TTS
34+ </StopButton>
35+ </Container>
36+ );
37+}
added gui/src/components/mainInput/Lump/LumpToolbar/components.ts +18 −0
@@ -0,0 +1,18 @@
1+// TODO: Convert these to tailwind
2+
3+import styled from "styled-components";
4+import { getFontSize } from "../../../../util";
5+
6+export const Container = styled.div`
7+ display: flex;
8+ justify-content: space-between;
9+ align-items: center;
10+ width: 100%;
11+`;
12+
13+export const StopButton = styled.div`
14+ font-size: ${getFontSize() - 3}px;
15+ padding: 2px;
16+ padding-right: 4px;
17+ cursor: pointer;
18+`;
added gui/src/components/mainInput/Lump/LumpToolbar/index.ts +1 −0
@@ -0,0 +1,1 @@
1+export * from "./LumpToolbar";
modified gui/src/components/mainInput/Lump/index.tsx +1 −1
@@ -37,7 +37,7 @@
3737
3838 return (
3939 <LumpDiv>
40- <div className="xs:px-2 mt-0.5 px-1">
40+ <div className="xs:px-2 px-1 py-0.5">
4141 <LumpToolbar />
4242
4343 <ContentDiv
modified gui/src/components/mainInput/TipTapEditor/MainEditorProvider.tsx +15 −12
@@ -27,9 +27,15 @@
2727 onEnterRef: React.MutableRefObject<(modifiers: InputModifiers) => void>;
2828 }
2929
30-const MainEditorContext = createContext<MainEditorContextType | undefined>(
31- undefined,
32-);
30+const initialState: MainEditorContextType = {
31+ mainEditor: null,
32+ setMainEditor: () => {},
33+ inputId: null,
34+ setInputId: () => {},
35+ onEnterRef: { current: () => {} },
36+};
37+
38+const MainEditorContext = createContext<MainEditorContextType>(initialState);
3339
3440 /**
3541 * Provider component that maintains a reference to the main editor
@@ -38,8 +44,10 @@
3844 children,
3945 }) => {
4046 const dispatch = useAppDispatch();
41- const [mainEditor, setMainEditorInternal] = useState<Editor | null>(null);
42- const [inputId, setInputId] = useState<string | null>(null);
47+ const [mainEditor, setMainEditorInternal] = useState<Editor | null>(
48+ initialState.mainEditor,
49+ );
50+ const [inputId, setInputId] = useState<string | null>(initialState.inputId);
4351 const onEnterRef = useRef<(modifiers: InputModifiers) => void>(() => {});
4452 const editorFocusedRef = useRef<boolean>(false);
4553 const historyLength = useAppSelector((store) => store.session.history.length);
@@ -108,10 +116,5 @@
108116 /**
109117 * Hook to access the main editor context
110118 */
111-export const useMainEditor = (): MainEditorContextType => {
112- const context = useContext(MainEditorContext);
113- if (context === undefined) {
114- throw new Error("useMainEditor must be used within a MainEditorProvider");
115- }
116- return context;
117-};
119+export const useMainEditor = (): MainEditorContextType =>
120+ useContext(MainEditorContext);
modified gui/src/components/mainInput/TipTapEditor/TipTapEditor.tsx +7 −8
@@ -42,14 +42,13 @@
4242 const mainEditorContext = useMainEditor();
4343
4444 const ideMessenger = useContext(IdeMessengerContext);
45-
4645 const isOSREnabled = useIsOSREnabled();
4746
4847 const defaultModel = useAppSelector(selectSelectedChatModel);
4948 const isStreaming = useAppSelector((state) => state.session.isStreaming);
5049 const historyLength = useAppSelector((store) => store.session.history.length);
50+ const isInEdit = useAppSelector((store) => store.session.isInEdit);
5151
52- const mode = useAppSelector((store) => store.session.mode);
5352 const { editor, onEnterRef } = createEditorConfig({
5453 props,
5554 ideMessenger,
@@ -87,10 +86,10 @@
8786 }, [editor, props.isMainInput]);
8887
8988 useEffect(() => {
90- if (mode === "edit") {
89+ if (isInEdit) {
9190 setShouldHideToolbar(false);
9291 }
93- }, [mode]);
92+ }, [isInEdit]);
9493
9594 const editorFocusedRef = useUpdatingRef(editor?.isFocused, [editor]);
9695
@@ -150,7 +149,7 @@
150149
151150 const handleBlur = useCallback(
152151 (e: React.FocusEvent) => {
153- if (mode === "edit") {
152+ if (isInEdit) {
154153 return;
155154 }
156155 // Check if the new focus target is within our InputBoxDiv
@@ -165,7 +164,7 @@
165164 setShouldHideToolbar(true);
166165 }, 100);
167166 },
168- [mode, blurTimeout],
167+ [isInEdit, blurTimeout],
169168 );
170169
171170 const handleFocus = useCallback(() => {
@@ -213,7 +212,7 @@
213212 }
214213 setShowDragOverMsg(false);
215214 let file = event.dataTransfer.files[0];
216- handleImageFile(ideMessenger, file).then((result) => {
215+ void handleImageFile(ideMessenger, file).then((result) => {
217216 if (!editor) {
218217 return;
219218 }
@@ -245,7 +244,7 @@
245244 onAddContextItem={() => insertCharacterWithWhitespace("@")}
246245 onEnter={onEnterRef.current}
247246 onImageFileSelected={(file) => {
248- handleImageFile(ideMessenger, file).then((result) => {
247+ void handleImageFile(ideMessenger, file).then((result) => {
249248 if (!editor) {
250249 return;
251250 }
modified gui/src/components/mainInput/TipTapEditor/components/ExpandableToolbarPreview.tsx +1 −1
@@ -159,7 +159,7 @@
159159 contentEditable={false}
160160 >
161161 <div
162- className="border-b-vsc-commandCenter-inactiveBorder m-0 flex cursor-pointer items-center justify-between break-all border-0 border-b-[1px] border-solid px-[5px] py-1.5 hover:opacity-90"
162+ className="border-b-command-border m-0 flex cursor-pointer items-center justify-between break-all border-0 border-b-[1px] border-solid px-[5px] py-1.5 hover:opacity-90"
163163 style={{
164164 fontSize: getFontSize() - 3,
165165 }}
modified gui/src/components/mainInput/TipTapEditor/useMainEditorWebviewListeners.ts +1 −1
@@ -3,7 +3,7 @@
33 import { rifWithContentsToContextItem } from "core/commands/util";
44 import { MutableRefObject } from "react";
55 import { useWebviewListener } from "../../../hooks/useWebviewListener";
6-import { clearCodeToEdit } from "../../../redux/slices/editModeState";
6+import { clearCodeToEdit } from "../../../redux/slices/editState";
77 import { setNewestToolbarPreviewForInput } from "../../../redux/slices/sessionSlice";
88 import { AppDispatch } from "../../../redux/store";
99 import { loadSession, saveCurrentSession } from "../../../redux/thunks/session";
modified gui/src/components/mainInput/TipTapEditor/utils/editorConfig.ts +9 −9
@@ -23,7 +23,7 @@
2323 import { selectUseActiveFile } from "../../../../redux/selectors";
2424 import { selectSelectedChatModel } from "../../../../redux/slices/configSlice";
2525 import { AppDispatch } from "../../../../redux/store";
26-import { exitEditMode } from "../../../../redux/thunks/editMode";
26+import { exitEdit } from "../../../../redux/thunks/edit";
2727 import { getFontSize, isJetBrains } from "../../../../util";
2828 import * as ContinueExtensions from "../extensions";
2929 import { TipTapEditorProps } from "../TipTapEditor";
@@ -81,9 +81,9 @@
8181 const isStreaming = useAppSelector((state) => state.session.isStreaming);
8282 const useActiveFile = useAppSelector(selectUseActiveFile);
8383 const historyLength = useAppSelector((store) => store.session.history.length);
84- const mode = useAppSelector((store) => store.session.mode);
85- const modeRef = useUpdatingRef(mode);
8684 const codeToEdit = useAppSelector((store) => store.editModeState.codeToEdit);
85+ const isInEdit = useAppSelector((store) => store.session.isInEdit);
86+ const isInEditRef = useUpdatingRef(isInEdit);
8787
8888 const inSubmenuRef = useRef<string | undefined>(undefined);
8989 const inDropdownRef = useRef(false);
@@ -157,7 +157,7 @@
157157 for (const item of items) {
158158 const file = item.getAsFile();
159159 file &&
160- modelSupportsImages(
160+ void modelSupportsImages(
161161 model.provider,
162162 model.model,
163163 model.title,
@@ -269,9 +269,9 @@
269269 return true;
270270 }
271271
272- if (modeRef.current === "edit") {
273- dispatch(
274- exitEditMode({
272+ if (isInEditRef.current) {
273+ void dispatch(
274+ exitEdit({
275275 openNewSession: false,
276276 }),
277277 );
@@ -345,7 +345,7 @@
345345 if (!editor) {
346346 return;
347347 }
348- if (isStreaming || (codeToEdit.length === 0 && mode === "edit")) {
348+ if (isStreaming || (codeToEdit.length === 0 && isInEdit)) {
349349 return;
350350 }
351351
@@ -362,7 +362,7 @@
362362
363363 props.onEnter(json, modifiers, editor);
364364 },
365- [props.onEnter, editor, props.isMainInput, codeToEdit, mode],
365+ [props.onEnter, editor, props.isMainInput, codeToEdit, isInEdit],
366366 );
367367
368368 return { editor, onEnterRef };
added gui/src/components/mainInput/util/index.ts +20 −0
@@ -0,0 +1,20 @@
1+import { SetCodeToEditPayload } from "core";
2+import { getUriPathBasename } from "core/util/uri";
3+
4+export * from "./handleMetaKeyIssues";
5+
6+export function getEditFilenameAndRangeText(code: SetCodeToEditPayload) {
7+ const fileName = getUriPathBasename(code.filepath);
8+ let title = `${fileName}`;
9+
10+ if ("range" in code) {
11+ const start = code.range.start.line + 1;
12+ const end = code.range.end.line + 1;
13+ const isInsertion = start === end;
14+ title += isInsertion
15+ ? ` - Inserting at line ${start}`
16+ : ` (${start} - ${end})`;
17+ }
18+
19+ return title;
20+}
deleted gui/src/components/mainInput/util/inputModifiers.ts +0 −6
@@ -1,6 +0,0 @@
1-import { InputModifiers } from "core";
2-
3-export const defaultInputModifiers: InputModifiers = {
4- useCodebase: false,
5- noContext: true,
6-};
deleted gui/src/components/mainInput/utils.ts +0 −18
@@ -1,18 +0,0 @@
1-import { JSONContent } from "@tiptap/core";
2-
3-export function getParagraphNodeFromString(str: string): JSONContent {
4- return {
5- type: "doc",
6- content: [
7- {
8- type: "paragraph",
9- content: [
10- {
11- type: "text",
12- text: str,
13- },
14- ],
15- },
16- ],
17- };
18-}
deleted gui/src/components/modelSelection/ModeSelect.tsx +0 −201
@@ -1,201 +0,0 @@
1-// A dropdown menu for selecting between Chat, Edit, and Agent modes with keyboard shortcuts
2-import {
3- ChatBubbleLeftIcon,
4- CheckIcon,
5- ChevronDownIcon,
6- PencilIcon,
7- SparklesIcon,
8-} from "@heroicons/react/24/outline";
9-import { MessageModes } from "core";
10-import { modelSupportsTools } from "core/llm/autodetect";
11-import { useCallback, useEffect, useMemo } from "react";
12-import styled from "styled-components";
13-import { lightGray } from "..";
14-import { useAppDispatch, useAppSelector } from "../../redux/hooks";
15-import { selectSelectedChatModel } from "../../redux/slices/configSlice";
16-import { setMode } from "../../redux/slices/sessionSlice";
17-import { enterEditMode, exitEditMode } from "../../redux/thunks/editMode";
18-import { getFontSize, getMetaKeyLabel, isJetBrains } from "../../util";
19-import { useMainEditor } from "../mainInput/TipTapEditor";
20-import {
21- Listbox,
22- ListboxButton,
23- ListboxOption,
24- ListboxOptions,
25-} from "../ui/Listbox";
26-
27-const ShortcutText = styled.span`
28- color: ${lightGray};
29- font-size: ${getFontSize() - 3}px;
30- margin-right: auto;
31-`;
32-
33-function ModeSelect() {
34- const dispatch = useAppDispatch();
35- const mode = useAppSelector((store) => store.session.mode);
36- const selectedModel = useAppSelector(selectSelectedChatModel);
37- const agentModeSupported = useMemo(() => {
38- return selectedModel && modelSupportsTools(selectedModel);
39- }, [selectedModel]);
40- const { mainEditor } = useMainEditor();
41- const jetbrains = useMemo(() => {
42- return isJetBrains();
43- }, []);
44- const metaKeyLabel = useMemo(() => {
45- return getMetaKeyLabel();
46- }, []);
47-
48- const getModeIcon = (mode: MessageModes) => {
49- switch (mode) {
50- case "agent":
51- return <SparklesIcon className="xs:h-3 xs:w-3 h-3 w-3" />;
52- case "chat":
53- return <ChatBubbleLeftIcon className="xs:h-3 xs:w-3 h-3 w-3" />;
54- case "edit":
55- return <PencilIcon className="xs:h-3 xs:w-3 h-3 w-3" />;
56- }
57- };
58-
59- // Switch to chat mode if agent mode is selected but not supported
60- useEffect(() => {
61- if (!selectedModel) {
62- return;
63- }
64- if (mode === "agent" && !agentModeSupported) {
65- dispatch(setMode("chat"));
66- }
67- }, [mode, agentModeSupported, dispatch, selectedModel]);
68-
69- const cycleMode = useCallback(async () => {
70- const modes: MessageModes[] = jetbrains
71- ? ["chat", "agent"]
72- : ["chat", "agent", "edit"];
73- const currentIndex = modes.indexOf(mode);
74- const nextMode = modes[(currentIndex + 1) % modes.length];
75-
76- if (mode === "edit") {
77- await dispatch(
78- exitEditMode({
79- goToMode: nextMode,
80- }),
81- );
82- } else {
83- if (nextMode === "edit") {
84- await dispatch(
85- enterEditMode({
86- returnToMode: mode,
87- }),
88- );
89- } else {
90- dispatch(setMode(nextMode));
91- }
92- }
93- mainEditor?.commands.focus();
94- }, [jetbrains, mode, mainEditor]);
95-
96- const selectMode = useCallback(
97- async (newMode: MessageModes) => {
98- if (newMode === mode) {
99- return;
100- }
101- if (newMode === "edit") {
102- await dispatch(
103- enterEditMode({
104- returnToMode: mode,
105- }),
106- );
107- } else {
108- if (mode === "edit") {
109- await dispatch(
110- exitEditMode({
111- goToMode: newMode,
112- }),
113- );
114- } else {
115- dispatch(setMode(newMode));
116- }
117- }
118-
119- mainEditor?.commands.focus();
120- },
121- [mode, mainEditor],
122- );
123-
124- useEffect(() => {
125- const handleKeyDown = (e: KeyboardEvent) => {
126- if (e.key === "." && (e.metaKey || e.ctrlKey)) {
127- e.preventDefault();
128- void cycleMode();
129- }
130- };
131-
132- document.addEventListener("keydown", handleKeyDown);
133- return () => document.removeEventListener("keydown", handleKeyDown);
134- }, [cycleMode]);
135-
136- return (
137- <Listbox value={mode} onChange={selectMode}>
138- <div className="relative">
139- <ListboxButton
140- data-testid="mode-select-button"
141- className="xs:px-2 gap-1 border-none px-1.5 py-0.5 text-gray-400 transition-colors duration-200"
142- style={{
143- backgroundColor: `${lightGray}33`,
144- borderRadius: "9999px",
145- }}
146- >
147- {getModeIcon(mode)}
148- <span className="hidden sm:block">
149- {mode.charAt(0).toUpperCase() + mode.slice(1)}
150- </span>
151- <ChevronDownIcon
152- className="h-2 w-2 flex-shrink-0"
153- aria-hidden="true"
154- />
155- </ListboxButton>
156- <ListboxOptions className="min-w-32 max-w-48">
157- {!jetbrains && (
158- <ListboxOption value="edit">
159- <div className="flex flex-row items-center gap-1.5">
160- <PencilIcon className="h-3 w-3" />
161- <span className="">Edit</span>
162- <ShortcutText>{getMetaKeyLabel()}I</ShortcutText>
163- </div>
164- {mode === "edit" && <CheckIcon className="ml-auto h-3 w-3" />}
165- </ListboxOption>
166- )}
167- <ListboxOption value="chat">
168- <div className="flex flex-row items-center gap-1.5">
169- <ChatBubbleLeftIcon className="h-3 w-3" />
170- <span className="">Chat</span>
171- <ShortcutText>{getMetaKeyLabel()}L</ShortcutText>
172- </div>
173- {mode === "chat" && <CheckIcon className="ml-auto h-3 w-3" />}
174- </ListboxOption>
175-
176- <ListboxOption
177- value="agent"
178- disabled={!agentModeSupported}
179- className={"gap-1"}
180- >
181- <div className="flex flex-row items-center gap-1.5">
182- <SparklesIcon className="h-3 w-3" />
183- <span className="">Agent</span>
184- </div>
185- {agentModeSupported ? (
186- mode === "agent" && <CheckIcon className="ml-auto h-3 w-3" />
187- ) : (
188- <span>(Not supported)</span>
189- )}
190- </ListboxOption>
191-
192- <div className="text-lightgray px-2 py-1">
193- {`${metaKeyLabel} . for next mode`}
194- </div>
195- </ListboxOptions>
196- </div>
197- </Listbox>
198- );
199-}
200-
201-export default ModeSelect;
modified gui/src/components/modelSelection/ModelSelect.tsx +5 −21
@@ -6,8 +6,7 @@
66 PlusIcon,
77 } from "@heroicons/react/24/outline";
88 import { useContext, useEffect, useRef, useState } from "react";
9-import styled from "styled-components";
10-import { defaultBorderRadius, lightGray } from "..";
9+import { lightGray } from "..";
1110 import { useAuth } from "../../context/Auth";
1211 import { IdeMessengerContext } from "../../context/IdeMessenger";
1312 import AddModelForm from "../../forms/AddModelForm";
@@ -30,21 +29,6 @@
3029 apiKey?: string;
3130 }
3231
33-const IconBase = styled.div<{ $hovered: boolean }>`
34- width: 1.2em;
35- height: 1.2em;
36- cursor: pointer;
37- padding: 4px;
38- border-radius: ${defaultBorderRadius};
39- opacity: ${(props) => (props.$hovered ? 0.75 : 0)};
40- visibility: ${(props) => (props.$hovered ? "visible" : "hidden")};
41-
42- &:hover {
43- opacity: 1;
44- background-color: ${lightGray}33;
45- }
46-`;
47-
4832 function modelSelectTitle(model: any): string {
4933 if (model?.title) return model?.title;
5034 if (model?.model !== undefined && model?.model.trim() !== "") {
@@ -120,12 +104,12 @@
120104 function ModelSelect() {
121105 const dispatch = useAppDispatch();
122106
123- const mode = useAppSelector((store) => store.session.mode);
107+ const isInEdit = useAppSelector((store) => store.session.isInEdit);
124108 const config = useAppSelector((state) => state.config.config);
125109
126110 let selectedModel = null;
127111 let allModels = null;
128- if (mode === "edit") {
112+ if (isInEdit) {
129113 allModels = config.modelsByRole.edit;
130114 selectedModel = config.selectedModelByRole.edit;
131115 }
@@ -226,7 +210,7 @@
226210 void dispatch(
227211 updateSelectedModelByRole({
228212 selectedProfile,
229- role: mode === "edit" ? "edit" : "chat",
213+ role: isInEdit ? "edit" : "chat",
230214 modelTitle: val,
231215 }),
232216 );
@@ -236,7 +220,7 @@
236220 <ListboxButton
237221 data-testid="model-select-button"
238222 ref={buttonRef}
239- className="h-[18px] gap-1 border-none text-gray-400"
223+ className="text-description h-[18px] gap-1 border-none"
240224 >
241225 <span className="line-clamp-1 break-all hover:brightness-110">
242226 {modelSelectTitle(selectedModel) || "Select model"}
modified gui/src/components/modelSelection/platform/AssistantSelect.tsx +8 −8
@@ -126,7 +126,7 @@
126126 )}
127127 {isLocalProfile(profile) ? (
128128 <Cog6ToothIcon
129- className="text-lightgray h-3 w-3 flex-shrink-0 cursor-pointer"
129+ className="text-description h-3 w-3 flex-shrink-0 cursor-pointer"
130130 onClick={(e) => {
131131 e.stopPropagation();
132132 e.preventDefault();
@@ -135,7 +135,7 @@
135135 />
136136 ) : (
137137 <ArrowTopRightOnSquareIcon
138- className="text-lightgray h-3 w-3 flex-shrink-0 cursor-pointer"
138+ className="text-description h-3 w-3 flex-shrink-0 cursor-pointer"
139139 onClick={(e) => {
140140 e.stopPropagation();
141141 e.preventDefault();
@@ -242,12 +242,12 @@
242242 return (
243243 <div
244244 onClick={() => {
245- ideMessenger.request("controlPlane/openUrl", {
245+ void ideMessenger.request("controlPlane/openUrl", {
246246 path: "/new?type=assistant",
247247 orgSlug: currentOrg?.slug,
248248 });
249249 }}
250- className="flex cursor-pointer select-none items-center gap-1 text-gray-400"
250+ className="text-description flex cursor-pointer select-none items-center gap-1"
251251 style={{ fontSize: smallFont }}
252252 >
253253 <PlusIcon className="h-3 w-3 flex-shrink-0 select-none" />
@@ -266,7 +266,7 @@
266266 <ListboxButton
267267 data-testid="assistant-select-button"
268268 ref={buttonRef}
269- className="border-none bg-transparent text-gray-400 hover:brightness-125"
269+ className="text-description border-none bg-transparent hover:brightness-125"
270270 style={{ fontSize: fontSize(-3) }}
271271 >
272272 <div className="flex flex-row items-center gap-1.5">
@@ -301,7 +301,7 @@
301301 >
302302 <ArrowPathIcon
303303 className={cn(
304- "text-lightgray h-2.5 w-2.5",
304+ "text-description h-2.5 w-2.5",
305305 loading && "animate-spin-slow",
306306 )}
307307 />
@@ -339,7 +339,7 @@
339339 onClick={session ? onNewAssistant : () => login(false)}
340340 >
341341 <div
342- className="text-lightgray flex flex-row items-center gap-2"
342+ className="text-description flex flex-row items-center gap-2"
343343 style={{
344344 fontSize: tinyFont,
345345 }}
@@ -358,7 +358,7 @@
358358 />
359359
360360 <div
361- className="text-lightgray flex items-center justify-between px-2 py-1"
361+ className="text-description flex items-center justify-between px-2 py-1"
362362 style={{
363363 fontSize: tinyFont,
364364 }}
modified gui/src/context/VscTheme.tsx +1 −1
@@ -1,6 +1,6 @@
11 import { createContext, useContext, useState } from "react";
2-import { parseHexColor } from "../components";
32 import { useWebviewListener } from "../hooks/useWebviewListener";
3+import { parseHexColor } from "../styles/utils";
44
55 const hljsToTextMate: Record<string, string[]> = {
66 ".hljs-comment": ["comment"],
modified gui/src/hooks/ParallelListeners.tsx +52 −67
@@ -1,9 +1,9 @@
11 import { useCallback, useContext, useEffect, useRef } from "react";
2-import { VSC_THEME_COLOR_VARS } from "../components";
32 import { IdeMessengerContext } from "../context/IdeMessenger";
43
54 import { EDIT_MODE_STREAM_ID } from "core/edit/constants";
65 import { FromCoreProtocol } from "core/protocol";
6+import { useMainEditor } from "../components/mainInput/TipTapEditor";
77 import {
88 initializeProfilePreferences,
99 setOrganizations,
@@ -16,7 +16,7 @@
1616 import {
1717 setLastNonEditSessionEmpty,
1818 updateEditStateApplyState,
19-} from "../redux/slices/editModeState";
19+} from "../redux/slices/editState";
2020 import { updateIndexingStatus } from "../redux/slices/indexingSlice";
2121 import {
2222 acceptToolCall,
@@ -24,11 +24,15 @@
2424 updateApplyState,
2525 } from "../redux/slices/sessionSlice";
2626 import { setTTSActive } from "../redux/slices/uiSlice";
27-import { streamResponseAfterToolCall } from "../redux/thunks";
27+import { exitEdit, streamResponseAfterToolCall } from "../redux/thunks";
2828 import { cancelStream } from "../redux/thunks/cancelStream";
2929 import { refreshSessionMetadata } from "../redux/thunks/session";
3030 import { streamResponseThunk } from "../redux/thunks/streamResponse";
3131 import { updateFileSymbolsFromHistory } from "../redux/thunks/updateFileSymbols";
32+import {
33+ setDocumentStylesFromLocalStorage,
34+ setDocumentStylesFromTheme,
35+} from "../styles/theme";
3236 import { isJetBrains } from "../util";
3337 import { setLocalStorage } from "../util/localStorage";
3438 import { useWebviewListener } from "./useWebviewListener";
@@ -37,12 +41,18 @@
3741 const dispatch = useAppDispatch();
3842 const ideMessenger = useContext(IdeMessengerContext);
3943 const history = useAppSelector((store) => store.session.history);
44+ const isInEdit = useAppSelector((store) => store.session.isInEdit);
4045
4146 const selectedProfileId = useAppSelector(
4247 (store) => store.profiles.selectedProfileId,
4348 );
4449
4550 const hasDoneInitialConfigLoad = useRef(false);
51+ const currentToolCallApplyState = useAppSelector(
52+ selectCurrentToolCallApplyState,
53+ );
54+
55+ const { mainEditor } = useMainEditor();
4656
4757 const handleConfigUpdate = useCallback(
4858 async (isInitial: boolean, result: FromCoreProtocol["configUpdate"][0]) => {
@@ -96,18 +106,18 @@
96106
97107 // Load config from the IDE
98108 useEffect(() => {
99- initialLoadAuthAndConfig(true);
109+ void initialLoadAuthAndConfig(true);
100110 const interval = setInterval(() => {
101111 if (hasDoneInitialConfigLoad.current) {
102112 // Init to run on initial config load
103113 ideMessenger.post("docs/initStatuses", undefined);
104- dispatch(updateFileSymbolsFromHistory());
105- dispatch(refreshSessionMetadata({}));
114+ void dispatch(updateFileSymbolsFromHistory());
115+ void dispatch(refreshSessionMetadata({}));
106116
107117 // This triggers sending pending status to the GUI for relevant docs indexes
108118 clearInterval(interval);
109119 } else {
110- initialLoadAuthAndConfig(true);
120+ void initialLoadAuthAndConfig(true);
111121 }
112122 }, 2_000);
113123
@@ -129,76 +139,50 @@
129139 const sessionId = useAppSelector((state) => state.session.id);
130140 useEffect(() => {
131141 if (sessionId) {
132- dispatch(updateFileSymbolsFromHistory());
142+ void dispatch(updateFileSymbolsFromHistory());
133143 }
134144 }, [sessionId]);
135145
136146 // ON LOAD
137147 useEffect(() => {
138148 // Override persisted state
139- dispatch(cancelStream());
149+ void dispatch(cancelStream());
140150
141151 const jetbrains = isJetBrains();
142- for (const colorVar of VSC_THEME_COLOR_VARS) {
143- if (jetbrains) {
144- const cached = localStorage.getItem(colorVar);
145- if (cached) {
146- document.body.style.setProperty(colorVar, cached);
147- }
148- }
149-
150- // Remove alpha channel from colors
151- const value = getComputedStyle(document.documentElement).getPropertyValue(
152- colorVar,
153- );
154- if (colorVar.startsWith("#") && value.length > 7) {
155- document.body.style.setProperty(colorVar, value.slice(0, 7));
156- }
157- }
152+ setDocumentStylesFromLocalStorage(jetbrains);
158153
159154 if (jetbrains) {
160155 // Save theme colors to local storage for immediate loading in JetBrains
161- ideMessenger.request("jetbrains/getColors", undefined).then((result) => {
162- if (result.status === "success") {
163- Object.entries(result.content).forEach(([key, value]) => {
164- document.body.style.setProperty(key, value);
165- document.documentElement.style.setProperty(key, value);
166- });
167- }
168- });
156+ void ideMessenger
157+ .request("jetbrains/getColors", undefined)
158+ .then((result) => {
159+ if (result.status === "success") {
160+ setDocumentStylesFromTheme(result.content);
161+ }
162+ });
169163
170164 // Tell JetBrains the webview is ready
171- ideMessenger.request("jetbrains/onLoad", undefined).then((result) => {
172- if (result.status === "error") {
173- return;
174- }
175-
176- const msg = result.content;
177- (window as any).windowId = msg.windowId;
178- (window as any).serverUrl = msg.serverUrl;
179- (window as any).workspacePaths = msg.workspacePaths;
180- (window as any).vscMachineId = msg.vscMachineId;
181- (window as any).vscMediaUrl = msg.vscMediaUrl;
182- });
183-
184- for (const colorVar of VSC_THEME_COLOR_VARS) {
185- if (document.body.style.getPropertyValue(colorVar)) {
186- localStorage.setItem(
187- colorVar,
188- document.body.style.getPropertyValue(colorVar),
189- );
190- }
191- }
165+ void ideMessenger
166+ .request("jetbrains/onLoad", undefined)
167+ .then((result) => {
168+ if (result.status === "error") {
169+ return;
170+ }
171+
172+ const msg = result.content;
173+ (window as any).windowId = msg.windowId;
174+ (window as any).serverUrl = msg.serverUrl;
175+ (window as any).workspacePaths = msg.workspacePaths;
176+ (window as any).vscMachineId = msg.vscMachineId;
177+ (window as any).vscMediaUrl = msg.vscMediaUrl;
178+ });
192179 }
193180 }, []);
194181
195182 useWebviewListener(
196183 "jetbrains/setColors",
197184 async (data) => {
198- Object.entries(data).forEach(([key, value]) => {
199- document.body.style.setProperty(key, value);
200- document.documentElement.style.setProperty(key, value);
201- });
185+ setDocumentStylesFromTheme(data);
202186 },
203187 [],
204188 );
@@ -221,7 +205,7 @@
221205 );
222206
223207 useWebviewListener("setInactive", async () => {
224- dispatch(cancelStream());
208+ void dispatch(cancelStream());
225209 });
226210
227211 useWebviewListener("setTTSActive", async (status) => {
@@ -230,7 +214,7 @@
230214
231215 // TODO - remove?
232216 useWebviewListener("submitMessage", async (data) => {
233- dispatch(
217+ void dispatch(
234218 streamResponseThunk({
235219 editorState: data.message,
236220 modifiers: { useCodebase: false, noContext: true },
@@ -251,14 +235,15 @@
251235 dispatch(updateIndexingStatus(data));
252236 });
253237
254- const currentToolCallApplyState = useAppSelector(
255- selectCurrentToolCallApplyState,
256- );
257238 useWebviewListener(
258239 "updateApplyState",
259240 async (state) => {
260241 if (state.streamId === EDIT_MODE_STREAM_ID) {
261242 dispatch(updateEditStateApplyState(state));
243+
244+ if (state.status === "closed") {
245+ dispatch(exitEdit({}));
246+ }
262247 } else {
263248 // chat or agent
264249 dispatch(updateApplyState(state));
@@ -280,7 +265,7 @@
280265 }),
281266 );
282267 // dispatch(setToolCallOutput([]));
283- dispatch(
268+ void dispatch(
284269 streamResponseAfterToolCall({
285270 toolCallId: currentToolCallApplyState.toolCallId!,
286271 }),
@@ -291,12 +276,12 @@
291276 [currentToolCallApplyState, history],
292277 );
293278
294- const mode = useAppSelector((store) => store.session.mode);
295279 useEffect(() => {
296- if (mode !== "edit") {
280+ if (!isInEdit) {
297281 dispatch(setLastNonEditSessionEmpty(history.length === 0));
298282 }
299- }, [mode, history]);
283+ }, [isInEdit, history]);
284+
300285 return <></>;
301286 }
302287
modified gui/src/pages/config/HelpCenterSection.tsx +12 −0
@@ -1,6 +1,7 @@
11 import {
22 ArrowTopRightOnSquareIcon,
33 DocumentArrowUpIcon,
4+ PaintBrushIcon,
45 TableCellsIcon,
56 } from "@heroicons/react/24/outline";
67 import { useContext } from "react";
@@ -9,6 +10,7 @@
910 import { useAppDispatch } from "../../redux/hooks";
1011 import { setOnboardingCard } from "../../redux/slices/uiSlice";
1112 import { saveCurrentSession } from "../../redux/thunks/session";
13+import { ROUTES } from "../../util/navigation";
1214 import MoreHelpRow from "./MoreHelpRow";
1315
1416 export function HelpCenterSection() {
@@ -83,6 +85,16 @@
8385 ideMessenger.post("showTutorial", undefined);
8486 }}
8587 />
88+ {process.env.NODE_ENV === "development" && (
89+ <MoreHelpRow
90+ title="Theme Test Page"
91+ description="Development page for testing themes"
92+ Icon={PaintBrushIcon}
93+ onClick={async () => {
94+ navigate(ROUTES.THEME);
95+ }}
96+ />
97+ )}
8698 </div>
8799 </div>
88100 );
modified gui/src/pages/config/KeyboardShortcuts.tsx +1 −1
@@ -11,7 +11,7 @@
1111 function KeyboardShortcut(props: KeyboardShortcutProps) {
1212 return (
1313 <div
14- className={`flex flex-col items-start p-2 py-2 sm:flex-row sm:items-center ${props.isEven ? "" : "bg-table-odd-rows"}`}
14+ className={`flex flex-col items-start p-2 py-2 sm:flex-row sm:items-center ${props.isEven ? "" : "bg-table-oddRow"}`}
1515 >
1616 <div className="w-full flex-grow pb-1 pr-4 sm:w-auto sm:pb-0">
1717 <span className="block break-words text-xs">{props.description}:</span>
modified gui/src/pages/gui/Chat.test.tsx +2 −2
@@ -35,8 +35,8 @@
3535 );
3636 });
3737
38- // Check that it switched to Edit mode
39- expect(await screen.findByText("Edit")).toBeInTheDocument();
38+ // Check that it switched back to Chat mode
39+ expect(await screen.findByText("Chat")).toBeInTheDocument();
4040 });
4141
4242 it.skip("should send a message and receive a response", async () => {
modified gui/src/pages/gui/Chat.tsx +37 −40
@@ -44,24 +44,21 @@
4444 setDialogMessage,
4545 setShowDialog,
4646 } from "../../redux/slices/uiSlice";
47+import { streamResponseThunk } from "../../redux/thunks";
4748 import { cancelStream } from "../../redux/thunks/cancelStream";
48-import { streamEditThunk } from "../../redux/thunks/editMode";
49+import { streamEditThunk } from "../../redux/thunks/edit";
4950 import { loadLastSession } from "../../redux/thunks/session";
50-import { streamResponseThunk } from "../../redux/thunks";
5151 import { isJetBrains, isMetaEquivalentKeyPressed } from "../../util";
5252 import {
5353 FREE_TRIAL_LIMIT_REQUESTS,
5454 incrementFreeTrialCount,
5555 } from "../../util/freeTrial";
5656
57-import CodeToEditCard from "../../components/mainInput/CodeToEditCard";
58-import EditModeDetails from "../../components/mainInput/EditModeDetails";
5957 import { getLocalStorage, setLocalStorage } from "../../util/localStorage";
6058 import { EmptyChatBody } from "./EmptyChatBody";
6159 import { ExploreDialogWatcher } from "./ExploreDialogWatcher";
6260 import { ToolCallDiv } from "./ToolCallDiv";
6361 import { useAutoScroll } from "./useAutoScroll";
64-import AcceptRejectDiffButtons from "../../components/AcceptRejectDiffButtons";
6562
6663 const StepsDiv = styled.div`
6764 position: relative;
@@ -113,6 +110,7 @@
113110 const [stepsOpen] = useState<(boolean | undefined)[]>([]);
114111 const mainTextInputRef = useRef<HTMLInputElement>(null);
115112 const stepsDivRef = useRef<HTMLDivElement>(null);
113+ const tabsRef = useRef<HTMLDivElement>(null);
116114 const history = useAppSelector((state) => state.session.history);
117115 const showChatScrollbar = useAppSelector(
118116 (state) => state.config.config.ui?.showChatScrollbar,
@@ -120,9 +118,7 @@
120118 const codeToEdit = useAppSelector((state) => state.editModeState.codeToEdit);
121119 const toolCallState = useAppSelector(selectCurrentToolCall);
122120 const mode = useAppSelector((store) => store.session.mode);
123- const applyStates = useAppSelector(
124- (state) => state.session.codeBlockApplyStates.states,
125- );
121+ const isInEdit = useAppSelector((store) => store.session.isInEdit);
126122
127123 const lastSessionId = useAppSelector((state) => state.session.lastSessionId);
128124 const hasDismissedExploreDialog = useAppSelector(
@@ -143,6 +139,7 @@
143139 !e.shiftKey
144140 ) {
145141 dispatch(cancelStream());
142+ ideMessenger.post("cancelApply", undefined); // just always cancel, if not in applying won't matter
146143 }
147144 };
148145 window.addEventListener("keydown", listener);
@@ -152,7 +149,11 @@
152149 };
153150 }, [isStreaming, jetbrains]);
154151
155- const { widget, highlights } = useFindWidget(stepsDivRef);
152+ const { widget, highlights } = useFindWidget(
153+ stepsDivRef,
154+ tabsRef,
155+ isStreaming,
156+ );
156157
157158 const currentToolCallApplyState = useAppSelector(
158159 selectCurrentToolCallApplyState,
@@ -179,15 +180,14 @@
179180 );
180181 }
181182
182- const model =
183- mode === "edit"
184- ? (selectedModels?.edit ?? selectedModels?.chat)
185- : selectedModels?.chat;
183+ const model = isInEdit
184+ ? (selectedModels?.edit ?? selectedModels?.chat)
185+ : selectedModels?.chat;
186186 if (!model) {
187187 return;
188188 }
189189
190- if (mode === "edit" && codeToEdit.length === 0) {
190+ if (isInEdit && codeToEdit.length === 0) {
191191 return;
192192 }
193193
@@ -218,15 +218,15 @@
218218 }
219219 }
220220
221- if (mode === "edit") {
222- dispatch(
221+ if (isInEdit) {
222+ void dispatch(
223223 streamEditThunk({
224224 editorState,
225225 codeToEdit,
226226 }),
227227 );
228228 } else {
229- dispatch(streamResponseThunk({ editorState, modifiers, index }));
229+ void dispatch(streamResponseThunk({ editorState, modifiers, index }));
230230
231231 if (editorToClearOnSend) {
232232 editorToClearOnSend.commands.clearContent();
@@ -246,7 +246,15 @@
246246 setLocalStorage("mainTextEntryCounter", 1);
247247 }
248248 },
249- [history, selectedModels, streamResponse, mode, codeToEdit, toolCallState],
249+ [
250+ history,
251+ selectedModels,
252+ streamResponse,
253+ mode,
254+ isInEdit,
255+ codeToEdit,
256+ toolCallState,
257+ ],
250258 );
251259
252260 useWebviewListener(
@@ -286,13 +294,12 @@
286294
287295 return (
288296 <>
297+ {!!showSessionTabs && !isInEdit && <TabBar ref={tabsRef} />}
289298 {widget}
290299
291- {!!showSessionTabs && mode !== "edit" && <TabBar />}
292-
293300 <StepsDiv
294301 ref={stepsDivRef}
295- className={`mt-3 overflow-y-scroll pt-[8px] ${showScrollbar ? "thin-scrollbar" : "no-scrollbar"} ${history.length > 0 ? "flex-1" : ""}`}
302+ className={`overflow-y-scroll pt-[8px] ${showScrollbar ? "thin-scrollbar" : "no-scrollbar"} ${history.length > 0 ? "flex-1" : ""}`}
296303 >
297304 {highlights}
298305 {history.map((item, index: number) => (
@@ -376,24 +383,14 @@
376383 ))}
377384 </StepsDiv>
378385 <div className={"relative"}>
379- <>
380- {!isStreaming && mode !== "edit" && (
381- <AcceptRejectDiffButtons
382- applyStates={applyStates}
383- onAcceptOrReject={async () => {}}
384- />
385- )}
386- {mode === "edit" && <CodeToEditCard />}
387- <ContinueInputBox
388- isMainInput
389- isLastUserInput={false}
390- onEnter={(editorState, modifiers, editor) =>
391- sendInput(editorState, modifiers, undefined, editor)
392- }
393- inputId={MAIN_EDITOR_INPUT_ID}
394- />
395- <EditModeDetails />
396- </>
386+ <ContinueInputBox
387+ isMainInput
388+ isLastUserInput={false}
389+ onEnter={(editorState, modifiers, editor) =>
390+ sendInput(editorState, modifiers, undefined, editor)
391+ }
392+ inputId={MAIN_EDITOR_INPUT_ID}
393+ />
397394
398395 <div
399396 style={{
@@ -402,7 +399,7 @@
402399 >
403400 <div className="flex flex-row items-center justify-between pb-1 pl-0.5 pr-2">
404401 <div className="xs:inline hidden">
405- {history.length === 0 && lastSessionId && mode !== "edit" && (
402+ {history.length === 0 && lastSessionId && !isInEdit && (
406403 <div className="xs:inline hidden">
407404 <NewSessionButton
408405 onClick={async () => {
modified gui/src/pages/gui/StreamError.tsx +86 −47
@@ -1,12 +1,15 @@
11 import {
22 ArrowTopRightOnSquareIcon,
3- Cog8ToothIcon,
3+ ClipboardIcon,
4+ Cog6ToothIcon,
5+ KeyIcon,
46 } from "@heroicons/react/24/outline";
57 import { DISCORD_LINK, GITHUB_LINK } from "core/util/constants";
68 import { useContext, useMemo } from "react";
7-import { Button, SecondaryButton } from "../../components";
9+import { GhostButton, SecondaryButton } from "../../components";
810 import { DiscordIcon } from "../../components/svg/DiscordIcon";
911 import { GithubIcon } from "../../components/svg/GithubIcon";
12+import ToggleDiv from "../../components/ToggleDiv";
1013 import { useAuth } from "../../context/Auth";
1114 import { IdeMessengerContext } from "../../context/IdeMessenger";
1215 import { selectSelectedProfile } from "../../redux/";
@@ -48,11 +51,15 @@
4851 );
4952
5053 const handleRefreshProfiles = () => {
51- refreshProfiles();
54+ void refreshProfiles();
5255 dispatch(setShowDialog(false));
5356 dispatch(setDialogMessage(undefined));
5457 };
5558
59+ const copyErrorToClipboard = () => {
60+ void navigator.clipboard.writeText(parsedError);
61+ };
62+
5663 // Collect model information to display useful error info
5764 let modelTitle = "Chat model";
5865 let providerName = "the model provider";
@@ -99,30 +106,29 @@
99106 }
100107
101108 const checkKeysButton = apiKeyUrl ? (
102- <Button
103- className="cursor-pointer hover:underline"
109+ <GhostButton
110+ className="flex items-center"
104111 onClick={() => {
105112 ideMessenger.post("openUrl", apiKeyUrl!);
106113 }}
107114 >
108- Check keys/usage
109- </Button>
115+ <KeyIcon className="mr-1.5 h-3.5 w-3.5" />
116+ <span>View key</span>
117+ </GhostButton>
110118 ) : null;
111119
112120 const configButton = (
113- <SecondaryButton
114- className="flex flex-row items-center gap-1.5 hover:underline hover:opacity-70"
121+ <GhostButton
122+ className="flex items-center"
115123 onClick={() => {
116124 ideMessenger.post("config/openProfile", {
117125 profileId: undefined,
118126 });
119127 }}
120128 >
121- <div>
122- <Cog8ToothIcon className="h-4 w-4" />
123- </div>
124- <span>Open Assistant configuration</span>
125- </SecondaryButton>
129+ <Cog6ToothIcon className="mr-1.5 h-3.5 w-3.5" />
130+ <span>View config</span>
131+ </GhostButton>
126132 );
127133
128134 if (
@@ -131,7 +137,20 @@
131137 return <ModelsAddOnLimitDialog />;
132138 }
133139
134- let errorContent: React.ReactNode = <></>;
140+ let errorContent = (
141+ <div className="mb-3 mt-1">
142+ <div className="m-0 p-0">
143+ <p className="m-0 mb-2 p-0">
144+ There was an error handling the response from{" "}
145+ {selectedModel?.title || "the model"}.
146+ </p>
147+ <p className="m-0 p-0">
148+ Please try to submit your message again, and if the error persists,
149+ let us know by reporting the issue using the buttons below.
150+ </p>
151+ </div>
152+ </div>
153+ );
135154
136155 // Display components for specific errors
137156 if (statusCode === 429) {
@@ -141,7 +160,7 @@
141160 {`This might mean your ${modelTitle} usage has been rate limited
142161 by ${providerName}.`}
143162 </span>
144- <div className="flex flex-row flex-wrap gap-2">
163+ <div className="flex flex-row flex-wrap justify-start gap-3 py-4">
145164 {checkKeysButton}
146165 {configButton}
147166 </div>
@@ -230,51 +249,71 @@
230249 );
231250 }
232251
252+ console.log({ message });
253+
233254 return (
234- <div className={`flex flex-col gap-1 px-3 pb-2 pt-3`}>
235- <p className="m-0 p-0 text-lg text-red-500">
236- {statusCode ? `Error (status code ${statusCode})` : "Error"}
237- </p>
238-
239- {message ? (
240- <div className="mt-2 flex flex-col gap-0 rounded-sm">
241- <code className="max-h-20 overflow-y-auto p-2 font-mono">
242- {parsedError}
243- </code>
244- <div
245- className="flex cursor-pointer flex-row items-center justify-end px-1 py-1 text-gray-500 hover:underline"
246- onClick={() => {
247- ideMessenger.post("toggleDevTools", undefined);
248- }}
249- >
250- <span className="px-2">View Logs</span>
251- <ArrowTopRightOnSquareIcon className="h-4 w-4" />
252- </div>
255+ <div className="flex flex-col gap-4 px-3 pb-3 pt-3">
256+ {/* Concise error title */}
257+ <h3 className="text-error m-0 p-0 text-lg font-medium">
258+ Error handling model response
259+ </h3>
260+
261+ {errorContent}
262+
263+ {/* Expandable technical details using ToggleDiv */}
264+ {message && (
265+ <div className="mb-2">
266+ <ToggleDiv title="View error output" testId="error-output-toggle">
267+ <div className="flex flex-col gap-0 rounded-sm">
268+ <code className="text-editor-foreground block max-h-48 overflow-y-auto p-3 font-mono text-xs">
269+ {parsedError}
270+ </code>
271+
272+ <div className="flex flex-row items-center justify-end gap-2 p-2">
273+ <GhostButton
274+ onClick={copyErrorToClipboard}
275+ className="flex items-center"
276+ >
277+ <ClipboardIcon className="mr-1.5 h-3.5 w-3.5" />
278+ <span>Copy output</span>
279+ </GhostButton>
280+
281+ <GhostButton
282+ onClick={() => {
283+ ideMessenger.post("toggleDevTools", undefined);
284+ }}
285+ className="flex items-center"
286+ >
287+ <ArrowTopRightOnSquareIcon className="mr-1.5 h-4 w-4" />
288+ <span className="text-xs">View Logs</span>
289+ </GhostButton>
290+ </div>
291+ </div>
292+ </ToggleDiv>
253293 </div>
254- ) : null}
255- <div className="mt-3">{errorContent}</div>
256-
257- <div className="mt-2 flex flex-col gap-1.5">
258- <span>Report this error:</span>
259- <div className="flex flex-row flex-wrap items-center gap-2">
260- <SecondaryButton
261- className="flex flex-row items-center gap-2 hover:opacity-70"
294+ )}
295+
296+ <div>
297+ <span className="text-base font-medium">Report this error</span>
298+ <div className="mt-2 flex flex-row flex-wrap items-center gap-2">
299+ <GhostButton
300+ className="flex flex-row items-center gap-2 rounded px-3 py-1.5"
262301 onClick={() => {
263302 ideMessenger.post("openUrl", GITHUB_LINK);
264303 }}
265304 >
266305 <GithubIcon className="h-5 w-5" />
267306 <span className="xs:flex hidden">Github</span>
268- </SecondaryButton>
269- <SecondaryButton
270- className="flex flex-row items-center gap-2 hover:opacity-70"
307+ </GhostButton>
308+ <GhostButton
309+ className="flex flex-row items-center gap-2 rounded px-3 py-1.5"
271310 onClick={() => {
272311 ideMessenger.post("openUrl", DISCORD_LINK);
273312 }}
274313 >
275314 <DiscordIcon className="h-5 w-5" />
276315 <span className="xs:flex hidden">Discord</span>
277- </SecondaryButton>
316+ </GhostButton>
278317 </div>
279318 </div>
280319 </div>
deleted gui/src/redux/slices/editModeState.ts +0 −77
@@ -1,77 +0,0 @@
1-import { createSlice, PayloadAction } from "@reduxjs/toolkit";
2-import { ApplyState, SetCodeToEditPayload, MessageModes } from "core";
3-import { EDIT_MODE_STREAM_ID } from "core/edit/constants";
4-
5-export interface EditModeState {
6- // Array because of previous multi-file edit functionality
7- // Keeping array to not break persisted redux for now
8- codeToEdit: SetCodeToEditPayload[];
9- applyState: ApplyState;
10- returnToMode: MessageModes;
11- lastNonEditSessionWasEmpty: boolean;
12-}
13-
14-export const INITIAL_EDIT_APPLY_STATE: ApplyState = {
15- streamId: EDIT_MODE_STREAM_ID,
16- status: "not-started",
17-};
18-
19-const initialState: EditModeState = {
20- applyState: INITIAL_EDIT_APPLY_STATE,
21- codeToEdit: [],
22- returnToMode: "chat",
23- lastNonEditSessionWasEmpty: false,
24-};
25-
26-export const editModeStateSlice = createSlice({
27- name: "editModeState",
28- initialState,
29- reducers: {
30- setReturnToModeAfterEdit: (
31- state,
32- { payload }: PayloadAction<MessageModes>,
33- ) => {
34- state.returnToMode = payload;
35- },
36- updateEditStateApplyState: (
37- state,
38- { payload }: PayloadAction<ApplyState>,
39- ) => {
40- state.applyState = {
41- ...state.applyState,
42- ...payload,
43- };
44- },
45- setCodeToEdit: (
46- state,
47- {
48- payload,
49- }: PayloadAction<{
50- codeToEdit: SetCodeToEditPayload | SetCodeToEditPayload[];
51- }>,
52- ) => {
53- state.codeToEdit = Array.isArray(payload.codeToEdit)
54- ? payload.codeToEdit
55- : [payload.codeToEdit];
56- },
57- clearCodeToEdit: (state) => {
58- state.codeToEdit = [];
59- },
60- setLastNonEditSessionEmpty: (
61- state,
62- { payload }: PayloadAction<boolean>,
63- ) => {
64- state.lastNonEditSessionWasEmpty = payload;
65- },
66- },
67- selectors: {},
68-});
69-
70-export const {
71- setReturnToModeAfterEdit,
72- clearCodeToEdit,
73- setCodeToEdit,
74- updateEditStateApplyState,
75- setLastNonEditSessionEmpty,
76-} = editModeStateSlice.actions;
77-export default editModeStateSlice.reducer;
added gui/src/redux/slices/editState.ts +87 −0
@@ -0,0 +1,87 @@
1+import { createSlice, PayloadAction } from "@reduxjs/toolkit";
2+import { JSONContent } from "@tiptap/core";
3+import { ApplyState, MessageModes, SetCodeToEditPayload } from "core";
4+import { EDIT_MODE_STREAM_ID } from "core/edit/constants";
5+
6+export interface EditState {
7+ // Array because of previous multi-file edit functionality
8+ // Keeping array to not break persisted redux for now
9+ codeToEdit: SetCodeToEditPayload[];
10+ applyState: ApplyState;
11+ returnToMode: MessageModes;
12+ lastNonEditSessionWasEmpty: boolean;
13+ previousModeEditorContent: JSONContent | undefined;
14+}
15+
16+export const INITIAL_EDIT_APPLY_STATE: ApplyState = {
17+ streamId: EDIT_MODE_STREAM_ID,
18+ status: "not-started",
19+};
20+
21+const initialState: EditState = {
22+ applyState: INITIAL_EDIT_APPLY_STATE,
23+ codeToEdit: [],
24+ returnToMode: "chat",
25+ lastNonEditSessionWasEmpty: false,
26+ previousModeEditorContent: undefined,
27+};
28+
29+export const editStateSlice = createSlice({
30+ name: "editState",
31+ initialState,
32+ reducers: {
33+ setReturnToModeAfterEdit: (
34+ state,
35+ { payload }: PayloadAction<MessageModes>,
36+ ) => {
37+ state.returnToMode = payload;
38+ },
39+ updateEditStateApplyState: (
40+ state,
41+ { payload }: PayloadAction<ApplyState>,
42+ ) => {
43+ state.applyState = {
44+ ...state.applyState,
45+ ...payload,
46+ };
47+ },
48+ setCodeToEdit: (
49+ state,
50+ {
51+ payload,
52+ }: PayloadAction<{
53+ codeToEdit: SetCodeToEditPayload | SetCodeToEditPayload[];
54+ }>,
55+ ) => {
56+ state.codeToEdit = Array.isArray(payload.codeToEdit)
57+ ? payload.codeToEdit
58+ : [payload.codeToEdit];
59+ },
60+ clearCodeToEdit: (state) => {
61+ state.codeToEdit = [];
62+ },
63+ setLastNonEditSessionEmpty: (
64+ state,
65+ { payload }: PayloadAction<boolean>,
66+ ) => {
67+ state.lastNonEditSessionWasEmpty = payload;
68+ },
69+ setPreviousModeEditorContent: (
70+ state,
71+ { payload }: PayloadAction<JSONContent | undefined>,
72+ ) => {
73+ state.previousModeEditorContent = payload;
74+ },
75+ },
76+ selectors: {},
77+});
78+
79+export const {
80+ setReturnToModeAfterEdit,
81+ clearCodeToEdit,
82+ setCodeToEdit,
83+ updateEditStateApplyState,
84+ setLastNonEditSessionEmpty,
85+ setPreviousModeEditorContent,
86+} = editStateSlice.actions;
87+export default editStateSlice.reducer;
modified gui/src/redux/slices/sessionSlice.ts +6 −0
@@ -47,6 +47,7 @@
4747 mainEditorContentTrigger?: JSONContent | undefined;
4848 symbols: FileSymbolMap;
4949 mode: MessageModes;
50+ isInEdit: boolean;
5051 codeBlockApplyStates: {
5152 states: ApplyState[];
5253 curIndex: number;
@@ -63,6 +64,7 @@
6364 streamAborter: new AbortController(),
6465 symbols: {},
6566 mode: "chat",
67+ isInEdit: false,
6668 codeBlockApplyStates: {
6769 states: [],
6870 curIndex: 0,
@@ -645,6 +647,9 @@
645647 setMode: (state, action: PayloadAction<MessageModes>) => {
646648 state.mode = action.payload;
647649 },
650+ setIsInEdit: (state, action: PayloadAction<boolean>) => {
651+ state.isInEdit = action.payload;
652+ },
648653 setNewestToolbarPreviewForInput: (
649654 state,
650655 {
@@ -741,6 +746,7 @@
741746 updateSessionMetadata,
742747 deleteSessionMetadata,
743748 setNewestToolbarPreviewForInput,
749+ setIsInEdit,
744750 } = sessionSlice.actions;
745751
746752 export const { selectIsGatheringContext } = sessionSlice.selectors;
modified gui/src/redux/store.ts +1 −1
@@ -17,7 +17,7 @@
1717 import { IdeMessenger, IIdeMessenger } from "../context/IdeMessenger";
1818 import { profilesReducer } from "./slices";
1919 import configReducer from "./slices/configSlice";
20-import editModeStateReducer from "./slices/editModeState";
20+import editModeStateReducer from "./slices/editState";
2121 import indexingReducer from "./slices/indexingSlice";
2222 import sessionReducer from "./slices/sessionSlice";
2323 import tabsReducer from "./slices/tabsSlice";
added gui/src/redux/thunks/edit.ts +155 −0
@@ -0,0 +1,155 @@
1+import { createAsyncThunk } from "@reduxjs/toolkit";
2+import { JSONContent } from "@tiptap/core";
3+import {
4+ MessageModes,
5+ RangeInFileWithContents,
6+ SetCodeToEditPayload,
7+} from "core";
8+import { stripImages } from "core/util/messageContent";
9+import { resolveEditorContent } from "../../components/mainInput/TipTapEditor";
10+import {
11+ clearCodeToEdit,
12+ INITIAL_EDIT_APPLY_STATE,
13+ setPreviousModeEditorContent,
14+ setReturnToModeAfterEdit,
15+ updateEditStateApplyState,
16+} from "../slices/editState";
17+import {
18+ newSession,
19+ setActive,
20+ setIsInEdit,
21+ setMainEditorContentTrigger,
22+ setMode,
23+} from "../slices/sessionSlice";
24+import { ThunkApiType } from "../store";
25+import { loadLastSession, saveCurrentSession } from "./session";
26+import { streamThunkWrapper } from "./streamThunkWrapper";
27+
28+export const streamEditThunk = createAsyncThunk<
29+ void,
30+ {
31+ editorState: JSONContent;
32+ codeToEdit: SetCodeToEditPayload[];
33+ },
34+ ThunkApiType
35+>(
36+ "chat/streamResponse",
37+ async ({ editorState, codeToEdit }, { dispatch, extra }) => {
38+ await dispatch(
39+ streamThunkWrapper(async () => {
40+ dispatch(setActive());
41+ const [contextItems, __, userInstructions, _] =
42+ await resolveEditorContent({
43+ editorState,
44+ modifiers: {
45+ noContext: true,
46+ useCodebase: false,
47+ },
48+ ideMessenger: extra.ideMessenger,
49+ defaultContextProviders: [],
50+ availableSlashCommands: [],
51+ dispatch,
52+ });
53+
54+ const prompt = [
55+ ...contextItems.map((item) => item.content),
56+ stripImages(userInstructions),
57+ ].join("\n\n");
58+
59+ const response = await extra.ideMessenger.request("edit/sendPrompt", {
60+ prompt,
61+ range: codeToEdit[0] as RangeInFileWithContents,
62+ });
63+
64+ if (response.status === "error") {
65+ throw new Error(response.error);
66+ }
67+ }),
68+ );
69+ },
70+);
71+
72+export const exitEdit = createAsyncThunk<
73+ void,
74+ { goToMode?: MessageModes; openNewSession?: boolean },
75+ ThunkApiType
76+>(
77+ "edit/exit",
78+ async ({ goToMode, openNewSession }, { dispatch, extra, getState }) => {
79+ const state = getState();
80+ const codeToEdit = state.editModeState.codeToEdit;
81+ const isInEdit = state.session.isInEdit;
82+ const previousModeEditorContent =
83+ state.editModeState.previousModeEditorContent;
84+
85+ if (!isInEdit) {
86+ return;
87+ }
88+
89+ if (codeToEdit[0] && state.editModeState.applyState.numDiffs) {
90+ extra.ideMessenger.post("rejectDiff", {
91+ filepath: codeToEdit[0].filepath,
92+ });
93+ }
94+
95+ extra.ideMessenger.post("edit/clearDecorations", undefined);
96+
97+ dispatch(clearCodeToEdit());
98+ dispatch(updateEditStateApplyState(INITIAL_EDIT_APPLY_STATE));
99+ dispatch(setIsInEdit(false));
100+
101+ // Restore the previous editor content if available
102+ if (previousModeEditorContent) {
103+ dispatch(setMainEditorContentTrigger(previousModeEditorContent));
104+ dispatch(setPreviousModeEditorContent(undefined));
105+ }
106+
107+ if (openNewSession || state.editModeState.lastNonEditSessionWasEmpty) {
108+ dispatch(newSession());
109+ } else {
110+ await dispatch(
111+ loadLastSession({
112+ saveCurrentSession: false,
113+ }),
114+ );
115+ }
116+
117+ dispatch(setMode(goToMode ?? state.editModeState.returnToMode));
118+ },
119+);
120+
121+export const enterEdit = createAsyncThunk<
122+ void,
123+ { returnToMode?: MessageModes; editorContent?: JSONContent },
124+ ThunkApiType
125+>(
126+ "edit/enter",
127+ async ({ returnToMode, editorContent }, { dispatch, extra, getState }) => {
128+ const state = getState();
129+ const isInEdit = state.session.isInEdit;
130+
131+ if (isInEdit) {
132+ return;
133+ }
134+
135+ dispatch(setMainEditorContentTrigger({}));
136+ dispatch(setPreviousModeEditorContent(editorContent));
137+
138+ dispatch(setReturnToModeAfterEdit(returnToMode ?? state.session.mode));
139+ dispatch(updateEditStateApplyState(INITIAL_EDIT_APPLY_STATE));
140+
141+ await dispatch(
142+ saveCurrentSession({
143+ openNewSession: true,
144+ // Because this causes a lag before Edit is focused. TODO just have that happen in background
145+ generateTitle: false,
146+ }),
147+ );
148+
149+ dispatch(setIsInEdit(true));
150+
151+ if (!state.editModeState.codeToEdit[0]) {
152+ extra.ideMessenger.post("edit/addCurrentSelection", undefined);
153+ }
154+ },
155+);
deleted gui/src/redux/thunks/editMode.ts +0 −130
@@ -1,130 +0,0 @@
1-import { createAsyncThunk } from "@reduxjs/toolkit";
2-import { JSONContent } from "@tiptap/core";
3-import {
4- SetCodeToEditPayload,
5- MessageModes,
6- RangeInFileWithContents,
7-} from "core";
8-import { stripImages } from "core/util/messageContent";
9-import { resolveEditorContent } from "../../components/mainInput/TipTapEditor";
10-import {
11- clearCodeToEdit,
12- INITIAL_EDIT_APPLY_STATE,
13- setReturnToModeAfterEdit,
14- updateEditStateApplyState,
15-} from "../slices/editModeState";
16-import { newSession, setActive, setMode } from "../slices/sessionSlice";
17-import { ThunkApiType } from "../store";
18-import { loadLastSession, saveCurrentSession } from "./session";
19-import { streamThunkWrapper } from "./streamThunkWrapper";
20-
21-export const streamEditThunk = createAsyncThunk<
22- void,
23- {
24- editorState: JSONContent;
25- codeToEdit: SetCodeToEditPayload[];
26- },
27- ThunkApiType
28->(
29- "chat/streamResponse",
30- async ({ editorState, codeToEdit }, { dispatch, extra, getState }) => {
31- await dispatch(
32- streamThunkWrapper(async () => {
33- dispatch(setActive());
34- const [contextItems, __, userInstructions, _] =
35- await resolveEditorContent({
36- editorState,
37- modifiers: {
38- noContext: true,
39- useCodebase: false,
40- },
41- ideMessenger: extra.ideMessenger,
42- defaultContextProviders: [],
43- availableSlashCommands: [],
44- dispatch,
45- });
46-
47- const prompt = [
48- ...contextItems.map((item) => item.content),
49- stripImages(userInstructions),
50- ].join("\n\n");
51-
52- const response = await extra.ideMessenger.request("edit/sendPrompt", {
53- prompt,
54- range: codeToEdit[0] as RangeInFileWithContents,
55- });
56-
57- if (response.status === "error") {
58- throw new Error(response.error);
59- }
60- }),
61- );
62- },
63-);
64-
65-export const exitEditMode = createAsyncThunk<
66- void,
67- { goToMode?: MessageModes; openNewSession?: boolean },
68- ThunkApiType
69->(
70- "edit/exitMode",
71- async ({ goToMode, openNewSession }, { dispatch, extra, getState }) => {
72- const state = getState();
73- const codeToEdit = state.editModeState.codeToEdit;
74-
75- if (state.session.mode !== "edit") {
76- return;
77- }
78-
79- if (codeToEdit[0] && state.editModeState.applyState.numDiffs) {
80- extra.ideMessenger.post("rejectDiff", {
81- filepath: codeToEdit[0].filepath,
82- });
83- }
84-
85- extra.ideMessenger.post("edit/clearDecorations", undefined);
86-
87- dispatch(clearCodeToEdit());
88- dispatch(updateEditStateApplyState(INITIAL_EDIT_APPLY_STATE));
89-
90- if (openNewSession || state.editModeState.lastNonEditSessionWasEmpty) {
91- dispatch(newSession());
92- } else {
93- await dispatch(
94- loadLastSession({
95- saveCurrentSession: false,
96- }),
97- );
98- }
99-
100- dispatch(setMode(goToMode ?? state.editModeState.returnToMode));
101- },
102-);
103-
104-export const enterEditMode = createAsyncThunk<
105- void,
106- { returnToMode?: MessageModes },
107- ThunkApiType
108->("edit/enterMode", async ({ returnToMode }, { dispatch, extra, getState }) => {
109- const state = getState();
110-
111- if (state.session.mode === "edit") {
112- return;
113- }
114-
115- dispatch(setReturnToModeAfterEdit(returnToMode ?? state.session.mode));
116-
117- await dispatch(
118- saveCurrentSession({
119- openNewSession: true,
120- // Because this causes a lag before Edit mode is focused. TODO just have that happen in background
121- generateTitle: false,
122- }),
123- );
124- dispatch(updateEditStateApplyState(INITIAL_EDIT_APPLY_STATE));
125- dispatch(setMode("edit"));
126-
127- if (!state.editModeState.codeToEdit[0]) {
128- extra.ideMessenger.post("edit/addCurrentSelection", undefined);
129- }
130-});
modified gui/src/redux/thunks/index.ts +11 −7
@@ -1,7 +1,11 @@
1-export { gatherContext } from "./gatherContext";
2-export { resetStateForNewMessage } from "./resetStateForNewMessage";
3-export { streamNormalInput } from "./streamNormalInput";
4-export { streamResponseThunk } from "./streamResponse";
5-export { streamResponseAfterToolCall } from "./streamResponseAfterToolCall";
6-export { streamThunkWrapper } from "./streamThunkWrapper";
7-export { updateSelectedModelByRole } from "./updateSelectedModelByRole";
1+export * from "./callCurrentTool";
2+export * from "./cancelCurrentToolCall";
3+export * from "./cancelStream";
4+export * from "./edit";
5+export * from "./gatherContext";
6+export * from "./resetStateForNewMessage";
7+export * from "./streamNormalInput";
8+export * from "./streamResponse";
9+export * from "./streamResponseAfterToolCall";
10+export * from "./streamThunkWrapper";
11+export * from "./updateSelectedModelByRole";
modified gui/src/redux/thunks/streamNormalInput.ts +1 −1
@@ -79,7 +79,7 @@
7979 data: {
8080 prompt: next.value.prompt,
8181 completion: next.value.completion,
82- modelProvider: selectedChatModel.provider,
82+ modelProvider: selectedChatModel.underlyingProviderName,
8383 modelTitle: selectedChatModel.title,
8484 sessionId: state.session.id,
8585 },
added gui/src/styles/ThemePage.tsx +232 −0
@@ -0,0 +1,232 @@
1+import {
2+ CheckCircleIcon,
3+ ExclamationCircleIcon,
4+ ExclamationTriangleIcon,
5+} from "@heroicons/react/24/outline";
6+import { useContext, useEffect, useMemo, useState } from "react";
7+import { useNavigate } from "react-router-dom";
8+import { Button } from "../components";
9+import { IdeMessengerContext } from "../context/IdeMessenger";
10+import { isJetBrains } from "../util";
11+import { ROUTES } from "../util/navigation";
12+import {
13+ clearThemeLocalCache,
14+ setDocumentStylesFromTheme,
15+ THEME_COLORS,
16+ varWithFallback,
17+} from "./theme";
18+
19+const ThemeTailwindClassExample = ({
20+ colorName,
21+ varNames,
22+ defaultColor,
23+ isMissing,
24+}: {
25+ colorName: string;
26+ varNames: string[];
27+ defaultColor: string;
28+ isMissing?: boolean;
29+}) => {
30+ return (
31+ <>
32+ <div className={`line-clamp-1 break-all px-2 text-right`}>
33+ {colorName}
34+ </div>
35+ <div
36+ className={`line-clamp-1 break-all p-1 text-[9px] ${isMissing ? "text-error" : ""}`}
37+ style={{
38+ backgroundColor: varWithFallback(
39+ colorName as keyof typeof THEME_COLORS,
40+ ),
41+ }}
42+ >
43+ {varNames.join(", ")}
44+ </div>
45+ <div
46+ className={`line-clamp-1 break-all p-1 text-[9px]`}
47+ style={{
48+ backgroundColor: defaultColor,
49+ }}
50+ >
51+ {defaultColor}
52+ </div>
53+ </>
54+ );
55+};
56+
57+function ThemePage() {
58+ const navigate = useNavigate();
59+ const [listToggled, setListToggled] = useState(false);
60+ const ideMessenger = useContext(IdeMessengerContext);
61+ const jetbrains = useMemo(() => {
62+ return isJetBrains();
63+ }, []);
64+
65+ const [missingVars, setMissingVars] = useState<string[]>([]);
66+ const refreshColors = () => {
67+ if (jetbrains) {
68+ // Jetbrains: get colors and check which ones are missing from theme
69+ void ideMessenger
70+ .request("jetbrains/getColors", undefined)
71+ .then((result) => {
72+ console.log(result);
73+ if (result.status === "success") {
74+ const missingColors = setDocumentStylesFromTheme(result.content);
75+ setMissingVars(missingColors);
76+ }
77+ });
78+ } else {
79+ // VS Code: find actual missing CSS variables
80+ const notFound: string[] = [];
81+ Object.entries(THEME_COLORS).forEach(([colorName, themeVals], idx) => {
82+ let found = false;
83+ themeVals.vars.forEach((cssVar) => {
84+ const value = getComputedStyle(
85+ document.documentElement,
86+ ).getPropertyValue(cssVar);
87+ if (!value) {
88+ notFound.push(`cssVar (choice #${idx + 1} for color ${colorName}`);
89+ }
90+ });
91+ });
92+ setMissingVars(notFound);
93+ }
94+ };
95+
96+ useEffect(() => {
97+ refreshColors();
98+ }, []);
99+
100+ return (
101+ <div className="flex flex-1 flex-col gap-3 px-2 py-2">
102+ <span
103+ className="flex cursor-pointer flex-row items-center gap-2"
104+ onClick={() => navigate(ROUTES.HOME)}
105+ >
106+ <span className="">←</span>
107+ Back to Chat
108+ </span>
109+ <h2 className="mb-2 mt-0 p-0 text-center text-xl font-semibold">
110+ Theme Tester
111+ </h2>
112+ <div className="bg-background border-border grid grid-cols-1 gap-4 rounded-md border border-solid p-4 md:grid-cols-2">
113+ <div className="col-span-2 flex gap-4">
114+ <p className="">Normal text</p>
115+ <p className="text-description">Description text</p>
116+ <p className="text-description-muted">Muted text</p>
117+ </div>
118+
119+ <button className="bg-primary text-primary-foreground hover:bg-primary-hover cursor-pointer rounded border-none px-4 py-2 disabled:cursor-not-allowed disabled:brightness-75">
120+ Primary Button
121+ </button>
122+ <button className="bg-secondary text-secondary-foreground hover:bg-secondary-hover cursor-pointer rounded border-none px-4 py-2 disabled:cursor-not-allowed disabled:brightness-75">
123+ Secondary Button
124+ </button>
125+
126+ <div className="border-border rounded-md border border-solid p-3">
127+ Normal border
128+ </div>
129+
130+ <div className="border-border-focus rounded-md border border-solid p-3">
131+ Focus border
132+ </div>
133+
134+ <input
135+ className="bg-input text-input-foreground border-input-border placeholder:text-input-placeholder focus:border-border-focus rounded-md border border-solid p-2 focus:outline-none"
136+ placeholder="Input example"
137+ />
138+
139+ <div className="bg-badge text-badge-foreground border-border inline-block rounded-full border border-solid p-2">
140+ <span className="px-2">Badge</span>
141+ </div>
142+
143+ <div className="flex items-center gap-2">
144+ <CheckCircleIcon className="text-success h-4 w-4" />
145+ <span className="text-success">Success</span>
146+ </div>
147+ <div className="flex items-center gap-2">
148+ <ExclamationCircleIcon className="text-warning h-4 w-4" />
149+ <span className="text-warning">Warning</span>
150+ </div>
151+ <div className="flex items-center gap-2">
152+ <ExclamationTriangleIcon className="text-error h-4 w-4" />
153+ <span className="text-error">Error</span>
154+ </div>
155+
156+ <div
157+ onClick={() => setListToggled(!listToggled)}
158+ className={`cursor-pointer p-2 ${listToggled ? "bg-list-active text-list-active-foreground" : "bg-background text-foreground hover:bg-list-hover"}`}
159+ >
160+ List item (clickable)
161+ </div>
162+ <div className="bg-editor text-editor-foreground border-border rounded-sm border border-solid p-2">
163+ <span>Editor</span>
164+ </div>
165+ <table>
166+ <tbody>
167+ <tr>
168+ <td className="border-border border-b border-solid p-2">
169+ <span>even table row</span>
170+ </td>
171+ </tr>
172+ <tr className="bg-table-oddRow">
173+ <td className="border-border border-b border-solid p-2">
174+ <span>odd table row</span>
175+ </td>
176+ </tr>
177+ </tbody>
178+ </table>
179+ <div>
180+ <span className="text-link">Link</span>
181+ </div>
182+ <div className="flex items-center gap-2">
183+ <span className="bg-findMatch">find match</span>
184+ <span className="bg-findMatch-selected">current match</span>
185+ </div>
186+ <div className="flex items-center gap-2">
187+ <span className="">Accent</span>
188+ <div className="bg-accent h-3 w-3" />
189+ </div>
190+ </div>
191+ <h2 className="mb-2 mt-6 text-xl font-semibold">Manage Theme</h2>
192+ <h2 className="mb-2 text-lg font-semibold">Missing Theme Colors</h2>
193+ {missingVars.length > 0 ? (
194+ <div className="flex flex-col gap-1">
195+ {missingVars.map((varName) => (
196+ <div key={varName} className="">
197+ {varName}
198+ </div>
199+ ))}
200+ </div>
201+ ) : (
202+ <div className="">No missing variables</div>
203+ )}
204+ <Button onClick={refreshColors}>Refresh Missing Colors</Button>
205+ {jetbrains ? (
206+ <Button onClick={clearThemeLocalCache}>Clear Theme Cache</Button>
207+ ) : null}
208+ <h2 className="mb-2 mt-6 text-xl font-semibold">All Theme Colors</h2>
209+ <div className="grid grid-cols-3">
210+ <div className="p-1">
211+ <span className="font-bold">Theme Color</span>
212+ </div>
213+ <div className="p-1">
214+ <span className="font-bold">CSS Var</span>
215+ </div>
216+ <div className="p-1">
217+ <span className="font-bold">Default</span>
218+ </div>
219+ {Object.entries(THEME_COLORS).map(([colorName, val]) => (
220+ <ThemeTailwindClassExample
221+ isMissing={missingVars.includes(colorName)}
222+ key={colorName}
223+ colorName={colorName}
224+ defaultColor={val.default}
225+ varNames={val.vars}
226+ />
227+ ))}
228+ </div>
229+ </div>
230+ );
231+}
232+export default ThemePage;
added gui/src/styles/theme.test.ts +24 −0
@@ -0,0 +1,24 @@
1+import { getRecursiveVar } from "./theme";
2+
3+test("getRecursiveVar returns single var with default for one variable", () => {
4+ const vars = ["--test-var"];
5+ const defaultColor = "#ffffff";
6+ const result = getRecursiveVar(vars, defaultColor);
7+ expect(result).toBe("var(--test-var, #ffffff)");
8+});
9+
10+test("getRecursiveVar returns nested vars in correct order for multiple variables", () => {
11+ const vars = ["--first-var", "--second-var", "--third-var"];
12+ const defaultColor = "#000000";
13+ const result = getRecursiveVar(vars, defaultColor);
14+ expect(result).toBe(
15+ "var(--first-var, var(--second-var, var(--third-var, #000000)))",
16+ );
17+});
18+
19+test("getRecursiveVar handles empty vars array", () => {
20+ const vars: string[] = [];
21+ const defaultColor = "#123456";
22+ const result = getRecursiveVar(vars, defaultColor);
23+ expect(result).toBe("#123456");
24+});
added gui/src/styles/theme.ts +271 −0
@@ -0,0 +1,271 @@
1+// All vscode variables https://gist.github.com/estruyf/ba49203e1a7d6868e9320a4ea480c27a
2+// Examples for vscode https://github.com/githubocto/tailwind-vscode/blob/main/index.js
3+
4+// The current default theme is dark with blue accents
5+export const THEME_COLORS = {
6+ background: {
7+ vars: [
8+ "--vscode-sideBar-background",
9+ "--vscode-editor-background",
10+ "--vscode-panel-background",
11+ ],
12+ default: "#1e1e1e", // dark gray
13+ },
14+ foreground: {
15+ vars: [
16+ "--vscode-sideBar-foreground",
17+ "--vscode-editor-foreground",
18+ "--vscode-panel-foreground",
19+ ],
20+ default: "#e6e6e6", // light gray
21+ },
22+ "editor-background": {
23+ vars: ["--vscode-editor-background"],
24+ default: "#1e1e1e", // dark gray
25+ },
26+ "editor-foreground": {
27+ vars: ["--vscode-editor-foreground"],
28+ default: "#e6e6e6", // light gray
29+ },
30+ "primary-background": {
31+ vars: ["--vscode-button-background"],
32+ default: "#2c5aa0", // medium blue
33+ },
34+ "primary-foreground": {
35+ vars: ["--vscode-button-foreground"],
36+ default: "#ffffff", // white
37+ },
38+ "primary-hover": {
39+ vars: ["--vscode-button-hoverBackground"],
40+ default: "#3a6db3", // lighter blue
41+ },
42+ "secondary-background": {
43+ vars: ["--vscode-button-secondaryBackground"],
44+ default: "#303030", // medium dark gray
45+ },
46+ "secondary-foreground": {
47+ vars: ["--vscode-button-secondaryForeground"],
48+ default: "#e6e6e6", // light gray
49+ },
50+ "secondary-hover": {
51+ vars: ["--vscode-button-secondaryHoverBackground"],
52+ default: "#3a3a3a", // medium gray
53+ },
54+ border: {
55+ vars: ["--vscode-sideBar-border", "--vscode-panel-border"],
56+ default: "#2a2a2a", // dark gray border
57+ },
58+ "border-focus": {
59+ vars: ["--vscode-focusBorder"],
60+ default: "#3a6db3", // lighter blue
61+ },
62+ // Command styles are used for tip-tap editor
63+ "command-background": {
64+ vars: ["--vscode-commandCenter-background"],
65+ default: "#252525", // dark gray
66+ },
67+ "command-foreground": {
68+ vars: ["--vscode-commandCenter-foreground"],
69+ default: "#e6e6e6", // light gray
70+ },
71+ "command-border": {
72+ vars: ["--vscode-commandCenter-inactiveBorder"],
73+ default: "#555555", // medium gray
74+ },
75+ "command-border-focus": {
76+ vars: ["--vscode-commandCenter-activeBorder"],
77+ default: "#4d8bf0", // bright blue
78+ },
79+ description: {
80+ vars: ["--vscode-descriptionForeground"],
81+ default: "#b3b3b3", // medium light gray
82+ },
83+ "description-muted": {
84+ vars: ["--vscode-list-deemphasizedForeground"],
85+ default: "#8c8c8c", // medium gray
86+ },
87+ "input-background": {
88+ vars: ["--vscode-input-background"],
89+ default: "#2d2d2d", // dark gray
90+ },
91+ "input-foreground": {
92+ vars: ["--vscode-input-foreground"],
93+ default: "#e6e6e6", // light gray
94+ },
95+ "input-border": {
96+ vars: [
97+ "--vscode-input-border",
98+ "--vscode-commandCenter-inactiveBorder",
99+ "vscode-border",
100+ ],
101+ default: "#555555", // medium gray
102+ },
103+ "input-placeholder": {
104+ vars: ["--vscode-input-placeholderForeground"],
105+ default: "#9e9e9e", // medium light gray
106+ },
107+ "table-oddRow": {
108+ vars: ["--vscode-tree-tableOddRowsBackground"],
109+ default: "#2d2d2d", // dark gray
110+ },
111+ "badge-background": {
112+ vars: ["--vscode-badge-background"],
113+ default: "#4d4d4d", // medium dark gray
114+ },
115+ "badge-foreground": {
116+ vars: ["--vscode-badge-foreground"],
117+ default: "#ffffff", // white
118+ },
119+ success: {
120+ vars: [
121+ "--vscode-notebookStatusSuccessIcon-foreground",
122+ "--vscode-testing-iconPassed",
123+ "--vscode-gitDecoration-addedResourceForeground",
124+ "--vscode-charts-green",
125+ ],
126+ default: "#4caf50", // green
127+ },
128+ warning: {
129+ vars: [
130+ "--vscode-editorWarning-foreground",
131+ "--vscode-list-warningForeground",
132+ ],
133+ default: "#ffb74d", // amber/yellow
134+ },
135+ error: {
136+ vars: ["--vscode-editorError-foreground", "--vscode-list-errorForeground"],
137+ default: "#f44336", // red
138+ },
139+ link: {
140+ vars: ["--vscode-textLink-foreground"],
141+ default: "#5c9ce6", // medium blue
142+ },
143+ accent: {
144+ vars: ["--vscode-tab-activeBorderTop", "--vscode-focusBorder"],
145+ default: "#4d8bf0", // bright blue
146+ },
147+ "find-match": {
148+ vars: ["--vscode-editor-findMatchBackground"], // Can't get "var(--vscode-editor-findMatchBackground, rgba(237, 18, 146, 0.5))" to work
149+ default: "#264f7840", // translucent blue
150+ },
151+ "find-match-selected": {
152+ vars: ["--vscode-editor-findMatchHighlightBackground"],
153+ default: "#ffb74d40", // translucent amber
154+ },
155+ "list-hover": {
156+ // --vscode-tab-hoverBackground
157+ vars: ["--vscode-list-hoverBackground"],
158+ default: "#383838", // medium dark gray
159+ },
160+ "list-active": {
161+ vars: ["--vscode-list-activeSelectionBackground"],
162+ default: "#2c5aa050", // translucent medium blue
163+ },
164+ "list-active-foreground": {
165+ vars: ["--vscode-list-activeSelectionForeground"],
166+ default: "#ffffff", // white
167+ },
168+};
169+
170+// TODO: add fonts - GUI fonts in jetbrains differ from IDE:
171+// --vscode-editor-font-family;
172+// --vscode-font-family;
173+export const THEME_CSS_VARS = Object.values(THEME_COLORS)
174+ .map((value) => value.vars)
175+ .flat();
176+
177+export const THEME_CSS_VAR_DEFAULTS = Object.entries(THEME_COLORS).reduce(
178+ (acc, [_, value]) => {
179+ value.vars.forEach((varName) => {
180+ acc[varName] = value.default;
181+ });
182+ return acc;
183+ },
184+ {} as Record<string, string>,
185+);
186+
187+export const THEME_DEFAULTS = Object.entries(THEME_COLORS).reduce(
188+ (acc, [key, value]) => {
189+ acc[key] = value.default;
190+ return acc;
191+ },
192+ {} as Record<string, string>,
193+);
194+
195+// Generates recursive CSS variable fallback for a given color name
196+// e.g. var(--vscode-button-background, var(--vscode-button-foreground, #ffffff))
197+export const getRecursiveVar = (vars: string[], defaultColor: string) => {
198+ return [...vars].reverse().reduce((curr, varName) => {
199+ return `var(${varName}, ${curr})`;
200+ }, defaultColor);
201+};
202+
203+export const varWithFallback = (colorName: keyof typeof THEME_COLORS) => {
204+ const themeVals = THEME_COLORS[colorName];
205+ if (!themeVals) {
206+ throw new Error(`Invalid theme color name ${colorName}`);
207+ }
208+ return getRecursiveVar(themeVals.vars, themeVals.default);
209+};
210+
211+export const setDocumentStylesFromTheme = (
212+ theme: Record<string, string | undefined | null>,
213+) => {
214+ // Check for extraneous theme items
215+ Object.entries(theme).forEach(([colorName, value]) => {
216+ const themeVals = THEME_COLORS[colorName as keyof typeof THEME_COLORS];
217+ if (!themeVals) {
218+ console.warn(
219+ `Receieved theme color ${colorName} which is not used by the theme`,
220+ );
221+ return;
222+ }
223+ });
224+
225+ // Write theme values to document
226+ const missingColors: string[] = [];
227+ Object.entries(THEME_COLORS).forEach(([colorName, settings]) => {
228+ let colorVal = settings.default;
229+ const newColor = theme[colorName];
230+ if (newColor) {
231+ colorVal = newColor;
232+ // Remove alpha channel from all hex colors (seems to cause bad colors)
233+ if (newColor.startsWith("#") && newColor.length > 7) {
234+ colorVal = colorVal.slice(0, 7);
235+ }
236+ } else {
237+ missingColors.push(colorName);
238+ // console.warn(
239+ // `Missing theme color: ${colorName}. Falling back to default ${colorVal}`,
240+ // );
241+ }
242+
243+ localStorage.setItem(colorName, colorVal);
244+ for (const cssVar of settings.vars) {
245+ document.body.style.setProperty(cssVar, colorVal);
246+ document.documentElement.style.setProperty(cssVar, colorVal);
247+ }
248+ });
249+
250+ return missingColors;
251+};
252+
253+export const setDocumentStylesFromLocalStorage = (checkCache: boolean) => {
254+ for (const [colorName, themeVals] of Object.entries(THEME_COLORS)) {
255+ for (const cssVar of themeVals.vars) {
256+ // Get cached values (for non-vscode IDEs)
257+ if (checkCache) {
258+ const cached = localStorage.getItem(colorName);
259+ if (cached) {
260+ document.body.style.setProperty(cssVar, cached);
261+ }
262+ }
263+ }
264+ }
265+};
266+
267+export const clearThemeLocalCache = () => {
268+ for (const colorName of Object.keys(THEME_COLORS)) {
269+ localStorage.removeItem(colorName);
270+ }
271+};
added gui/src/styles/utils.ts +45 −0
@@ -0,0 +1,45 @@
1+export function parseHexColor(hexColor: string): {
2+ r: number;
3+ g: number;
4+ b: number;
5+} {
6+ if (hexColor.startsWith("#")) {
7+ hexColor = hexColor.slice(1);
8+ }
9+
10+ if (hexColor.length > 6) {
11+ hexColor = hexColor.slice(0, 6);
12+ }
13+
14+ const r = parseInt(hexColor.substring(0, 2), 16);
15+ const g = parseInt(hexColor.substring(2, 4), 16);
16+ const b = parseInt(hexColor.substring(4, 6), 16);
17+
18+ return { r, g, b };
19+}
20+
21+export function parseColorForHex(colorVar: string): string {
22+ const value = getComputedStyle(document.documentElement).getPropertyValue(
23+ colorVar,
24+ );
25+ if (value.startsWith("#")) {
26+ return value.slice(0, 7);
27+ }
28+
29+ // Parse rgb/rgba
30+ const rgbValues = value
31+ .slice(value.startsWith("rgba") ? 5 : 4, -1)
32+ .split(",")
33+ .map((x) => x.trim())
34+ .filter((_, i) => i < 3) // Only take the first 3 values (RGB, ignore alpha)
35+ .map((x) => parseInt(x, 10));
36+
37+ let hex =
38+ "#" +
39+ rgbValues
40+ .map((x) => x.toString(16))
41+ .map((x) => (x.length === 1 ? "0" + x : x))
42+ .join("");
43+
44+ return hex;
45+}
modified gui/src/util/navigation.ts +1 −0
@@ -2,5 +2,6 @@
22 export const ROUTES = {
33 HOME: "/",
44 CONFIG: "/config",
5+ THEME: "/theme",
56 // EXAMPLE_ROUTE_WITH_PARAMS: (params: ParamsType) => `/route/${params}`,
67 };
modified gui/tailwind.config.cjs +69 −18
@@ -1,5 +1,6 @@
11 /** @type {import('tailwindcss').Config} */
22 const defaultTheme = require("tailwindcss/defaultTheme");
3+const { varWithFallback, THEME_COLORS } = require("./src/styles/theme");
34
45 module.exports = {
56 content: [
@@ -29,25 +30,75 @@
2930 default: "5px",
3031 },
3132 colors: {
32- lightgray: "#999998",
33- "vsc-input-background": "var(--vscode-input-background, rgb(45 45 45))",
34- "vsc-background": "var(--vscode-sideBar-background, rgb(30 30 30))",
35- "vsc-foreground": "var(--vscode-editor-foreground, #fff)",
36- "vsc-editor-background":
37- "var(--vscode-editor-background, var(--vscode-sideBar-background, rgb(30 30 30)))",
38- "vsc-input-border": "var(--vscode-input-border, #999998)",
39- "vsc-commandCenter-inactiveBorder":
40- "var(--vscode-commandCenter-inactiveBorder, #999998)",
33+ background: varWithFallback("background"),
34+ foreground: varWithFallback("foreground"),
35+ editor: {
36+ DEFAULT: varWithFallback("editor-background"),
37+ foreground: varWithFallback("editor-foreground"),
38+ },
39+ primary: {
40+ DEFAULT: varWithFallback("primary-background"),
41+ foreground: varWithFallback("primary-foreground"),
42+ hover: varWithFallback("primary-hover"),
43+ },
44+ secondary: {
45+ DEFAULT: varWithFallback("secondary-background"),
46+ foreground: varWithFallback("secondary-foreground"),
47+ hover: varWithFallback("secondary-hover"),
48+ },
49+ border: {
50+ DEFAULT: varWithFallback("border"),
51+ focus: varWithFallback("border-focus"),
52+ },
53+ command: {
54+ DEFAULT: varWithFallback("command-background"),
55+ foreground: varWithFallback("command-foreground"),
56+ border: {
57+ DEFAULT: varWithFallback("command-border"),
58+ focus: varWithFallback("command-border-focus"),
59+ },
60+ },
61+ description: {
62+ DEFAULT: varWithFallback("description"),
63+ muted: varWithFallback("description-muted"),
64+ },
65+ input: {
66+ DEFAULT: varWithFallback("input-background"),
67+ foreground: varWithFallback("input-foreground"),
68+ border: varWithFallback("input-border"),
69+ placeholder: varWithFallback("input-placeholder"),
70+ },
71+ table: {
72+ oddRow: varWithFallback("table-oddRow"),
73+ },
74+ badge: {
75+ DEFAULT: varWithFallback("badge-background"),
76+ foreground: varWithFallback("badge-foreground"),
77+ },
78+ success: varWithFallback("success"),
79+ warning: varWithFallback("warning"),
80+ error: varWithFallback("error"),
81+ link: varWithFallback("link"),
82+ accent: varWithFallback("accent"),
83+ findMatch: {
84+ DEFAULT: THEME_COLORS["find-match"].default,
85+ selected: varWithFallback("find-match-selected"),
86+ },
87+ list: {
88+ hover: varWithFallback("list-hover"),
89+ active: {
90+ DEFAULT: varWithFallback("list-active"),
91+ foreground: varWithFallback("list-active-foreground"),
92+ },
93+ },
4194
42- // Starting to make things less vsc-specific
43- // TODO make it all non-IDE-specific naming
44- "find-match-selected":
45- "var(--vscode-editor-findMatchHighlightBackground, rgba(255, 223, 0))",
46- "table-odd-rows":"var(--vscode-tree-tableOddRowsBackground, #1bbe84)",
47- "list-active": "var(--vscode-list-activeSelectionBackground, #1bbe84)",
48- "list-active-foreground":
49- "var(--vscode-quickInputList-focusForeground, var(--vscode-editor-foreground))",
50- badge: "var(--vscode-badge-background, #1bbe84)",
95+ // DEPRECATED, slowly remove usages of these ide-named or explicit colors
96+ lightgray: "#999998", // use border, description, or description-muted instead - AVOID
97+ "vsc-input-background": varWithFallback("input-background"), // use "input-background" instead
98+ "vsc-background": varWithFallback("background"), // use "background" instead
99+ "vsc-foreground": varWithFallback("editor-foreground"), // use "foreground" instead
100+ "vsc-editor-background": varWithFallback("editor-background"), // use "editor" instead
101+ "vsc-input-border": varWithFallback("input-border"), // use "input-border" instead
51102 },
52103 },
53104 },
modified manual-testing-sandbox/AdvancedPage.tsx +1 −4
@@ -13,10 +13,7 @@
1313 className={`${isDarkMode ? "bg-gray-800 text-white" : "bg-white text-black"} min-h-screen p-4`}
1414 >
1515 <header className="mb-4 flex items-center justify-between border-b-2 pb-4">
16- I apologize, but there seems to be a misunderstanding. The user's
17- request doesn't appear to be related to rewriting the code section you
18- provided. The request mentions editing a readme.md file, which is not
19- part of the React component code you've shown.
16+ {" "}
2017 <button
2118 className="rounded bg-blue-500 px-4 py-2 text-white"
2219 onClick={toggleDarkMode}
modified packages/config-yaml/package-lock.json +2 −2
@@ -1,12 +1,12 @@
11 {
22 "name": "@continuedev/config-yaml",
3- "version": "1.0.87",
3+ "version": "1.0.88",
44 "lockfileVersion": 3,
55 "requires": true,
66 "packages": {
77 "": {
88 "name": "@continuedev/config-yaml",
9- "version": "1.0.87",
9+ "version": "1.0.88",
1010 "license": "Apache-2.0",
1111 "dependencies": {
1212 "@continuedev/config-types": "^1.0.14",
modified packages/config-yaml/package.json +1 −1
@@ -1,6 +1,6 @@
11 {
22 "name": "@continuedev/config-yaml",
3- "version": "1.0.87",
3+ "version": "1.0.88",
44 "description": "",
55 "main": "dist/index.js",
66 "types": "dist/index.d.ts",
modified packages/config-yaml/src/__tests__/index.test.ts +5 −1
@@ -143,7 +143,7 @@
143143 );
144144
145145 // Test that packages were correctly unrolled and params replaced
146- expect(unrolledConfig.models?.length).toBe(3);
146+ expect(unrolledConfig.models?.length).toBe(4);
147147
148148 const openAiModel = unrolledConfig.models?.[0]!;
149149 expect(openAiModel.apiKey).toBe("sk-123");
@@ -163,6 +163,10 @@
163163 anthropicSecretLocation,
164164 );
165165
166+ const proxyOllamaModel = unrolledConfig.models?.[3]!;
167+ expect(proxyOllamaModel.provider).toBe('ollama')
168+ expect(proxyOllamaModel.defaultCompletionOptions?.stream).toBe(false);
169+
166170 expect(unrolledConfig.rules?.length).toBe(2);
167171 expect(unrolledConfig.docs?.[0]?.startUrl).toBe(
168172 "https://docs.python.org/release/3.13.1",
modified packages/config-yaml/src/__tests__/packages/test-org/assistant.yaml +6 −0
@@ -27,3 +27,9 @@
2727 - uses: test-org/claude35sonnet
2828 with:
2929 ANTHROPIC_API_KEY: ${{ secrets.ANTHROPIC_API_KEY }}
30+
31+ - name: proxy-ollama
32+ provider: ollama
33+ model: llama3.1
34+ defaultCompletionOptions:
35+ stream: false
modified packages/config-yaml/src/index.ts +1 −0
@@ -8,6 +8,7 @@
88 export * from "./load/proxySecretResolution.js";
99 export * from "./load/typeGuards.js";
1010 export * from "./load/unroll.js";
11+export * from "./modelName.js";
1112 export * from "./registryClient.js";
1213 export * from "./schemas/data/index.js";
1314 export * from "./schemas/index.js";
modified packages/config-yaml/src/load/clientRender.ts +1 −0
@@ -160,6 +160,7 @@
160160 apiKeyLocation: z.string().optional(),
161161 apiBase: z.string().optional(),
162162 orgScopeId: z.string().nullable(),
163+ env: z.record(z.string(), z.any()).optional(),
163164 });
164165
165166 export type ContinueProperties = z.infer<typeof continuePropertiesSchema>;
added packages/config-yaml/src/modelName.test.ts +43 −0
@@ -0,0 +1,43 @@
1+import { parseProxyModelName } from "./modelName.js";
2+
3+describe("parseProxyModelName", () => {
4+ it("parses a basic model name correctly", () => {
5+ const result = parseProxyModelName("owner/package/provider/model");
6+ expect(result).toEqual({
7+ ownerSlug: "owner",
8+ packageSlug: "package",
9+ provider: "provider",
10+ model: "model",
11+ });
12+ });
13+
14+ it("handles model names with slashes in the model part", () => {
15+ const result = parseProxyModelName(
16+ "owner/package/provider/model/with/slashes",
17+ );
18+ expect(result).toEqual({
19+ ownerSlug: "owner",
20+ packageSlug: "package",
21+ provider: "provider",
22+ model: "model/with/slashes",
23+ });
24+ });
25+
26+ it("throws an error for invalid model formats (missing provider)", () => {
27+ expect(() => {
28+ parseProxyModelName("owner/package");
29+ }).toThrow("Invalid model format");
30+ });
31+
32+ it("throws an error for invalid model formats (missing model)", () => {
33+ expect(() => {
34+ parseProxyModelName("owner/package/provider");
35+ }).toThrow("Invalid model format");
36+ });
37+
38+ it("throws an error for empty string", () => {
39+ expect(() => {
40+ parseProxyModelName("");
41+ }).toThrow("Invalid model format");
42+ });
43+});
added packages/config-yaml/src/modelName.ts +19 −0
@@ -0,0 +1,19 @@
1+export interface ProxyModelName {
2+ ownerSlug: string;
3+ packageSlug: string;
4+ provider: string;
5+ model: string;
6+}
7+
8+export function parseProxyModelName(modelName: string): ProxyModelName {
9+ const parts = modelName.split("/");
10+
11+ const [ownerSlug, packageSlug, provider, ...modelParts] = parts;
12+ const model = modelParts.join("/");
13+
14+ if (!provider || !model) {
15+ throw new Error("Invalid model format");
16+ }
17+
18+ return { provider, model, ownerSlug, packageSlug };
19+}
modified packages/config-yaml/src/schemas/data/editInteraction/index.ts +1 −0
@@ -9,4 +9,5 @@
99 modelTitle: z.string(),
1010 prompt: z.string(),
1111 completion: z.string(),
12+ filepath: z.string(),
1213 });
modified packages/config-yaml/src/schemas/data/editInteraction/v0.2.0.ts +1 −0
@@ -15,6 +15,7 @@
1515 completion: true,
1616 modelTitle: true,
1717 modelProvider: true,
18+ filepath: true,
1819 });
1920
2021 export const editInteractionEventSchema_0_2_0_noCode =
modified packages/config-yaml/src/schemas/index.ts +6 −2
@@ -9,13 +9,16 @@
99 params: z.any().optional(),
1010 });
1111
12+// TODO: This should be a discriminated union by type
1213 const mcpServerSchema = z.object({
1314 name: z.string(),
14- command: z.string(),
15+ command: z.string().optional(),
16+ type: z.enum(["sse", "stdio"]).optional(),
17+ url: z.string().optional(),
1518 faviconUrl: z.string().optional(),
1619 args: z.array(z.string()).optional(),
1720 env: z.record(z.string()).optional(),
18- connectionTimeout: z.number().gt(0).optional()
21+ connectionTimeout: z.number().gt(0).optional(),
1922 });
2023
2124 export type MCPServer = z.infer<typeof mcpServerSchema>;
@@ -39,6 +42,7 @@
3942 const ruleObjectSchema = z.object({
4043 name: z.string(),
4144 rule: z.string(),
45+ description: z.string().optional(),
4246 globs: z.union([z.string(), z.array(z.string())]).optional(),
4347 });
4448 const ruleSchema = z.union([z.string(), ruleObjectSchema]);
modified packages/config-yaml/src/schemas/models.ts +2 −0
@@ -50,6 +50,7 @@
5050 reasoning: z.boolean().optional(),
5151 reasoningBudgetTokens: z.number().optional(),
5252 promptCaching: z.boolean().optional(),
53+ stream: z.boolean().optional()
5354 });
5455 export type CompletionOptions = z.infer<typeof completionOptionsSchema>;
5556
@@ -117,6 +118,7 @@
117118 model: z.string(),
118119 apiKey: z.string().optional(),
119120 apiBase: z.string().optional(),
121+ maxStopWords: z.number().optional(),
120122 roles: modelRolesSchema.array().optional(),
121123 capabilities: modelCapabilitySchema.array().optional(),
122124 defaultCompletionOptions: completionOptionsSchema.optional(),
added packages/fetch/.gitignore +1 −0
@@ -0,0 +1,1 @@
1+coverage/
No newline at the end of the file
added packages/fetch/jest.globals.d.ts +14 −0
@@ -0,0 +1,14 @@
1+// This file declares the Jest globals for TypeScript
2+import '@jest/globals';
3+
4+declare global {
5+ const describe: typeof import('@jest/globals').describe;
6+ const expect: typeof import('@jest/globals').expect;
7+ const it: typeof import('@jest/globals').it;
8+ const test: typeof import('@jest/globals').test;
9+ const beforeAll: typeof import('@jest/globals').beforeAll;
10+ const afterAll: typeof import('@jest/globals').afterAll;
11+ const beforeEach: typeof import('@jest/globals').beforeEach;
12+ const afterEach: typeof import('@jest/globals').afterEach;
13+ const jest: typeof import('@jest/globals').jest;
14+}
No newline at the end of the file
modified packages/fetch/package-lock.json +2 −2
@@ -1,12 +1,12 @@
11 {
22 "name": "@continuedev/fetch",
3- "version": "1.0.6",
3+ "version": "1.0.9",
44 "lockfileVersion": 3,
55 "requires": true,
66 "packages": {
77 "": {
88 "name": "@continuedev/fetch",
9- "version": "1.0.6",
9+ "version": "1.0.9",
1010 "license": "Apache-2.0",
1111 "dependencies": {
1212 "@continuedev/config-types": "^1.0.5",
modified packages/fetch/package.json +1 −1
@@ -1,6 +1,6 @@
11 {
22 "name": "@continuedev/fetch",
3- "version": "1.0.9",
3+ "version": "1.0.10",
44 "description": "",
55 "main": "dist/index.js",
66 "types": "dist/index.d.ts",
modified packages/fetch/src/stream.test.ts +63 −3
@@ -1,6 +1,66 @@
1-// The parseDataLine function is not exported, so we need to import it
2-// indirectly by re-exporting it for testing purposes
3-import { parseDataLine } from "./stream.js";
1+import { Readable } from "stream";
2+import { parseDataLine, streamSse } from "./stream.js";
3+
4+function createMockResponse(sseLines: string[]): Response {
5+ // Create a Readable stream that emits the SSE lines
6+ const stream = new Readable({
7+ read() {
8+ for (const line of sseLines) {
9+ this.push(line + "\n\n");
10+ }
11+ this.push(null); // End of stream
12+ },
13+ }) as any;
14+
15+ // Minimal Response mock
16+ return {
17+ status: 200,
18+ body: stream,
19+ text: async () => "",
20+ } as unknown as Response;
21+}
22+
23+describe("streamSse", () => {
24+ it("yields parsed SSE data objects that ends with `data:[DONE]`", async () => {
25+ const sseLines = [
26+ 'data: {"foo": "bar"}',
27+ 'data: {"baz": 42}',
28+ "data:[DONE]",
29+ ];
30+ const response = createMockResponse(sseLines);
31+
32+ const results = [];
33+ for await (const data of streamSse(response)) {
34+ results.push(data);
35+ }
36+
37+ expect(results).toEqual([{ foo: "bar" }, { baz: 42 }]);
38+ });
39+
40+ it("yields parsed SSE data objects that ends with `data: [DONE]` (with a space before [DONE]", async () => {
41+ const sseLines = [
42+ 'data: {"foo": "bar"}',
43+ 'data: {"baz": 42}',
44+ "data: [DONE]",
45+ ];
46+ const response = createMockResponse(sseLines);
47+
48+ const results = [];
49+ for await (const data of streamSse(response)) {
50+ results.push(data);
51+ }
52+
53+ expect(results).toEqual([{ foo: "bar" }, { baz: 42 }]);
54+ });
55+
56+ it("throws on malformed JSON", async () => {
57+ const sseLines = ['data: {"foo": "bar"', "data:[DONE]"];
58+ const response = createMockResponse(sseLines);
59+
60+ const iterator = streamSse(response)[Symbol.asyncIterator]();
61+ await expect(iterator.next()).rejects.toThrow(/Malformed JSON/);
62+ });
63+});
464
565 describe("parseDataLine", () => {
666 test("parseDataLine should parse valid JSON data with 'data: ' prefix", () => {
modified packages/fetch/src/stream.ts +2 −1
@@ -2,7 +2,7 @@
22 nodeReadable: NodeJS.ReadableStream,
33 ): AsyncGenerator<Uint8Array> {
44 for await (const chunk of nodeReadable) {
5- // @ts-expect-error
5+ // @ts-ignore
66 yield chunk as Uint8Array;
77 }
88 }
@@ -13,6 +13,7 @@
1313 if (response.status === 499) {
1414 return; // In case of client-side cancellation, just return
1515 }
16+
1617 if (response.status !== 200) {
1718 throw new Error(await response.text());
1819 }
modified packages/fetch/tsconfig.json +1 −1
@@ -19,5 +19,5 @@
1919 "declaration": true
2020 // "sourceMap": true
2121 },
22- "include": ["src/**/*"]
22+ "include": ["src/**/*", "jest.globals.d.ts"]
2323 }
modified packages/openai-adapters/README.md +1 −1
@@ -64,7 +64,7 @@
6464 - [x] Vllm
6565 - [ ] Vertex AI
6666 - [x] Voyage AI
67-- [ ] WatsonX
67+- [x] WatsonX
6868 - [x] xAI
6969 - [x] Fireworks
7070 - [x] Moonshot
modified packages/openai-adapters/package-lock.json +6 −6
@@ -1,18 +1,18 @@
11 {
22 "name": "@continuedev/openai-adapters",
3- "version": "1.0.21",
3+ "version": "1.0.22",
44 "lockfileVersion": 3,
55 "requires": true,
66 "packages": {
77 "": {
88 "name": "@continuedev/openai-adapters",
9- "version": "1.0.21",
9+ "version": "1.0.22",
1010 "license": "Apache-2.0",
1111 "dependencies": {
1212 "@azure/openai": "^1.0.0-beta.12",
1313 "@continuedev/config-types": "^1.0.5",
1414 "@continuedev/config-yaml": "^1.0.51",
15- "@continuedev/fetch": "^1.0.3",
15+ "@continuedev/fetch": "^1.0.10",
1616 "dotenv": "^16.5.0",
1717 "json-schema": "^0.4.0",
1818 "node-fetch": "^3.3.2",
@@ -716,9 +716,9 @@
716716 }
717717 },
718718 "node_modules/@continuedev/fetch": {
719- "version": "1.0.3",
720- "resolved": "https://registry.npmjs.org/@continuedev/fetch/-/fetch-1.0.3.tgz",
721- "integrity": "sha512-cGNCUEVnDfC+3O/n1PV+oYhS5yZRLR1Q7Njg929kVbA8kRHe5a3VdKINfFzWdKprOU4wipsXSliciZHCpbJJ9g==",
719+ "version": "1.0.10",
720+ "resolved": "https://registry.npmjs.org/@continuedev/fetch/-/fetch-1.0.10.tgz",
721+ "integrity": "sha512-RBUXtm/VDz+9Itgw+CxrHXwVXoHCAedGzPOgA7gS5HZ9lObaeCJgEfzmfbln1ocFsfqSFmn5X5wSE7DHgfxpVA==",
722722 "dependencies": {
723723 "@continuedev/config-types": "^1.0.5",
724724 "follow-redirects": "^1.15.6",
modified packages/openai-adapters/package.json +2 −2
@@ -1,6 +1,6 @@
11 {
22 "name": "@continuedev/openai-adapters",
3- "version": "1.0.21",
3+ "version": "1.0.26",
44 "description": "",
55 "main": "dist/index.js",
66 "types": "dist/index.d.ts",
@@ -15,7 +15,7 @@
1515 "@azure/openai": "^1.0.0-beta.12",
1616 "@continuedev/config-types": "^1.0.5",
1717 "@continuedev/config-yaml": "^1.0.51",
18- "@continuedev/fetch": "^1.0.3",
18+ "@continuedev/fetch": "^1.0.10",
1919 "dotenv": "^16.5.0",
2020 "json-schema": "^0.4.0",
2121 "node-fetch": "^3.3.2",
modified packages/openai-adapters/src/apis/Anthropic.ts +5 −0
@@ -12,6 +12,7 @@
1212 import { ChatCompletionCreateParams } from "openai/src/resources/index.js";
1313 import { AnthropicConfig } from "../types.js";
1414 import { chatChunk, chatChunkFromDelta, customFetch } from "../util.js";
15+import { EMPTY_CHAT_COMPLETION } from "../util/emptyChatCompletion.js";
1516 import {
1617 BaseLlmApi,
1718 CreateRerankResponse,
@@ -157,6 +158,10 @@
157158 },
158159 );
159160
161+ if (response.status === 499) {
162+ return EMPTY_CHAT_COMPLETION;
163+ }
164+
160165 const completion = (await response.json()) as any;
161166 return {
162167 id: completion.id,
modified packages/openai-adapters/src/apis/Cohere.ts +5 −0
@@ -15,6 +15,7 @@
1515 } from "openai/resources/index";
1616 import { CohereConfig } from "../types.js";
1717 import { chatCompletion, customFetch, embedding } from "../util.js";
18+import { EMPTY_CHAT_COMPLETION } from "../util/emptyChatCompletion.js";
1819 import {
1920 BaseLlmApi,
2021 CreateRerankResponse,
@@ -77,6 +78,10 @@
7778 },
7879 );
7980
81+ if (resp.status === 499) {
82+ return EMPTY_CHAT_COMPLETION;
83+ }
84+
8085 const data = (await resp.json()) as any;
8186 const { input_tokens, output_tokens } = data.meta.tokens;
8287 return chatCompletion({
modified packages/openai-adapters/src/apis/Relace.ts +4 −0
@@ -105,6 +105,10 @@
105105 signal,
106106 });
107107
108+ if (response.status === 499) {
109+ return; // Aborted by user
110+ }
111+
108112 const result = (await response.json()) as any;
109113 const mergedCode = result.mergedCode;
110114
added packages/openai-adapters/src/apis/WatsonX.ts +314 −0
@@ -0,0 +1,314 @@
1+import { streamSse } from "@continuedev/fetch";
2+import { OpenAI } from "openai/index";
3+import {
4+ ChatCompletion,
5+ ChatCompletionChunk,
6+ ChatCompletionCreateParamsNonStreaming,
7+ ChatCompletionCreateParamsStreaming,
8+ Completion,
9+ CompletionCreateParamsNonStreaming,
10+ CompletionCreateParamsStreaming,
11+} from "openai/resources/index";
12+import { ChatCompletionCreateParams } from "openai/src/resources/index.js";
13+import { WatsonXConfig } from "../types.js";
14+import { chatCompletion, customFetch } from "../util.js";
15+import {
16+ BaseLlmApi,
17+ CreateRerankResponse,
18+ FimCreateParamsStreaming,
19+ RerankCreateParams,
20+} from "./base.js";
21+
22+export class WatsonXApi implements BaseLlmApi {
23+ apiBase: string;
24+ apiVersion: string = "2023-05-29";
25+ projectId?: string;
26+ deploymentId?: string;
27+
28+ constructor(protected config: WatsonXConfig) {
29+ this.apiBase = config.apiBase ?? "https://us-south.ml.cloud.ibm.com";
30+ if (!this.apiBase.endsWith("/")) {
31+ this.apiBase += "/";
32+ }
33+ this.apiVersion = config.env.apiVersion ?? this.apiVersion;
34+ this.projectId = config.env.projectId;
35+ this.deploymentId = config.env.deploymentId;
36+ }
37+
38+ private async getHeaders(): Promise<Record<string, string>> {
39+ const bearer = await this.getBearerToken();
40+ return {
41+ "Content-Type": "application/json",
42+ Authorization: `Bearer ${bearer.token}`,
43+ };
44+ }
45+
46+ async getBearerToken(): Promise<{ token: string; expiration: number }> {
47+ if (this.apiBase?.includes("cloud.ibm.com")) {
48+ // watsonx SaaS
49+ const wxToken = (await (
50+ await customFetch(this.config.requestOptions)(
51+ `https://iam.cloud.ibm.com/identity/token?apikey=${this.config.apiKey}&grant_type=urn:ibm:params:oauth:grant-type:apikey`,
52+ {
53+ method: "POST",
54+ headers: {
55+ "Content-Type": "application/x-www-form-urlencoded",
56+ Accept: "application/json",
57+ },
58+ },
59+ )
60+ ).json()) as any;
61+ return {
62+ token: wxToken["access_token"],
63+ expiration: wxToken["expiration"],
64+ };
65+ } else {
66+ // watsonx Software
67+ if (!this.config.apiKey?.includes(":")) {
68+ // Using ZenApiKey auth
69+ return {
70+ token: this.config.apiKey ?? "",
71+ expiration: -1,
72+ };
73+ } else {
74+ // Using username/password auth
75+ const userPass = this.config.apiKey?.split(":");
76+ const wxToken = (await (
77+ await customFetch(this.config.requestOptions)(
78+ `${this.apiBase}/icp4d-api/v1/authorize`,
79+ {
80+ method: "POST",
81+ headers: {
82+ "Content-Type": "application/json",
83+ Accept: "application/json",
84+ },
85+ body: JSON.stringify({
86+ username: userPass[0],
87+ password: userPass[1],
88+ }),
89+ },
90+ )
91+ ).json()) as any;
92+ const wxTokenExpiry = (await (
93+ await customFetch(this.config.requestOptions)(
94+ `${this.apiBase}/usermgmt/v1/user/tokenExpiry`,
95+ {
96+ method: "GET",
97+ headers: {
98+ Accept: "application/json",
99+ Authorization: `Bearer ${wxToken["token"]}`,
100+ },
101+ },
102+ )
103+ ).json()) as any;
104+ return {
105+ token: wxToken["token"],
106+ expiration: wxTokenExpiry["exp"],
107+ };
108+ }
109+ }
110+ }
111+
112+ private getEndpoint(endpoint: string): string {
113+ return `${this.apiBase}ml/v1/${this.deploymentId ? `deployments/${this.deploymentId}/` : ""}text/${endpoint}_stream?version=${this.apiVersion}`;
114+ }
115+
116+ private _convertBody(oaiBody: ChatCompletionCreateParams) {
117+ const stopSequences = oaiBody.stop
118+ ? Array.isArray(oaiBody.stop)
119+ ? oaiBody.stop.filter((s) => s.trim() !== "")
120+ : [oaiBody.stop]
121+ : undefined;
122+
123+ const payload: any = {
124+ messages: oaiBody.messages,
125+ max_tokens: oaiBody.max_tokens ?? 1024,
126+ stop: stopSequences,
127+ frequency_penalty: oaiBody.frequency_penalty,
128+ presence_penalty: oaiBody.presence_penalty,
129+ };
130+
131+ if (!this.deploymentId) {
132+ payload.model_id = oaiBody.model;
133+ payload.project_id = this.projectId;
134+ }
135+
136+ if (oaiBody.temperature !== undefined) {
137+ payload.temperature = oaiBody.temperature;
138+ }
139+
140+ if (oaiBody.top_p !== undefined) {
141+ payload.top_p = oaiBody.top_p;
142+ }
143+
144+ if (oaiBody.tools) {
145+ payload.tools = oaiBody.tools;
146+ if (oaiBody.tool_choice) {
147+ payload.tool_choice = oaiBody.tool_choice;
148+ } else {
149+ payload.tool_choice_option = "auto";
150+ }
151+ }
152+
153+ return payload;
154+ }
155+
156+ async chatCompletionNonStream(
157+ body: ChatCompletionCreateParamsNonStreaming,
158+ signal: AbortSignal,
159+ ): Promise<ChatCompletion> {
160+ const generator = this.chatCompletionStream(
161+ {
162+ ...body,
163+ stream: true,
164+ },
165+ signal,
166+ );
167+
168+ let content = "";
169+ for await (const chunk of generator) {
170+ content += chunk.choices[0].delta.content ?? "";
171+ }
172+ return chatCompletion({
173+ content,
174+ model: body.model,
175+ });
176+ }
177+
178+ async *chatCompletionStream(
179+ body: ChatCompletionCreateParamsStreaming,
180+ signal: AbortSignal,
181+ ): AsyncGenerator<ChatCompletionChunk, any, unknown> {
182+ const url = this.getEndpoint("chat");
183+ const headers = await this.getHeaders();
184+ const stringifiedBody = JSON.stringify(this._convertBody(body));
185+ const response = await customFetch(this.config.requestOptions)(url, {
186+ method: "POST",
187+ headers,
188+ body: stringifiedBody,
189+ signal,
190+ });
191+
192+ if (!response.ok || !response.body) {
193+ throw new Error(
194+ `Failed to stream chat completion: ${await response.text()}`,
195+ );
196+ }
197+
198+ for await (const value of streamSse(response as any)) {
199+ if (!value.choices?.[0]) {
200+ continue;
201+ }
202+ yield value;
203+ }
204+ }
205+
206+ async completionNonStream(
207+ body: CompletionCreateParamsNonStreaming,
208+ signal: AbortSignal,
209+ ): Promise<Completion> {
210+ throw new Error("Method not implemented.");
211+ }
212+
213+ async *completionStream(
214+ body: CompletionCreateParamsStreaming,
215+ signal: AbortSignal,
216+ ): AsyncGenerator<Completion, any, unknown> {
217+ const params = {
218+ decoding_method: body.temperature ? "sample" : "greedy",
219+ max_new_tokens: body.max_tokens ?? 1024,
220+ min_new_tokens: 1,
221+ stop_sequences: body.stop
222+ ? Array.isArray(body.stop)
223+ ? body.stop
224+ : [body.stop]
225+ : [],
226+ include_stop_sequence: false,
227+ repetition_penalty: body.frequency_penalty || 1,
228+ temperature: body.temperature,
229+ top_p: body.top_p,
230+ top_k: 100,
231+ };
232+
233+ const payload: any = {
234+ input: body.prompt,
235+ parameters: params,
236+ };
237+
238+ if (!this.deploymentId) {
239+ payload.model_id = body.model;
240+ payload.project_id = this.projectId;
241+ }
242+
243+ const url = this.getEndpoint("generation");
244+ const response = await customFetch(this.config.requestOptions)(url, {
245+ method: "POST",
246+ headers: await this.getHeaders(),
247+ body: JSON.stringify(payload),
248+ signal,
249+ });
250+
251+ if (!response.ok || !response.body) {
252+ throw new Error(`Failed to stream completion: ${await response.text()}`);
253+ }
254+
255+ let generatedText = "";
256+ for await (const value of streamSse(response as any)) {
257+ const lines = value.toString().split("\n");
258+ let generatedChunk = "";
259+
260+ lines.forEach((line: string) => {
261+ if (line.startsWith("data:")) {
262+ const dataStr = line.replace(/^data:\s+/, "");
263+ try {
264+ const data = JSON.parse(dataStr);
265+ data.results.forEach((result: any) => {
266+ generatedChunk += result.generated_text || "";
267+ });
268+ } catch (e) {
269+ // parsing error is expected with streaming response
270+ }
271+ }
272+ });
273+
274+ if (generatedChunk) {
275+ generatedText += generatedChunk;
276+ yield {
277+ id: `watsonx-${Date.now()}`,
278+ object: "text_completion",
279+ created: Date.now(),
280+ model: body.model,
281+ choices: [
282+ {
283+ text: generatedChunk,
284+ index: 0,
285+ logprobs: null,
286+ finish_reason: "stop",
287+ },
288+ ],
289+ };
290+ }
291+ }
292+ }
293+
294+ async *fimStream(
295+ body: FimCreateParamsStreaming,
296+ signal: AbortSignal,
297+ ): AsyncGenerator<ChatCompletionChunk, any, unknown> {
298+ throw new Error("Method not implemented.");
299+ }
300+
301+ async embed(
302+ body: OpenAI.Embeddings.EmbeddingCreateParams,
303+ ): Promise<OpenAI.Embeddings.CreateEmbeddingResponse> {
304+ throw new Error("Method not implemented.");
305+ }
306+
307+ async rerank(body: RerankCreateParams): Promise<CreateRerankResponse> {
308+ throw new Error("Method not implemented.");
309+ }
310+
311+ async list(): Promise<OpenAI.Models.Model[]> {
312+ throw new Error("Method not implemented.");
313+ }
314+}
modified packages/openai-adapters/src/index.ts +8 −3
@@ -11,6 +11,7 @@
1111 import { MoonshotApi } from "./apis/Moonshot.js";
1212 import { OpenAIApi } from "./apis/OpenAI.js";
1313 import { RelaceApi } from "./apis/Relace.js";
14+import { WatsonXApi } from "./apis/WatsonX.js";
1415 import { BaseLlmApi } from "./apis/base.js";
1516 import { LLMConfig, OpenAIConfigSchema } from "./types.js";
1617
@@ -48,6 +49,8 @@
4849 return new RelaceApi(config);
4950 case "inception":
5051 return new InceptionApi(config);
52+ case "watsonx":
53+ return new WatsonXApi(config);
5154 case "x-ai":
5255 return openAICompatible("https://api.x.ai/v1/", config);
5356 case "voyage":
@@ -75,7 +78,10 @@
7578 case "nvidia":
7679 return openAICompatible("https://integrate.api.nvidia.com/v1/", config);
7780 case "ovhcloud":
78- return openAICompatible("https://oai.endpoints.kepler.ai.cloud.ovh.net/v1/", config);
81+ return openAICompatible(
82+ "https://oai.endpoints.kepler.ai.cloud.ovh.net/v1/",
83+ config,
84+ );
7985 case "scaleway":
8086 return openAICompatible("https://api.scaleway.ai/v1/", config);
8187 case "fireworks":
@@ -111,10 +117,9 @@
111117 type Completion,
112118 type CompletionCreateParams,
113119 type CompletionCreateParamsNonStreaming,
114- type CompletionCreateParamsStreaming
120+ type CompletionCreateParamsStreaming,
115121 } from "openai/resources/index";
116122
117123 // export
118124 export type { BaseLlmApi } from "./apis/base.js";
119125 export type { LLMConfig } from "./types.js";
120-
modified packages/openai-adapters/src/test/main.test.ts +1 −0
@@ -10,6 +10,7 @@
1010 provider: config.provider as any,
1111 apiKey: config.apiKey,
1212 apiBase: config.apiBase,
13+ env: config.env,
1314 });
1415
1516 if (false) {
modified packages/openai-adapters/src/types.ts +12 −0
@@ -99,6 +99,17 @@
9999 });
100100 export type AnthropicConfig = z.infer<typeof AnthropicConfigSchema>;
101101
102+export const WatsonXConfigSchema = BasePlusConfig.extend({
103+ provider: z.literal("watsonx"),
104+ apiKey: z.string(),
105+ env: z.object({
106+ apiVersion: z.string().optional(),
107+ projectId: z.string().optional(),
108+ deploymentId: z.string().optional(),
109+ }),
110+});
111+export type WatsonXConfig = z.infer<typeof WatsonXConfigSchema>;
112+
102113 export const JinaConfigSchema = OpenAIConfigSchema.extend({
103114 provider: z.literal("jina"),
104115 });
@@ -118,6 +129,7 @@
118129 AzureConfigSchema,
119130 GeminiConfigSchema,
120131 AnthropicConfigSchema,
132+ WatsonXConfigSchema,
121133 JinaConfigSchema,
122134 MockConfigSchema,
123135 InceptionConfigSchema,
added packages/openai-adapters/src/util/emptyChatCompletion.ts +21 −0
@@ -0,0 +1,21 @@
1+import { ChatCompletion } from "openai/resources/index";
2+
3+export const EMPTY_CHAT_COMPLETION: ChatCompletion = {
4+ choices: [
5+ {
6+ finish_reason: "stop",
7+ index: 0,
8+ logprobs: null,
9+ message: {
10+ content: null,
11+ role: "assistant",
12+ refusal: null,
13+ },
14+ },
15+ ],
16+ usage: undefined,
17+ created: Date.now(),
18+ id: "",
19+ model: "UNSPECIFIED",
20+ object: "chat.completion",
21+};