Elffuss BraidHub

kikocis/continue public

Merge branch 'main' into nate/vllm-no-fim
Changeset1db4eaf4c0a710b4b1caf8ea8214e10ab229b569a6c0bde59e9c300360208380
AuthorNate <sestinj@gmail.com> · 2025-05-25 21:48 -07:00
CommitterNate <sestinj@gmail.com> · 2025-05-25 21:48 -07:00
Parents04a1ed437233, fa514d4463b9

Browse the files at this changeset

111 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/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/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/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 +2 −1
@@ -424,7 +424,7 @@
424424 completion: string;
425425 }
426426
427-export type MessageModes = "chat" | "edit" | "agent";
427+export type MessageModes = "chat" | "agent";
428428
429429 export type ToolStatus =
430430 | "generating"
@@ -1242,6 +1242,7 @@
12421242 language: string | undefined;
12431243 modelTitle: string | undefined;
12441244 includeRulesInSystemMessage: boolean;
1245+ fileUri?: string;
12451246 }
12461247
12471248 export interface HighlightedCodePayload {
modified core/llm/index.ts +3 −0
@@ -390,6 +390,9 @@
390390
391391 // Error mapping to be more helpful
392392 if (!resp.ok) {
393+ if (resp.status === 499) {
394+ return resp; // client side cancellation
395+ }
393396 let text = await resp.text();
394397 if (resp.status === 404 && !resp.url.includes("/v1")) {
395398 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/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/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 }
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.ts +11 −3
@@ -111,6 +111,7 @@
111111 "pixtral",
112112 "ministral",
113113 "mistral-nemo",
114+ "devstral",
114115 ].some((part) => model.toLowerCase().includes(part))
115116 );
116117 },
@@ -185,9 +186,14 @@
185186 return false;
186187 }
187188 if (
188- ["llama-3", "llama-4", "mistral", "codestral", "granite-3"].some(
189- (part) => model.toLowerCase().includes(part),
190- )
189+ [
190+ "llama-3",
191+ "llama-4",
192+ "mistral",
193+ "codestral",
194+ "granite-3",
195+ "devstral",
196+ ].some((part) => model.toLowerCase().includes(part))
191197 ) {
192198 return true;
193199 }
@@ -211,6 +217,7 @@
211217 "openai/o3",
212218 "openai/o4",
213219 "anthropic/claude-3",
220+ "anthropic/claude-4",
214221 "microsoft/phi-3",
215222 "google/gemini-flash-1.5",
216223 "google/gemini-2",
@@ -225,6 +232,7 @@
225232 "mistralai/codestral",
226233 "mistralai/mixtral",
227234 "mistral/ministral",
235+ "mistral/devstral",
228236 "mistralai/pixtral",
229237 "meta-llama/llama-3.3",
230238 "amazon/nova",
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 +2 −2
@@ -49,9 +49,9 @@
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",
54+ "@continuedev/openai-adapters": "^1.0.25",
5555 "@modelcontextprotocol/sdk": "^1.5.0",
5656 "@mozilla/readability": "^0.5.0",
5757 "@octokit/rest": "^20.1.1",
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[]];
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 +1 −0
@@ -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 [
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/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 +1 −1
@@ -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 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/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";
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/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/hooks/ParallelListeners.tsx +46 −34
@@ -3,6 +3,7 @@
33
44 import { EDIT_MODE_STREAM_ID } from "core/edit/constants";
55 import { FromCoreProtocol } from "core/protocol";
6+import { useMainEditor } from "../components/mainInput/TipTapEditor";
67 import {
78 initializeProfilePreferences,
89 setOrganizations,
@@ -15,7 +16,7 @@
1516 import {
1617 setLastNonEditSessionEmpty,
1718 updateEditStateApplyState,
18-} from "../redux/slices/editModeState";
19+} from "../redux/slices/editState";
1920 import { updateIndexingStatus } from "../redux/slices/indexingSlice";
2021 import {
2122 acceptToolCall,
@@ -23,7 +24,7 @@
2324 updateApplyState,
2425 } from "../redux/slices/sessionSlice";
2526 import { setTTSActive } from "../redux/slices/uiSlice";
26-import { streamResponseAfterToolCall } from "../redux/thunks";
27+import { exitEdit, streamResponseAfterToolCall } from "../redux/thunks";
2728 import { cancelStream } from "../redux/thunks/cancelStream";
2829 import { refreshSessionMetadata } from "../redux/thunks/session";
2930 import { streamResponseThunk } from "../redux/thunks/streamResponse";
@@ -40,12 +41,18 @@
4041 const dispatch = useAppDispatch();
4142 const ideMessenger = useContext(IdeMessengerContext);
4243 const history = useAppSelector((store) => store.session.history);
44+ const isInEdit = useAppSelector((store) => store.session.isInEdit);
4345
4446 const selectedProfileId = useAppSelector(
4547 (store) => store.profiles.selectedProfileId,
4648 );
4749
4850 const hasDoneInitialConfigLoad = useRef(false);
51+ const currentToolCallApplyState = useAppSelector(
52+ selectCurrentToolCallApplyState,
53+ );
54+
55+ const { mainEditor } = useMainEditor();
4956
5057 const handleConfigUpdate = useCallback(
5158 async (isInitial: boolean, result: FromCoreProtocol["configUpdate"][0]) => {
@@ -99,18 +106,18 @@
99106
100107 // Load config from the IDE
101108 useEffect(() => {
102- initialLoadAuthAndConfig(true);
109+ void initialLoadAuthAndConfig(true);
103110 const interval = setInterval(() => {
104111 if (hasDoneInitialConfigLoad.current) {
105112 // Init to run on initial config load
106113 ideMessenger.post("docs/initStatuses", undefined);
107- dispatch(updateFileSymbolsFromHistory());
108- dispatch(refreshSessionMetadata({}));
114+ void dispatch(updateFileSymbolsFromHistory());
115+ void dispatch(refreshSessionMetadata({}));
109116
110117 // This triggers sending pending status to the GUI for relevant docs indexes
111118 clearInterval(interval);
112119 } else {
113- initialLoadAuthAndConfig(true);
120+ void initialLoadAuthAndConfig(true);
114121 }
115122 }, 2_000);
116123
@@ -132,39 +139,43 @@
132139 const sessionId = useAppSelector((state) => state.session.id);
133140 useEffect(() => {
134141 if (sessionId) {
135- dispatch(updateFileSymbolsFromHistory());
142+ void dispatch(updateFileSymbolsFromHistory());
136143 }
137144 }, [sessionId]);
138145
139146 // ON LOAD
140147 useEffect(() => {
141148 // Override persisted state
142- dispatch(cancelStream());
149+ void dispatch(cancelStream());
143150
144151 const jetbrains = isJetBrains();
145152 setDocumentStylesFromLocalStorage(jetbrains);
146153
147154 if (jetbrains) {
148155 // Save theme colors to local storage for immediate loading in JetBrains
149- ideMessenger.request("jetbrains/getColors", undefined).then((result) => {
150- if (result.status === "success") {
151- setDocumentStylesFromTheme(result.content);
152- }
153- });
156+ void ideMessenger
157+ .request("jetbrains/getColors", undefined)
158+ .then((result) => {
159+ if (result.status === "success") {
160+ setDocumentStylesFromTheme(result.content);
161+ }
162+ });
154163
155164 // Tell JetBrains the webview is ready
156- ideMessenger.request("jetbrains/onLoad", undefined).then((result) => {
157- if (result.status === "error") {
158- return;
159- }
160-
161- const msg = result.content;
162- (window as any).windowId = msg.windowId;
163- (window as any).serverUrl = msg.serverUrl;
164- (window as any).workspacePaths = msg.workspacePaths;
165- (window as any).vscMachineId = msg.vscMachineId;
166- (window as any).vscMediaUrl = msg.vscMediaUrl;
167- });
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+ });
168179 }
169180 }, []);
170181
@@ -194,7 +205,7 @@
194205 );
195206
196207 useWebviewListener("setInactive", async () => {
197- dispatch(cancelStream());
208+ void dispatch(cancelStream());
198209 });
199210
200211 useWebviewListener("setTTSActive", async (status) => {
@@ -203,7 +214,7 @@
203214
204215 // TODO - remove?
205216 useWebviewListener("submitMessage", async (data) => {
206- dispatch(
217+ void dispatch(
207218 streamResponseThunk({
208219 editorState: data.message,
209220 modifiers: { useCodebase: false, noContext: true },
@@ -224,14 +235,15 @@
224235 dispatch(updateIndexingStatus(data));
225236 });
226237
227- const currentToolCallApplyState = useAppSelector(
228- selectCurrentToolCallApplyState,
229- );
230238 useWebviewListener(
231239 "updateApplyState",
232240 async (state) => {
233241 if (state.streamId === EDIT_MODE_STREAM_ID) {
234242 dispatch(updateEditStateApplyState(state));
243+
244+ if (state.status === "closed") {
245+ dispatch(exitEdit({}));
246+ }
235247 } else {
236248 // chat or agent
237249 dispatch(updateApplyState(state));
@@ -253,7 +265,7 @@
253265 }),
254266 );
255267 // dispatch(setToolCallOutput([]));
256- dispatch(
268+ void dispatch(
257269 streamResponseAfterToolCall({
258270 toolCallId: currentToolCallApplyState.toolCallId!,
259271 }),
@@ -264,12 +276,12 @@
264276 [currentToolCallApplyState, history],
265277 );
266278
267- const mode = useAppSelector((store) => store.session.mode);
268279 useEffect(() => {
269- if (mode !== "edit") {
280+ if (!isInEdit) {
270281 dispatch(setLastNonEditSessionEmpty(history.length === 0));
271282 }
272- }, [mode, history]);
283+ }, [isInEdit, history]);
284+
273285 return <></>;
274286 }
275287
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 +29 −36
@@ -46,7 +46,7 @@
4646 } from "../../redux/slices/uiSlice";
4747 import { streamResponseThunk } from "../../redux/thunks";
4848 import { cancelStream } from "../../redux/thunks/cancelStream";
49-import { streamEditThunk } from "../../redux/thunks/editMode";
49+import { streamEditThunk } from "../../redux/thunks/edit";
5050 import { loadLastSession } from "../../redux/thunks/session";
5151 import { isJetBrains, isMetaEquivalentKeyPressed } from "../../util";
5252 import {
@@ -54,9 +54,6 @@
5454 incrementFreeTrialCount,
5555 } from "../../util/freeTrial";
5656
57-import AcceptRejectDiffButtons from "../../components/AcceptRejectDiffButtons";
58-import CodeToEditCard from "../../components/mainInput/CodeToEditCard";
59-import EditModeDetails from "../../components/mainInput/EditModeDetails";
6057 import { getLocalStorage, setLocalStorage } from "../../util/localStorage";
6158 import { EmptyChatBody } from "./EmptyChatBody";
6259 import { ExploreDialogWatcher } from "./ExploreDialogWatcher";
@@ -121,9 +118,7 @@
121118 const codeToEdit = useAppSelector((state) => state.editModeState.codeToEdit);
122119 const toolCallState = useAppSelector(selectCurrentToolCall);
123120 const mode = useAppSelector((store) => store.session.mode);
124- const applyStates = useAppSelector(
125- (state) => state.session.codeBlockApplyStates.states,
126- );
121+ const isInEdit = useAppSelector((store) => store.session.isInEdit);
127122
128123 const lastSessionId = useAppSelector((state) => state.session.lastSessionId);
129124 const hasDismissedExploreDialog = useAppSelector(
@@ -144,6 +139,7 @@
144139 !e.shiftKey
145140 ) {
146141 dispatch(cancelStream());
142+ ideMessenger.post("cancelApply", undefined); // just always cancel, if not in applying won't matter
147143 }
148144 };
149145 window.addEventListener("keydown", listener);
@@ -184,15 +180,14 @@
184180 );
185181 }
186182
187- const model =
188- mode === "edit"
189- ? (selectedModels?.edit ?? selectedModels?.chat)
190- : selectedModels?.chat;
183+ const model = isInEdit
184+ ? (selectedModels?.edit ?? selectedModels?.chat)
185+ : selectedModels?.chat;
191186 if (!model) {
192187 return;
193188 }
194189
195- if (mode === "edit" && codeToEdit.length === 0) {
190+ if (isInEdit && codeToEdit.length === 0) {
196191 return;
197192 }
198193
@@ -223,15 +218,15 @@
223218 }
224219 }
225220
226- if (mode === "edit") {
227- dispatch(
221+ if (isInEdit) {
222+ void dispatch(
228223 streamEditThunk({
229224 editorState,
230225 codeToEdit,
231226 }),
232227 );
233228 } else {
234- dispatch(streamResponseThunk({ editorState, modifiers, index }));
229+ void dispatch(streamResponseThunk({ editorState, modifiers, index }));
235230
236231 if (editorToClearOnSend) {
237232 editorToClearOnSend.commands.clearContent();
@@ -251,7 +246,15 @@
251246 setLocalStorage("mainTextEntryCounter", 1);
252247 }
253248 },
254- [history, selectedModels, streamResponse, mode, codeToEdit, toolCallState],
249+ [
250+ history,
251+ selectedModels,
252+ streamResponse,
253+ mode,
254+ isInEdit,
255+ codeToEdit,
256+ toolCallState,
257+ ],
255258 );
256259
257260 useWebviewListener(
@@ -291,7 +294,7 @@
291294
292295 return (
293296 <>
294- {!!showSessionTabs && mode !== "edit" && <TabBar ref={tabsRef} />}
297+ {!!showSessionTabs && !isInEdit && <TabBar ref={tabsRef} />}
295298 {widget}
296299
297300 <StepsDiv
@@ -380,24 +383,14 @@
380383 ))}
381384 </StepsDiv>
382385 <div className={"relative"}>
383- <>
384- {!isStreaming && mode !== "edit" && (
385- <AcceptRejectDiffButtons
386- applyStates={applyStates}
387- onAcceptOrReject={async () => {}}
388- />
389- )}
390- {mode === "edit" && <CodeToEditCard />}
391- <ContinueInputBox
392- isMainInput
393- isLastUserInput={false}
394- onEnter={(editorState, modifiers, editor) =>
395- sendInput(editorState, modifiers, undefined, editor)
396- }
397- inputId={MAIN_EDITOR_INPUT_ID}
398- />
399- <EditModeDetails />
400- </>
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+ />
401394
402395 <div
403396 style={{
@@ -406,7 +399,7 @@
406399 >
407400 <div className="flex flex-row items-center justify-between pb-1 pl-0.5 pr-2">
408401 <div className="xs:inline hidden">
409- {history.length === 0 && lastSessionId && mode !== "edit" && (
402+ {history.length === 0 && lastSessionId && !isInEdit && (
410403 <div className="xs:inline hidden">
411404 <NewSessionButton
412405 onClick={async () => {
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 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/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/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/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 +1 −1
@@ -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/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+};