Elffuss BraidHub

kikocis/continue public

Merge branch 'main' into pe/markdown-rule-desc
Changeset611a42e81eb833cc77760c88a82993f242d1e628d69fcfe9a368ffd04755de23
AuthorPatrick Erichsen <patrick.a.erichsen@gmail.com> · 2025-05-23 17:32 -07:00
CommitterGitHub <noreply@github.com> · 2025-05-23 17:32 -07:00
Parentsde41b37de6c3, 5c04796c86d6

Browse the files at this changeset

42 files changed

modified core/config/yaml/loadYaml.ts +2 −2
@@ -71,7 +71,7 @@
7171 command: server.command,
7272 args: server.args ?? [],
7373 env: server.env,
74- },
74+ } as any, // TODO: Fix the mcpServers types in config-yaml (discriminated union)
7575 timeout: server.connectionTimeout,
7676 };
7777 }
@@ -458,7 +458,7 @@
458458 transport: {
459459 type: "stdio",
460460 args: [],
461- ...server,
461+ ...(server as any), // TODO: fix the types on mcpServers in config-yaml
462462 },
463463 timeout: server.connectionTimeout,
464464 })),
modified core/llm/llms/Bedrock.ts +1 −1
@@ -306,7 +306,7 @@
306306 }
307307
308308 const supportsTools =
309- PROVIDER_TOOL_SUPPORT.bedrock?.(options.model || "") ?? false;
309+ (this.capabilities?.tools || PROVIDER_TOOL_SUPPORT.bedrock?.(options.model)) ?? false;
310310
311311 let toolConfig = supportsTools && options.tools
312312 ? {
modified core/llm/llms/stubs/ContinueProxy.ts +5 −0
@@ -27,8 +27,12 @@
2727 // to call whatever LLM API is chosen
2828 private actualApiBase?: string;
2929
30+ // Contains extra properties that we pass along to the proxy. Originally from `env` property on LLMOptions
31+ private configEnv?: Record<string, any>;
32+
3033 constructor(options: LLMOptions) {
3134 super(options);
35+ this.configEnv = options.env;
3236 this.actualApiBase = options.apiBase;
3337 this.apiKeyLocation = options.apiKeyLocation;
3438 this.orgScopeId = options.orgScopeId;
@@ -48,6 +52,7 @@
4852 apiKeyLocation: this.apiKeyLocation,
4953 apiBase: this.actualApiBase,
5054 orgScopeId: this.orgScopeId ?? null,
55+ env: this.configEnv,
5156 };
5257 return {
5358 continueProperties,
modified core/llm/toolSupport.ts +3 −2
@@ -17,6 +17,7 @@
1717 "claude-3.5",
1818 "claude-3-7",
1919 "claude-3.7",
20+ "claude-sonnet-4",
2021 "gpt-4",
2122 "o3",
2223 "gemini",
@@ -24,7 +25,7 @@
2425 },
2526 anthropic: (model) => {
2627 if (
27- ["claude-3-5", "claude-3.5", "claude-3-7", "claude-3.7"].some((part) =>
28+ ["claude-3-5", "claude-3.5", "claude-3-7", "claude-3.7","claude-sonnet-4"].some((part) =>
2829 model.toLowerCase().startsWith(part),
2930 )
3031 ) {
@@ -76,7 +77,7 @@
7677 // For Bedrock, only support Claude Sonnet models with versions 3.5/3-5 and 3.7/3-7
7778 if (
7879 model.toLowerCase().includes("sonnet") &&
79- ["claude-3-5", "claude-3.5", "claude-3-7", "claude-3.7"].some((part) =>
80+ ["claude-3-5", "claude-3.5", "claude-3-7", "claude-3.7","claude-sonnet-4"].some((part) =>
8081 model.toLowerCase().includes(part),
8182 )
8283 ) {
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/protocol/ideWebview.ts +3 −3
@@ -2,12 +2,12 @@
22 import { ToWebviewFromIdeOrCoreProtocol } from "./webview";
33
44 import {
5+ AcceptOrRejectDiffPayload,
56 ApplyState,
6- SetCodeToEditPayload,
77 HighlightedCodePayload,
88 MessageContent,
99 RangeInFileWithContents,
10- AcceptOrRejectDiffPayload,
10+ SetCodeToEditPayload,
1111 ShowFilePayload,
1212 } from "../";
1313
@@ -42,7 +42,7 @@
4242 vscMediaUrl: string;
4343 },
4444 ];
45- "jetbrains/getColors": [undefined, Record<string, string>];
45+ "jetbrains/getColors": [undefined, Record<string, string | null | undefined>];
4646 "vscode/openMoveRightMarkdown": [undefined, void];
4747 setGitHubAuthToken: [{ token: string }, void];
4848 acceptDiff: [AcceptOrRejectDiffPayload, void];
modified core/protocol/webview.ts +1 −1
@@ -40,7 +40,7 @@
4040 setTTSActive: [boolean, void];
4141 getWebviewHistoryLength: [undefined, number];
4242 getCurrentSessionId: [undefined, string];
43- "jetbrains/setColors": [Record<string, string>, void];
43+ "jetbrains/setColors": [Record<string, string | null | undefined>, void];
4444 sessionUpdate: [{ sessionInfo: ControlPlaneSessionInfo | undefined }, void];
4545 toolCallPartialOutput: [{ toolCallId: string; contextItems: any[] }, void];
4646 };
modified docs/docs/reference.md +1 −1
@@ -406,7 +406,7 @@
406406 - `destination` (**required**): The destination/endpoint that will receive the data. Can be:
407407 - an HTTP endpoint that will receive a POST request with a JSON blob
408408 - a file URL to a directory in which events will be dumpted to `.jsonl` files
409-- `schema` (**required**): the schema version of the JSON blobs to be sent
409+- `schema` (**required**): the schema version of the JSON blobs to be sent. Options include `0.1.0` and `0.2.0`
410410 - `events`: an array of event names to include. Defaults to all events if not specified.
411411 - `level`: a pre-defined filter for event fields. Options include `all` and `noCode`; the latter excludes data like file
412412 contents, prompts, and completions. Defaults to `all`
modified docs/docs/troubleshooting.mdx +2 −0
@@ -120,6 +120,8 @@
120120
121121 You may also set `requestOptions.caBundlePath` to an array of paths to multiple certificates.
122122
123+***Windows VS Code Users***: Installing the [win-ca](https://marketplace.visualstudio.com/items?itemName=ukoloff.win-ca) extension should also correct this issue.
124+
123125 #### VS Code Proxy Settings
124126
125127 If you are using VS Code and require requests to be made through a proxy, you are likely already set up through VS Code's [Proxy Server Support](https://code.visualstudio.com/docs/setup/network#_proxy-server-support). To double-check that this is enabled, use <kbd>cmd/ctrl</kbd> + <kbd>,</kbd> to open settings and search for "Proxy Support". Unless it is set to "off", then VS Code is responsible for making the request to the proxy.
modified extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/continue/GetTheme.kt +146 −35
@@ -2,11 +2,13 @@
22
33 import com.intellij.openapi.editor.colors.EditorColors
44 import com.intellij.openapi.editor.colors.EditorColorsManager
5+import com.intellij.openapi.editor.colors.CodeInsightColors
56 import java.awt.Color
67 import kotlin.math.max
78 import kotlin.math.min
89 import com.intellij.ui.JBColor
910 import com.intellij.ui.ColorUtil
11+import kotlin.math.roundToInt
1012
1113 class GetTheme {
1214 fun getSecondaryDark(): Color {
@@ -38,64 +40,173 @@
3840 return globalScheme.getColor(EditorColors.MODIFIED_TAB_ICON_COLOR) ?: globalScheme.defaultForeground
3941 }
4042
41- fun getTheme(): Map<String, String> {
42- fun toHex(color: Color): String {
43- return String.format("#%02x%02x%02x", color.red, color.green, color.blue)
43+ fun toHex(color: Color?): String? {
44+ if(color == null) {
45+ return null
4446 }
47+ return String.format("#%02x%02x%02x", color.red, color.green, color.blue)
48+ }
49+
50+ fun namedColor(name: String): Color? {
51+ // JB Color named color will fall back to a default unless we give it a fallback
52+ // We want defaults to be handled on the GUI side, so we give it this filler color
53+ // Which has a very low chance of conflicting with a real one
54+ // And return undefined if it gets the skip color
55+ val SKIP_COLOR = Color (18, 52, 86) // Hex #123456
56+ val color = JBColor.namedColor(name, SKIP_COLOR)
57+ if(toHex(color) == "#123456") {
58+ return null
59+ }
60+ return color
61+ }
62+
63+ fun lighten(color: Color, percentage: Int = 5): Color {
64+ // Increase each RGB component slightly
65+ val factor = 1 + percentage / 100f;
66+ fun lightenInt(value: Int): Int {
67+ return (value * factor).roundToInt().coerceAtMost(255)
68+ }
69+ return Color(
70+ lightenInt(color.red),
71+ lightenInt (color.green),
72+ lightenInt(color.blue),
73+ color.alpha
74+ )
75+ }
76+
77+ fun darken(color: Color, percentage: Int = 5): Color {
78+ // Decrease each RGB component slightly
79+ val factor = 1 - percentage / 100f;
80+ fun darkenInt(value: Int): Int {
81+ return (value * factor).roundToInt().coerceAtLeast(0)
82+ }
83+ return Color(
84+ darkenInt(color.red),
85+ darkenInt(color.green),
86+ darkenInt(color.blue),
87+ color.alpha
88+ )
89+ }
90+
91+ fun slightChange(color: Color?, percentage: Int = 5): Color? {
92+ if(color == null){
93+ return null
94+ }
95+ // If dark, make slightly lighter. If light, make slightly darker
96+ val averageRgb = (color.red + color.green + color.blue) / 3
97+ return if (averageRgb > 128) darken(color, percentage) else lighten(color, percentage)
98+ }
99+
100+ fun getTheme(): Map<String, String?> {
45101 try {
102+ val editorScheme = EditorColorsManager.getInstance().globalScheme
103+
46104 val background = JBColor.background()
47105 val foreground = JBColor.foreground()
48106
49- val buttonBackground = JBColor.namedColor("Button.background", Color(230, 230, 230))
50- val buttonForeground = JBColor.namedColor("Button.foreground", Color(0, 0, 0))
107+ val border = JBColor.border()
108+ val focusBorder = namedColor("Focus.borderColor") ?: namedColor("Component.focusedBorderColor")
51109
52- val badgeBackground = JBColor.namedColor("Badge.background", Color(150, 150, 150))
53- val badgeForeground = JBColor.namedColor("Badge.foreground", Color(0, 0, 0))
110+ val buttonBackground = namedColor("Button.default.startBackground")
111+ ?: namedColor("Button.default.background")
54112
55- val inputBackground = JBColor.namedColor("TextField.background", Color(255, 255, 255))
113+ val buttonForeground = namedColor("Button.default.startForeground")
114+ ?: namedColor("Button.default.foreground")
56115
57- val border = JBColor.border()
58- val focusBorder = JBColor.namedColor("Focus.borderColor", Color(100, 100, 255))
59- val editorScheme = EditorColorsManager.getInstance().globalScheme
116+ val buttonHoverBackground = namedColor("Button.default.hoverStartBackground")
117+ ?: namedColor("Button.default.hoverBackground")
118+ ?: namedColor("Button.default.startHoverBackground")
119+ ?: slightChange(buttonBackground)
60120
61- val editorBackground = editorScheme.defaultBackground
62- val editorForeground = editorScheme.defaultForeground
121+ val secondaryBackground = namedColor("Button.background") ?: background
122+ val secondaryHoverBackground = namedColor("Button.hoverBackground") ?: slightChange(secondaryBackground)
63123
64- val actionHoverBackground = JBColor.namedColor("ActionButton.hoverBackground", Color(220, 220, 220))
124+ val badgeBackground = namedColor("Badge.background")
125+ val badgeForeground = namedColor("Badge.foreground")
65126
66- val findMatchBackground = editorScheme.getAttributes(EditorColors.SEARCH_RESULT_ATTRIBUTES)?.backgroundColor ?: Color(255, 221, 0)
127+ val commandBackground = namedColor("CommandButton.background") ?: namedColor("ToolWindow.background")
128+ val commandForeground = namedColor("CommandButton.foreground") ?: namedColor("ToolWindow.foreground")
67129
68- val theme = mapOf(
69- "--vscode-editor-foreground" to toHex(editorForeground),
70- "--vscode-editor-background" to toHex(editorBackground),
130+ val inputBackground = namedColor("TextField.background")
131+ val inputForeground = namedColor("TextField.foreground")
132+ val inputPlaceholder = namedColor("TextField.inactiveForeground")
133+
134+ val listHoverBackground = namedColor("List.hoverBackground") ?: slightChange(background)
135+ val actionHoverBackground = namedColor("ActionButton.hoverBackground") ?: namedColor("Button.darcula.hoverBackground")
136+
137+ val tableOddRow = namedColor("Table.hoverBackground") ?: namedColor("Table.stripeColor")
138+ val listSelectionForeground = namedColor("List.selectionForeground")
71139
72- "--vscode-button-background" to toHex(buttonBackground),
73- "--vscode-button-foreground" to toHex(buttonForeground),
140+ val description = namedColor("Label.disabledForeground") ?: namedColor("Label.infoForeground")
74141
75- "--vscode-list-activeSelectionBackground" to toHex(actionHoverBackground) + "50",
142+ val mutedDescription = namedColor("Component.infoForeground")
143+ ?: namedColor("ContextHelp.foreground")
144+ ?: namedColor("TextField.placeholderForeground")
145+ ?: namedColor("Label.disabledForeground")
146+ ?: namedColor("ToolTip.foreground")
76147
77- "--vscode-quickInputList-focusForeground" to toHex(foreground),
78- "--vscode-quickInput-background" to toHex(inputBackground),
148+ val link = namedColor("Link.activeForeground")
79149
80- "--vscode-badge-background" to toHex(badgeBackground),
81- "--vscode-badge-foreground" to toHex(badgeForeground),
150+ val successColor = namedColor("ValidationSuccess.successColor")
151+ ?: namedColor("Component.successForeground")
152+ ?: namedColor("Label.successForeground")
153+ val warningColor = namedColor("ValidationWarning.warningColor")
154+ ?: EditorColorsManager.getInstance().globalScheme.getAttributes(CodeInsightColors.WARNINGS_ATTRIBUTES)?.effectColor
155+ ?: namedColor("Component.warningForeground")
156+ ?: namedColor("Label.warningForeground")
157+ val errorColor = namedColor("ValidationError.errorColor") ?: namedColor("Component.errorForeground") ?: namedColor("Label.errorForeground")
82158
83- "--vscode-input-background" to toHex(inputBackground),
84- "--vscode-input-border" to toHex(border),
85- "--vscode-sideBar-background" to toHex(background),
86- "--vscode-sideBar-border" to toHex(border),
87- "--vscode-focusBorder" to toHex(focusBorder),
159+ val accentColor = namedColor("Focus.defaultButtonBorderColor") ?: namedColor("Button.default.focusedBorderColor") ?: namedColor("Button.focusedBorderColor")
88160
89- "--vscode-commandCenter-activeBorder" to toHex(focusBorder),
90- "--vscode-commandCenter-inactiveBorder" to toHex(border),
161+ val editorBackground = editorScheme.defaultBackground
162+ val editorForeground = editorScheme.defaultForeground
91163
92- "--vscode-editor-findMatchHighlightBackground" to toHex(findMatchBackground) + "40"
93- )
164+ val findMatchBackground = editorScheme.getAttributes(EditorColors.SEARCH_RESULT_ATTRIBUTES)?.backgroundColor
94165
166+ val findMatchSelectedBackground = namedColor("SearchMatch.selectedBackground") ?:
167+ editorScheme.getAttributes(EditorColors.SEARCH_RESULT_ATTRIBUTES)?.backgroundColor
168+
169+ // These should match the keys in GUI's theme.ts
170+ val theme = mapOf(
171+ "background" to background,
172+ "foreground" to foreground,
173+ "editor-background" to editorBackground,
174+ "editor-foreground" to editorForeground,
175+ "primary-background" to buttonBackground,
176+ "primary-foreground" to buttonForeground,
177+ "primary-hover" to buttonHoverBackground,
178+ "secondary-background" to secondaryBackground,
179+ "secondary-foreground" to foreground,
180+ "secondary-hover" to secondaryHoverBackground,
181+ "border" to border,
182+ "border-focus" to focusBorder,
183+ "command-background" to commandBackground,
184+ "command-foreground" to commandForeground,
185+ "command-border" to border,
186+ "command-border-focus" to focusBorder,
187+ "description" to description,
188+ "description-muted" to mutedDescription,
189+ "input-background" to inputBackground,
190+ "input-foreground" to inputForeground,
191+ "input-border" to border,
192+ "input-placeholder" to inputPlaceholder,
193+ "table-oddRow" to tableOddRow,
194+ "badge-background" to badgeBackground,
195+ "badge-foreground" to badgeForeground,
196+ "success" to successColor,
197+ "warning" to warningColor,
198+ "error" to errorColor,
199+ "link" to link,
200+ "accent" to accentColor,
201+ "find-match" to findMatchBackground,
202+ "find-match-selected" to findMatchSelectedBackground,
203+ "list-hover" to listHoverBackground,
204+ "list-active" to actionHoverBackground,
205+ "list-active-foreground" to listSelectionForeground
206+ ).mapValues { toHex(it.value) }
95207 return theme
96208 } catch (error: Error) {
97209 return mapOf()
98210 }
99-
100211 }
101212 }
No newline at the end of the file
modified extensions/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 +2 −2
@@ -2,7 +2,7 @@
22 "name": "continue",
33 "icon": "media/icon.png",
44 "author": "Continue Dev, Inc",
5- "version": "1.1.38",
5+ "version": "1.1.39",
66 "repository": {
77 "type": "git",
88 "url": "https://github.com/continuedev/continue"
@@ -631,7 +631,7 @@
631631 "devDependencies": {
632632 "@biomejs/biome": "1.6.4",
633633 "@nestjs/common": "^11.0.16",
634- "@openapitools/openapi-generator-cli": "^2.5.2",
634+ "@openapitools/openapi-generator-cli": "^2.20.0",
635635 "@types/chai": "^5.0.1",
636636 "@types/cors": "^2.8.17",
637637 "@types/express": "^4.17.21",
modified gui/package-lock.json +0 −0

Not shown: the file is larger than the hub shows, or this page holds as much as it shows. View the file.

modified gui/src/App.tsx +5 −0
@@ -9,6 +9,7 @@
99 import Chat from "./pages/gui";
1010 import History from "./pages/history";
1111 import Stats from "./pages/stats";
12+import ThemePage from "./styles/ThemePage";
1213 import { ROUTES } from "./util/navigation";
1314
1415 const router = createMemoryRouter([
@@ -37,6 +38,10 @@
3738 path: ROUTES.CONFIG,
3839 element: <ConfigPage />,
3940 },
41+ {
42+ path: ROUTES.THEME,
43+ element: <ThemePage />,
44+ },
4045 ],
4146 },
4247 ]);
modified gui/src/components/StyledMarkdownPreview/SymbolLink.tsx +1 −8
@@ -44,14 +44,7 @@
4444 data-tooltip-id={id}
4545 data-tooltip-delay-show={500}
4646 >
47- <code
48- className="align-middle"
49- style={{
50- color: "var(--vscode-textLink-foreground)",
51- }}
52- >
53- {content}
54- </code>
47+ <code className="text-link align-middle">{content}</code>
5548 </span>
5649 <ToolTip id={id} place="top" className="m-0 p-0">
5750 <pre className="text-left">{processedContent ?? symbol.filepath}</pre>
modified gui/src/components/TabBar/TabBar.tsx +23 −42
@@ -13,13 +13,25 @@
1313 } from "../../redux/slices/tabsSlice";
1414 import { AppDispatch, RootState } from "../../redux/store";
1515 import { loadSession, saveCurrentSession } from "../../redux/thunks/session";
16+import { varWithFallback } from "../../styles/theme";
17+
18+// Haven't set up theme colors for tabs yet
19+// Will keep it simple and choose from existing ones. Comments show vars we could use
20+const tabBorderVar = varWithFallback("border"); // --vscode-tab-border
21+const tabBackgroundVar = varWithFallback("background"); // --vscode-tab-inactiveBackground
22+const tabForegroundVar = varWithFallback("foreground"); // --vscode-tab-inactiveForeground
23+const tabHoverBackgroundVar = varWithFallback("list-hover"); // --vscode-tab-hoverBackground
24+const tabHoverForegroundVar = varWithFallback("foreground"); // --vscode-tab-hoverForeground
25+const tabSelectedBackgroundVar = varWithFallback("background"); // --vscode-tab-activeBackground
26+const tabSelectedForegroundVar = varWithFallback("foreground"); // --vscode-tab-activeForeground
27+const tabAccentVar = varWithFallback("accent"); // --vscode-tab-activeBorderTop
1628
1729 const TabBarContainer = styled.div`
1830 display: flex;
1931 flex-wrap: wrap;
2032 flex-shrink: 0;
2133 flex-grow: 0;
22- background-color: var(--vscode-tab-inactiveBackground);
34+ background-color: ${tabBackgroundVar};
2335 border-bottom: none;
2436 position: relative;
2537 margin-top: 2px;
@@ -41,24 +53,18 @@
4153 max-width: 150px;
4254 height: 25px;
4355 background-color: ${(props) =>
44- props.isActive
45- ? "var(--vscode-tab-activeBackground)"
46- : "var(--vscode-tab-inactiveBackground)"};
56+ props.isActive ? tabSelectedBackgroundVar : tabBackgroundVar};
4757 color: ${(props) =>
48- props.isActive
49- ? "var(--vscode-tab-activeForeground)"
50- : "var(--vscode-tab-inactiveForeground)"};
58+ props.isActive ? tabSelectedForegroundVar : tabForegroundVar};
5159 cursor: pointer;
52- border: 1px solid var(--vscode-tab-border);
60+ border: 1px solid ${tabBorderVar};
5361 border-bottom: ${(props) =>
54- props.isActive ? "none" : `1px solid var(--vscode-tab-border)`};
62+ props.isActive ? "none" : `1px solid ${tabBorderVar}`};
5563 user-select: none;
5664 position: relative;
5765 transition: background-color 0.2s;
5866 border-top: ${(props) =>
59- props.isActive
60- ? `1px solid var(--vscode-tab-activeBorderTop, --vscode-tab-border)`
61- : `1px solid var(--vscode-tab-border)`};
67+ props.isActive ? `1px solid ${tabAccentVar}` : `1px solid ${tabBorderVar}`};
6268 &:first-child {
6369 border-left: none;
6470 }
@@ -68,13 +74,9 @@
6874
6975 &:hover {
7076 background-color: ${(props) =>
71- props.isActive
72- ? "var(--vscode-tab-activeBackground)"
73- : "var(--vscode-tab-hoverBackground)"};
77+ props.isActive ? tabSelectedBackgroundVar : tabHoverBackgroundVar};
7478 color: ${(props) =>
75- props.isActive
76- ? "var(--vscode-tab-activeForeground)"
77- : "var(--vscode-tab-hoverForeground)"};
79+ props.isActive ? tabSelectedForegroundVar : tabHoverForegroundVar};
7880 }
7981 `;
8082
@@ -104,7 +106,7 @@
104106
105107 &:hover {
106108 opacity: 1;
107- background-color: var(--vscode-tab-hoverBackground);
109+ background-color: ${tabHoverBackgroundVar};
108110 }
109111
110112 ${Tab}:hover & {
@@ -119,33 +121,12 @@
119121 const TabBarSpace = styled.div`
120122 flex: 1;
121123 display: flex;
122- border-bottom: 1px solid var(--vscode-tab-border);
123- background-color: var(--vscode-tab-inactiveBackground);
124-`;
125-
126-const NewTabButton = styled.button`
127- display: flex;
128- align-items: center;
129- justify-content: center;
130- width: 35px;
131- height: 100%;
132- border: none;
133- background: transparent;
134- color: var(--vscode-tab-inactiveForeground);
135- cursor: pointer;
136- opacity: 0.7;
137- transition: opacity 0.2s;
138-
139- &:hover {
140- opacity: 1;
141- background-color: var(--vscode-tab-hoverBackground);
142- color: var(--vscode-tab-hoverForeground);
143- }
124+ border-bottom: 1px solid ${tabBorderVar};
125+ background-color: ${tabBackgroundVar};
144126 `;
145127
146128 export function TabBar() {
147129 const dispatch = useDispatch<AppDispatch>();
148- const currentSession = useSelector((state: RootState) => state.session);
149130 const currentSessionId = useSelector((state: RootState) => state.session.id);
150131 const currentSessionTitle = useSelector(
151132 (state: RootState) => state.session.title,
modified gui/src/components/dialogs/index.tsx +2 −3
@@ -4,12 +4,11 @@
44 import styled from "styled-components";
55 import {
66 CloseButton,
7- VSC_BACKGROUND_VAR,
87 defaultBorderRadius,
9- parseColorForHex,
108 vscBackground,
119 vscForeground,
1210 } from "..";
11+import { varWithFallback } from "../../styles/theme";
1312
1413 interface TextDialogProps {
1514 showDialog: boolean;
@@ -22,7 +21,7 @@
2221 position: fixed;
2322 width: 100%;
2423 height: 100%;
25- background-color: ${parseColorForHex(VSC_BACKGROUND_VAR)}aa;
24+ background-color: ${varWithFallback("background")}aa;
2625 z-index: 100000;
2726 flex-direction: column;
2827 `;
modified gui/src/components/find/FindWidget.tsx +2 −2
@@ -12,8 +12,8 @@
1212 useState,
1313 } from "react";
1414 import { HeaderButton, Input } from "..";
15-import HeaderButtonWithToolTip from "../gui/HeaderButtonWithToolTip";
1615 import { useAppSelector } from "../../redux/hooks";
16+import HeaderButtonWithToolTip from "../gui/HeaderButtonWithToolTip";
1717
1818 interface SearchMatch {
1919 index: number;
@@ -41,7 +41,7 @@
4141 const { isCurrent, top, left, width, height } = props;
4242 return (
4343 <div
44- className={isCurrent ? "bg-find-match-selected" : "bg-blue-200/30"} // bg-vsc-find-match can"t get to work
44+ className={isCurrent ? "bg-findMatch-selected/50" : "bg-findMatch/50"}
4545 key={`highlight-${top}-${left}`}
4646 style={{
4747 position: "absolute",
modified gui/src/components/gui/Alert.tsx +1 −1
@@ -39,7 +39,7 @@
3939 const { Icon } = ALERT_CONFIGS[type];
4040
4141 return (
42- <div className="rounded-lg border-l-4 bg-[color:var(--vscode-editor-foreground)] p-4 opacity-70 shadow-none">
42+ <div className="bg-editor-foreground rounded-lg border-l-4 p-4 opacity-70 shadow-none">
4343 <div className="flex items-start">
4444 <Icon
4545 className="h-6 min-h-5 w-6 min-w-5"
modified gui/src/components/index.ts +22 −109
@@ -1,114 +1,31 @@
11 import styled from "styled-components";
2-import { getFontSize } from "../util";
3-
4-export const VSC_INPUT_BACKGROUND_VAR = "--vscode-input-background";
5-export const VSC_BACKGROUND_VAR = "--vscode-sideBar-background";
6-export const VSC_FOREGROUND_VAR = "--vscode-editor-foreground";
7-export const VSC_BUTTON_BACKGROUND_VAR = "--vscode-button-background";
8-export const VSC_BUTTON_FOREGROUND_VAR = "--vscode-button-foreground";
9-export const VSC_EDITOR_BACKGROUND_VAR = "--vscode-editor-background";
10-export const VSC_LIST_SELECTION_BACKGROUND_VAR =
11- "--vscode-list-activeSelectionBackground";
12-export const VSC_FOCUS_BORDER_VAR = "--vscode-focusBorder";
13-export const VSC_LIST_ACTIVE_FOREGROUND_VAR =
14- "--vscode-quickInputList-focusForeground";
15-export const VSC_QUICK_INPUT_BACKGROUND_VAR = "--vscode-quickInput-background";
16-export const VSC_INPUT_BORDER_VAR = "--vscode-input-border";
17-export const VSC_BADGE_BACKGROUND_VAR = "--vscode-badge-background";
18-export const VSC_BADGE_FOREGROUND_VAR = "--vscode-badge-foreground";
19-export const VSC_COMMAND_CENTER_ACTIVE_BORDER_VAR =
20- "--vscode-commandCenter-activeBorder";
21-export const VSC_COMMAND_CENTER_INACTIVE_BORDER_VAR =
22- "--vscode-commandCenter-inactiveBorder";
23-export const VSC_FIND_MATCH_SELECTED_VAR =
24- "--vscode-editor-findMatchHighlightBackground";
25-
26-export const VSC_THEME_COLOR_VARS = [
27- VSC_INPUT_BACKGROUND_VAR,
28- VSC_BACKGROUND_VAR,
29- VSC_FOREGROUND_VAR,
30- VSC_BUTTON_BACKGROUND_VAR,
31- VSC_BUTTON_FOREGROUND_VAR,
32- VSC_EDITOR_BACKGROUND_VAR,
33- VSC_LIST_SELECTION_BACKGROUND_VAR,
34- VSC_FOCUS_BORDER_VAR,
35- VSC_LIST_ACTIVE_FOREGROUND_VAR,
36- VSC_QUICK_INPUT_BACKGROUND_VAR,
37- VSC_INPUT_BORDER_VAR,
38- VSC_BADGE_BACKGROUND_VAR,
39- VSC_BADGE_FOREGROUND_VAR,
40- VSC_COMMAND_CENTER_ACTIVE_BORDER_VAR,
41- VSC_COMMAND_CENTER_INACTIVE_BORDER_VAR,
42- VSC_FIND_MATCH_SELECTED_VAR,
43-];
2+import { varWithFallback } from "../styles/theme";
443
4+// DEPRECATED - avoid using these where possible, use tailwind classes instead
455 export const defaultBorderRadius = "5px";
466 export const lightGray = "#999998";
477 export const greenButtonColor = "#189e72";
488
49-export const vscInputBackground = `var(${VSC_INPUT_BACKGROUND_VAR}, rgb(45 45 45))`;
50-export const vscQuickInputBackground = `var(${VSC_QUICK_INPUT_BACKGROUND_VAR}, ${VSC_INPUT_BACKGROUND_VAR}, rgb(45 45 45))`;
51-export const vscBackground = `var(${VSC_BACKGROUND_VAR}, rgb(30 30 30))`;
52-export const vscForeground = `var(${VSC_FOREGROUND_VAR}, #fff)`;
53-export const vscButtonBackground = `var(${VSC_BUTTON_BACKGROUND_VAR}, #1bbe84)`;
54-export const vscButtonForeground = `var(${VSC_BUTTON_FOREGROUND_VAR}, #ffffff)`;
55-export const vscEditorBackground = `var(${VSC_EDITOR_BACKGROUND_VAR}, ${VSC_BACKGROUND_VAR}, rgb(30 30 30))`;
56-export const vscListActiveBackground = `var(${VSC_LIST_SELECTION_BACKGROUND_VAR}, #1bbe84)`;
57-export const vscFocusBorder = `var(${VSC_FOCUS_BORDER_VAR}, #1bbe84)`;
58-export const vscListActiveForeground = `var(${VSC_LIST_ACTIVE_FOREGROUND_VAR}, ${VSC_FOREGROUND_VAR})`;
59-export const vscInputBorder = `var(${VSC_INPUT_BORDER_VAR}, ${lightGray})`;
60-export const vscInputBorderFocus = `var(${VSC_FOCUS_BORDER_VAR}, ${lightGray})`;
61-export const vscBadgeBackground = `var(${VSC_BADGE_BACKGROUND_VAR}, #1bbe84)`;
62-export const vscBadgeForeground = `var(${VSC_BADGE_FOREGROUND_VAR}, #ffffff)`;
63-export const vscCommandCenterActiveBorder = `var(${VSC_COMMAND_CENTER_ACTIVE_BORDER_VAR}, #1bbe84)`;
64-export const vscCommandCenterInactiveBorder = `var(${VSC_COMMAND_CENTER_INACTIVE_BORDER_VAR}, #1bbe84)`;
65-export const vscFindMatchSelected = `var(${VSC_FIND_MATCH_SELECTED_VAR}, rgba(255, 223, 0))`;
66-
67-export function parseHexColor(hexColor: string): {
68- r: number;
69- g: number;
70- b: number;
71-} {
72- if (hexColor.startsWith("#")) {
73- hexColor = hexColor.slice(1);
74- }
75-
76- if (hexColor.length > 6) {
77- hexColor = hexColor.slice(0, 6);
78- }
79-
80- const r = parseInt(hexColor.substring(0, 2), 16);
81- const g = parseInt(hexColor.substring(2, 4), 16);
82- const b = parseInt(hexColor.substring(4, 6), 16);
83-
84- return { r, g, b };
85-}
86-
87-export function parseColorForHex(colorVar: string): string {
88- const value = getComputedStyle(document.documentElement).getPropertyValue(
89- colorVar,
90- );
91- if (value.startsWith("#")) {
92- return value.slice(0, 7);
93- }
94-
95- // Parse rgb/rgba
96- const rgbValues = value
97- .slice(value.startsWith("rgba") ? 5 : 4, -1)
98- .split(",")
99- .map((x) => x.trim())
100- .filter((_, i) => i < 3) // Only take the first 3 values (RGB, ignore alpha)
101- .map((x) => parseInt(x, 10));
102-
103- let hex =
104- "#" +
105- rgbValues
106- .map((x) => x.toString(16))
107- .map((x) => (x.length === 1 ? "0" + x : x))
108- .join("");
109-
110- return hex;
111-}
9+export const vscInputBackground = varWithFallback("input-background");
10+export const vscQuickInputBackground = varWithFallback("input-background");
11+export const vscBackground = varWithFallback("background");
12+export const vscForeground = varWithFallback("foreground");
13+export const vscButtonBackground = varWithFallback("primary-background");
14+export const vscButtonForeground = varWithFallback("primary-foreground");
15+export const vscEditorBackground = varWithFallback("editor-background");
16+export const vscListActiveBackground = varWithFallback("list-active");
17+export const vscFocusBorder = varWithFallback("border-focus");
18+export const vscListActiveForeground = varWithFallback(
19+ "list-active-foreground",
20+);
21+export const vscInputBorder = varWithFallback("input-border");
22+export const vscInputBorderFocus = varWithFallback("border-focus");
23+export const vscBadgeBackground = varWithFallback("badge-background");
24+export const vscBadgeForeground = varWithFallback("badge-foreground");
25+export const vscCommandCenterActiveBorder = varWithFallback(
26+ "command-border-focus",
27+);
28+export const vscCommandCenterInactiveBorder = varWithFallback("command-border");
11229
11330 export const Button = styled.button`
11431 padding: 6px 12px;
@@ -226,10 +143,6 @@
226143 }
227144 `;
228145
229-export const Label = styled.label<{ fontSize?: number }>`
230- font-size: ${(props) => props.fontSize || getFontSize()}px;
231-`;
232-
233146 export const HeaderButton = styled.button<{
234147 inverted: boolean | undefined;
235148 backgroundColor?: string;
modified gui/src/components/mainInput/TipTapEditor/components/ExpandableToolbarPreview.tsx +1 −1
@@ -159,7 +159,7 @@
159159 contentEditable={false}
160160 >
161161 <div
162- className="border-b-vsc-commandCenter-inactiveBorder m-0 flex cursor-pointer items-center justify-between break-all border-0 border-b-[1px] border-solid px-[5px] py-1.5 hover:opacity-90"
162+ className="border-b-command-border m-0 flex cursor-pointer items-center justify-between break-all border-0 border-b-[1px] border-solid px-[5px] py-1.5 hover:opacity-90"
163163 style={{
164164 fontSize: getFontSize() - 3,
165165 }}
modified gui/src/context/VscTheme.tsx +1 −1
@@ -1,6 +1,6 @@
11 import { createContext, useContext, useState } from "react";
2-import { parseHexColor } from "../components";
32 import { useWebviewListener } from "../hooks/useWebviewListener";
3+import { parseHexColor } from "../styles/utils";
44
55 const hljsToTextMate: Record<string, string[]> = {
66 ".hljs-comment": ["comment"],
modified gui/src/hooks/ParallelListeners.tsx +7 −34
@@ -1,5 +1,4 @@
11 import { useCallback, useContext, useEffect, useRef } from "react";
2-import { VSC_THEME_COLOR_VARS } from "../components";
32 import { IdeMessengerContext } from "../context/IdeMessenger";
43
54 import { EDIT_MODE_STREAM_ID } from "core/edit/constants";
@@ -29,6 +28,10 @@
2928 import { refreshSessionMetadata } from "../redux/thunks/session";
3029 import { streamResponseThunk } from "../redux/thunks/streamResponse";
3130 import { updateFileSymbolsFromHistory } from "../redux/thunks/updateFileSymbols";
31+import {
32+ setDocumentStylesFromLocalStorage,
33+ setDocumentStylesFromTheme,
34+} from "../styles/theme";
3235 import { isJetBrains } from "../util";
3336 import { setLocalStorage } from "../util/localStorage";
3437 import { useWebviewListener } from "./useWebviewListener";
@@ -139,31 +142,13 @@
139142 dispatch(cancelStream());
140143
141144 const jetbrains = isJetBrains();
142- for (const colorVar of VSC_THEME_COLOR_VARS) {
143- if (jetbrains) {
144- const cached = localStorage.getItem(colorVar);
145- if (cached) {
146- document.body.style.setProperty(colorVar, cached);
147- }
148- }
149-
150- // Remove alpha channel from colors
151- const value = getComputedStyle(document.documentElement).getPropertyValue(
152- colorVar,
153- );
154- if (colorVar.startsWith("#") && value.length > 7) {
155- document.body.style.setProperty(colorVar, value.slice(0, 7));
156- }
157- }
145+ setDocumentStylesFromLocalStorage(jetbrains);
158146
159147 if (jetbrains) {
160148 // Save theme colors to local storage for immediate loading in JetBrains
161149 ideMessenger.request("jetbrains/getColors", undefined).then((result) => {
162150 if (result.status === "success") {
163- Object.entries(result.content).forEach(([key, value]) => {
164- document.body.style.setProperty(key, value);
165- document.documentElement.style.setProperty(key, value);
166- });
151+ setDocumentStylesFromTheme(result.content);
167152 }
168153 });
169154
@@ -180,25 +165,13 @@
180165 (window as any).vscMachineId = msg.vscMachineId;
181166 (window as any).vscMediaUrl = msg.vscMediaUrl;
182167 });
183-
184- for (const colorVar of VSC_THEME_COLOR_VARS) {
185- if (document.body.style.getPropertyValue(colorVar)) {
186- localStorage.setItem(
187- colorVar,
188- document.body.style.getPropertyValue(colorVar),
189- );
190- }
191- }
192168 }
193169 }, []);
194170
195171 useWebviewListener(
196172 "jetbrains/setColors",
197173 async (data) => {
198- Object.entries(data).forEach(([key, value]) => {
199- document.body.style.setProperty(key, value);
200- document.documentElement.style.setProperty(key, value);
201- });
174+ setDocumentStylesFromTheme(data);
202175 },
203176 [],
204177 );
modified gui/src/pages/config/HelpCenterSection.tsx +12 −0
@@ -1,6 +1,7 @@
11 import {
22 ArrowTopRightOnSquareIcon,
33 DocumentArrowUpIcon,
4+ PaintBrushIcon,
45 TableCellsIcon,
56 } from "@heroicons/react/24/outline";
67 import { useContext } from "react";
@@ -9,6 +10,7 @@
910 import { useAppDispatch } from "../../redux/hooks";
1011 import { setOnboardingCard } from "../../redux/slices/uiSlice";
1112 import { saveCurrentSession } from "../../redux/thunks/session";
13+import { ROUTES } from "../../util/navigation";
1214 import MoreHelpRow from "./MoreHelpRow";
1315
1416 export function HelpCenterSection() {
@@ -83,6 +85,16 @@
8385 ideMessenger.post("showTutorial", undefined);
8486 }}
8587 />
88+ {process.env.NODE_ENV === "development" && (
89+ <MoreHelpRow
90+ title="Theme Test Page"
91+ description="Development page for testing themes"
92+ Icon={PaintBrushIcon}
93+ onClick={async () => {
94+ navigate(ROUTES.THEME);
95+ }}
96+ />
97+ )}
8698 </div>
8799 </div>
88100 );
modified gui/src/pages/config/KeyboardShortcuts.tsx +1 −1
@@ -11,7 +11,7 @@
1111 function KeyboardShortcut(props: KeyboardShortcutProps) {
1212 return (
1313 <div
14- className={`flex flex-col items-start p-2 py-2 sm:flex-row sm:items-center ${props.isEven ? "" : "bg-table-odd-rows"}`}
14+ className={`flex flex-col items-start p-2 py-2 sm:flex-row sm:items-center ${props.isEven ? "" : "bg-table-oddRow"}`}
1515 >
1616 <div className="w-full flex-grow pb-1 pr-4 sm:w-auto sm:pb-0">
1717 <span className="block break-words text-xs">{props.description}:</span>
modified gui/src/pages/gui/StreamError.tsx +86 −47
@@ -1,12 +1,15 @@
11 import {
22 ArrowTopRightOnSquareIcon,
3- Cog8ToothIcon,
3+ ClipboardIcon,
4+ Cog6ToothIcon,
5+ KeyIcon,
46 } from "@heroicons/react/24/outline";
57 import { DISCORD_LINK, GITHUB_LINK } from "core/util/constants";
68 import { useContext, useMemo } from "react";
7-import { Button, SecondaryButton } from "../../components";
9+import { GhostButton, SecondaryButton } from "../../components";
810 import { DiscordIcon } from "../../components/svg/DiscordIcon";
911 import { GithubIcon } from "../../components/svg/GithubIcon";
12+import ToggleDiv from "../../components/ToggleDiv";
1013 import { useAuth } from "../../context/Auth";
1114 import { IdeMessengerContext } from "../../context/IdeMessenger";
1215 import { selectSelectedProfile } from "../../redux/";
@@ -48,11 +51,15 @@
4851 );
4952
5053 const handleRefreshProfiles = () => {
51- refreshProfiles();
54+ void refreshProfiles();
5255 dispatch(setShowDialog(false));
5356 dispatch(setDialogMessage(undefined));
5457 };
5558
59+ const copyErrorToClipboard = () => {
60+ void navigator.clipboard.writeText(parsedError);
61+ };
62+
5663 // Collect model information to display useful error info
5764 let modelTitle = "Chat model";
5865 let providerName = "the model provider";
@@ -99,30 +106,29 @@
99106 }
100107
101108 const checkKeysButton = apiKeyUrl ? (
102- <Button
103- className="cursor-pointer hover:underline"
109+ <GhostButton
110+ className="flex items-center"
104111 onClick={() => {
105112 ideMessenger.post("openUrl", apiKeyUrl!);
106113 }}
107114 >
108- Check keys/usage
109- </Button>
115+ <KeyIcon className="mr-1.5 h-3.5 w-3.5" />
116+ <span>View key</span>
117+ </GhostButton>
110118 ) : null;
111119
112120 const configButton = (
113- <SecondaryButton
114- className="flex flex-row items-center gap-1.5 hover:underline hover:opacity-70"
121+ <GhostButton
122+ className="flex items-center"
115123 onClick={() => {
116124 ideMessenger.post("config/openProfile", {
117125 profileId: undefined,
118126 });
119127 }}
120128 >
121- <div>
122- <Cog8ToothIcon className="h-4 w-4" />
123- </div>
124- <span>Open Assistant configuration</span>
125- </SecondaryButton>
129+ <Cog6ToothIcon className="mr-1.5 h-3.5 w-3.5" />
130+ <span>View config</span>
131+ </GhostButton>
126132 );
127133
128134 if (
@@ -131,7 +137,20 @@
131137 return <ModelsAddOnLimitDialog />;
132138 }
133139
134- let errorContent: React.ReactNode = <></>;
140+ let errorContent = (
141+ <div className="mb-3 mt-1">
142+ <div className="m-0 p-0">
143+ <p className="m-0 mb-2 p-0">
144+ There was an error handling the response from{" "}
145+ {selectedModel?.title || "the model"}.
146+ </p>
147+ <p className="m-0 p-0">
148+ Please try to submit your message again, and if the error persists,
149+ let us know by reporting the issue using the buttons below.
150+ </p>
151+ </div>
152+ </div>
153+ );
135154
136155 // Display components for specific errors
137156 if (statusCode === 429) {
@@ -141,7 +160,7 @@
141160 {`This might mean your ${modelTitle} usage has been rate limited
142161 by ${providerName}.`}
143162 </span>
144- <div className="flex flex-row flex-wrap gap-2">
163+ <div className="flex flex-row flex-wrap justify-start gap-3 py-4">
145164 {checkKeysButton}
146165 {configButton}
147166 </div>
@@ -230,51 +249,71 @@
230249 );
231250 }
232251
252+ console.log({ message });
253+
233254 return (
234- <div className={`flex flex-col gap-1 px-3 pb-2 pt-3`}>
235- <p className="m-0 p-0 text-lg text-red-500">
236- {statusCode ? `Error (status code ${statusCode})` : "Error"}
237- </p>
238-
239- {message ? (
240- <div className="mt-2 flex flex-col gap-0 rounded-sm">
241- <code className="max-h-20 overflow-y-auto p-2 font-mono">
242- {parsedError}
243- </code>
244- <div
245- className="flex cursor-pointer flex-row items-center justify-end px-1 py-1 text-gray-500 hover:underline"
246- onClick={() => {
247- ideMessenger.post("toggleDevTools", undefined);
248- }}
249- >
250- <span className="px-2">View Logs</span>
251- <ArrowTopRightOnSquareIcon className="h-4 w-4" />
252- </div>
255+ <div className="flex flex-col gap-4 px-3 pb-3 pt-3">
256+ {/* Concise error title */}
257+ <h3 className="text-error m-0 p-0 text-lg font-medium">
258+ Error handling model response
259+ </h3>
260+
261+ {errorContent}
262+
263+ {/* Expandable technical details using ToggleDiv */}
264+ {message && (
265+ <div className="mb-2">
266+ <ToggleDiv title="View error output" testId="error-output-toggle">
267+ <div className="flex flex-col gap-0 rounded-sm">
268+ <code className="text-editor-foreground block max-h-48 overflow-y-auto p-3 font-mono text-xs">
269+ {parsedError}
270+ </code>
271+
272+ <div className="flex flex-row items-center justify-end gap-2 p-2">
273+ <GhostButton
274+ onClick={copyErrorToClipboard}
275+ className="flex items-center"
276+ >
277+ <ClipboardIcon className="mr-1.5 h-3.5 w-3.5" />
278+ <span>Copy output</span>
279+ </GhostButton>
280+
281+ <GhostButton
282+ onClick={() => {
283+ ideMessenger.post("toggleDevTools", undefined);
284+ }}
285+ className="flex items-center"
286+ >
287+ <ArrowTopRightOnSquareIcon className="mr-1.5 h-4 w-4" />
288+ <span className="text-xs">View Logs</span>
289+ </GhostButton>
290+ </div>
291+ </div>
292+ </ToggleDiv>
253293 </div>
254- ) : null}
255- <div className="mt-3">{errorContent}</div>
256-
257- <div className="mt-2 flex flex-col gap-1.5">
258- <span>Report this error:</span>
259- <div className="flex flex-row flex-wrap items-center gap-2">
260- <SecondaryButton
261- className="flex flex-row items-center gap-2 hover:opacity-70"
294+ )}
295+
296+ <div>
297+ <span className="text-base font-medium">Report this error</span>
298+ <div className="mt-2 flex flex-row flex-wrap items-center gap-2">
299+ <GhostButton
300+ className="flex flex-row items-center gap-2 rounded px-3 py-1.5"
262301 onClick={() => {
263302 ideMessenger.post("openUrl", GITHUB_LINK);
264303 }}
265304 >
266305 <GithubIcon className="h-5 w-5" />
267306 <span className="xs:flex hidden">Github</span>
268- </SecondaryButton>
269- <SecondaryButton
270- className="flex flex-row items-center gap-2 hover:opacity-70"
307+ </GhostButton>
308+ <GhostButton
309+ className="flex flex-row items-center gap-2 rounded px-3 py-1.5"
271310 onClick={() => {
272311 ideMessenger.post("openUrl", DISCORD_LINK);
273312 }}
274313 >
275314 <DiscordIcon className="h-5 w-5" />
276315 <span className="xs:flex hidden">Discord</span>
277- </SecondaryButton>
316+ </GhostButton>
278317 </div>
279318 </div>
280319 </div>
added gui/src/styles/ThemePage.tsx +232 −0
@@ -0,0 +1,232 @@
1+import {
2+ CheckCircleIcon,
3+ ExclamationCircleIcon,
4+ ExclamationTriangleIcon,
5+} from "@heroicons/react/24/outline";
6+import { useContext, useEffect, useMemo, useState } from "react";
7+import { useNavigate } from "react-router-dom";
8+import { Button } from "../components";
9+import { IdeMessengerContext } from "../context/IdeMessenger";
10+import { isJetBrains } from "../util";
11+import { ROUTES } from "../util/navigation";
12+import {
13+ clearThemeLocalCache,
14+ setDocumentStylesFromTheme,
15+ THEME_COLORS,
16+ varWithFallback,
17+} from "./theme";
18+
19+const ThemeTailwindClassExample = ({
20+ colorName,
21+ varNames,
22+ defaultColor,
23+ isMissing,
24+}: {
25+ colorName: string;
26+ varNames: string[];
27+ defaultColor: string;
28+ isMissing?: boolean;
29+}) => {
30+ return (
31+ <>
32+ <div className={`line-clamp-1 break-all px-2 text-right`}>
33+ {colorName}
34+ </div>
35+ <div
36+ className={`line-clamp-1 break-all p-1 text-[9px] ${isMissing ? "text-error" : ""}`}
37+ style={{
38+ backgroundColor: varWithFallback(
39+ colorName as keyof typeof THEME_COLORS,
40+ ),
41+ }}
42+ >
43+ {varNames.join(", ")}
44+ </div>
45+ <div
46+ className={`line-clamp-1 break-all p-1 text-[9px]`}
47+ style={{
48+ backgroundColor: defaultColor,
49+ }}
50+ >
51+ {defaultColor}
52+ </div>
53+ </>
54+ );
55+};
56+
57+function ThemePage() {
58+ const navigate = useNavigate();
59+ const [listToggled, setListToggled] = useState(false);
60+ const ideMessenger = useContext(IdeMessengerContext);
61+ const jetbrains = useMemo(() => {
62+ return isJetBrains();
63+ }, []);
64+
65+ const [missingVars, setMissingVars] = useState<string[]>([]);
66+ const refreshColors = () => {
67+ if (jetbrains) {
68+ // Jetbrains: get colors and check which ones are missing from theme
69+ void ideMessenger
70+ .request("jetbrains/getColors", undefined)
71+ .then((result) => {
72+ console.log(result);
73+ if (result.status === "success") {
74+ const missingColors = setDocumentStylesFromTheme(result.content);
75+ setMissingVars(missingColors);
76+ }
77+ });
78+ } else {
79+ // VS Code: find actual missing CSS variables
80+ const notFound: string[] = [];
81+ Object.entries(THEME_COLORS).forEach(([colorName, themeVals], idx) => {
82+ let found = false;
83+ themeVals.vars.forEach((cssVar) => {
84+ const value = getComputedStyle(
85+ document.documentElement,
86+ ).getPropertyValue(cssVar);
87+ if (!value) {
88+ notFound.push(`cssVar (choice #${idx + 1} for color ${colorName}`);
89+ }
90+ });
91+ });
92+ setMissingVars(notFound);
93+ }
94+ };
95+
96+ useEffect(() => {
97+ refreshColors();
98+ }, []);
99+
100+ return (
101+ <div className="flex flex-1 flex-col gap-3 px-2 py-2">
102+ <span
103+ className="flex cursor-pointer flex-row items-center gap-2"
104+ onClick={() => navigate(ROUTES.HOME)}
105+ >
106+ <span className="">←</span>
107+ Back to Chat
108+ </span>
109+ <h2 className="mb-2 mt-0 p-0 text-center text-xl font-semibold">
110+ Theme Tester
111+ </h2>
112+ <div className="bg-background border-border grid grid-cols-1 gap-4 rounded-md border border-solid p-4 md:grid-cols-2">
113+ <div className="col-span-2 flex gap-4">
114+ <p className="">Normal text</p>
115+ <p className="text-description">Description text</p>
116+ <p className="text-description-muted">Muted text</p>
117+ </div>
118+
119+ <button className="bg-primary text-primary-foreground hover:bg-primary-hover cursor-pointer rounded border-none px-4 py-2 disabled:cursor-not-allowed disabled:brightness-75">
120+ Primary Button
121+ </button>
122+ <button className="bg-secondary text-secondary-foreground hover:bg-secondary-hover cursor-pointer rounded border-none px-4 py-2 disabled:cursor-not-allowed disabled:brightness-75">
123+ Secondary Button
124+ </button>
125+
126+ <div className="border-border rounded-md border border-solid p-3">
127+ Normal border
128+ </div>
129+
130+ <div className="border-border-focus rounded-md border border-solid p-3">
131+ Focus border
132+ </div>
133+
134+ <input
135+ className="bg-input text-input-foreground border-input-border placeholder:text-input-placeholder focus:border-border-focus rounded-md border border-solid p-2 focus:outline-none"
136+ placeholder="Input example"
137+ />
138+
139+ <div className="bg-badge text-badge-foreground border-border inline-block rounded-full border border-solid p-2">
140+ <span className="px-2">Badge</span>
141+ </div>
142+
143+ <div className="flex items-center gap-2">
144+ <CheckCircleIcon className="text-success h-4 w-4" />
145+ <span className="text-success">Success</span>
146+ </div>
147+ <div className="flex items-center gap-2">
148+ <ExclamationCircleIcon className="text-warning h-4 w-4" />
149+ <span className="text-warning">Warning</span>
150+ </div>
151+ <div className="flex items-center gap-2">
152+ <ExclamationTriangleIcon className="text-error h-4 w-4" />
153+ <span className="text-error">Error</span>
154+ </div>
155+
156+ <div
157+ onClick={() => setListToggled(!listToggled)}
158+ className={`cursor-pointer p-2 ${listToggled ? "bg-list-active text-list-active-foreground" : "bg-background text-foreground hover:bg-list-hover"}`}
159+ >
160+ List item (clickable)
161+ </div>
162+ <div className="bg-editor text-editor-foreground border-border rounded-sm border border-solid p-2">
163+ <span>Editor</span>
164+ </div>
165+ <table>
166+ <tbody>
167+ <tr>
168+ <td className="border-border border-b border-solid p-2">
169+ <span>even table row</span>
170+ </td>
171+ </tr>
172+ <tr className="bg-table-oddRow">
173+ <td className="border-border border-b border-solid p-2">
174+ <span>odd table row</span>
175+ </td>
176+ </tr>
177+ </tbody>
178+ </table>
179+ <div>
180+ <span className="text-link">Link</span>
181+ </div>
182+ <div className="flex items-center gap-2">
183+ <span className="bg-findMatch">find match</span>
184+ <span className="bg-findMatch-selected">current match</span>
185+ </div>
186+ <div className="flex items-center gap-2">
187+ <span className="">Accent</span>
188+ <div className="bg-accent h-3 w-3" />
189+ </div>
190+ </div>
191+ <h2 className="mb-2 mt-6 text-xl font-semibold">Manage Theme</h2>
192+ <h2 className="mb-2 text-lg font-semibold">Missing Theme Colors</h2>
193+ {missingVars.length > 0 ? (
194+ <div className="flex flex-col gap-1">
195+ {missingVars.map((varName) => (
196+ <div key={varName} className="">
197+ {varName}
198+ </div>
199+ ))}
200+ </div>
201+ ) : (
202+ <div className="">No missing variables</div>
203+ )}
204+ <Button onClick={refreshColors}>Refresh Missing Colors</Button>
205+ {jetbrains ? (
206+ <Button onClick={clearThemeLocalCache}>Clear Theme Cache</Button>
207+ ) : null}
208+ <h2 className="mb-2 mt-6 text-xl font-semibold">All Theme Colors</h2>
209+ <div className="grid grid-cols-3">
210+ <div className="p-1">
211+ <span className="font-bold">Theme Color</span>
212+ </div>
213+ <div className="p-1">
214+ <span className="font-bold">CSS Var</span>
215+ </div>
216+ <div className="p-1">
217+ <span className="font-bold">Default</span>
218+ </div>
219+ {Object.entries(THEME_COLORS).map(([colorName, val]) => (
220+ <ThemeTailwindClassExample
221+ isMissing={missingVars.includes(colorName)}
222+ key={colorName}
223+ colorName={colorName}
224+ defaultColor={val.default}
225+ varNames={val.vars}
226+ />
227+ ))}
228+ </div>
229+ </div>
230+ );
231+}
232+export default ThemePage;
added gui/src/styles/theme.test.ts +24 −0
@@ -0,0 +1,24 @@
1+import { getRecursiveVar } from "./theme";
2+
3+test("getRecursiveVar returns single var with default for one variable", () => {
4+ const vars = ["--test-var"];
5+ const defaultColor = "#ffffff";
6+ const result = getRecursiveVar(vars, defaultColor);
7+ expect(result).toBe("var(--test-var, #ffffff)");
8+});
9+
10+test("getRecursiveVar returns nested vars in correct order for multiple variables", () => {
11+ const vars = ["--first-var", "--second-var", "--third-var"];
12+ const defaultColor = "#000000";
13+ const result = getRecursiveVar(vars, defaultColor);
14+ expect(result).toBe(
15+ "var(--first-var, var(--second-var, var(--third-var, #000000)))",
16+ );
17+});
18+
19+test("getRecursiveVar handles empty vars array", () => {
20+ const vars: string[] = [];
21+ const defaultColor = "#123456";
22+ const result = getRecursiveVar(vars, defaultColor);
23+ expect(result).toBe("#123456");
24+});
added gui/src/styles/theme.ts +271 −0
@@ -0,0 +1,271 @@
1+// All vscode variables https://gist.github.com/estruyf/ba49203e1a7d6868e9320a4ea480c27a
2+// Examples for vscode https://github.com/githubocto/tailwind-vscode/blob/main/index.js
3+
4+// The current default theme is dark with blue accents
5+export const THEME_COLORS = {
6+ background: {
7+ vars: [
8+ "--vscode-sideBar-background",
9+ "--vscode-editor-background",
10+ "--vscode-panel-background",
11+ ],
12+ default: "#1e1e1e", // dark gray
13+ },
14+ foreground: {
15+ vars: [
16+ "--vscode-sideBar-foreground",
17+ "--vscode-editor-foreground",
18+ "--vscode-panel-foreground",
19+ ],
20+ default: "#e6e6e6", // light gray
21+ },
22+ "editor-background": {
23+ vars: ["--vscode-editor-background"],
24+ default: "#1e1e1e", // dark gray
25+ },
26+ "editor-foreground": {
27+ vars: ["--vscode-editor-foreground"],
28+ default: "#e6e6e6", // light gray
29+ },
30+ "primary-background": {
31+ vars: ["--vscode-button-background"],
32+ default: "#2c5aa0", // medium blue
33+ },
34+ "primary-foreground": {
35+ vars: ["--vscode-button-foreground"],
36+ default: "#ffffff", // white
37+ },
38+ "primary-hover": {
39+ vars: ["--vscode-button-hoverBackground"],
40+ default: "#3a6db3", // lighter blue
41+ },
42+ "secondary-background": {
43+ vars: ["--vscode-button-secondaryBackground"],
44+ default: "#303030", // medium dark gray
45+ },
46+ "secondary-foreground": {
47+ vars: ["--vscode-button-secondaryForeground"],
48+ default: "#e6e6e6", // light gray
49+ },
50+ "secondary-hover": {
51+ vars: ["--vscode-button-secondaryHoverBackground"],
52+ default: "#3a3a3a", // medium gray
53+ },
54+ border: {
55+ vars: ["--vscode-sideBar-border", "--vscode-panel-border"],
56+ default: "#2a2a2a", // dark gray border
57+ },
58+ "border-focus": {
59+ vars: ["--vscode-focusBorder"],
60+ default: "#3a6db3", // lighter blue
61+ },
62+ // Command styles are used for tip-tap editor
63+ "command-background": {
64+ vars: ["--vscode-commandCenter-background"],
65+ default: "#252525", // dark gray
66+ },
67+ "command-foreground": {
68+ vars: ["--vscode-commandCenter-foreground"],
69+ default: "#e6e6e6", // light gray
70+ },
71+ "command-border": {
72+ vars: ["--vscode-commandCenter-inactiveBorder"],
73+ default: "#555555", // medium gray
74+ },
75+ "command-border-focus": {
76+ vars: ["--vscode-commandCenter-activeBorder"],
77+ default: "#4d8bf0", // bright blue
78+ },
79+ description: {
80+ vars: ["--vscode-descriptionForeground"],
81+ default: "#b3b3b3", // medium light gray
82+ },
83+ "description-muted": {
84+ vars: ["--vscode-list-deemphasizedForeground"],
85+ default: "#8c8c8c", // medium gray
86+ },
87+ "input-background": {
88+ vars: ["--vscode-input-background"],
89+ default: "#2d2d2d", // dark gray
90+ },
91+ "input-foreground": {
92+ vars: ["--vscode-input-foreground"],
93+ default: "#e6e6e6", // light gray
94+ },
95+ "input-border": {
96+ vars: [
97+ "--vscode-input-border",
98+ "--vscode-commandCenter-inactiveBorder",
99+ "vscode-border",
100+ ],
101+ default: "#555555", // medium gray
102+ },
103+ "input-placeholder": {
104+ vars: ["--vscode-input-placeholderForeground"],
105+ default: "#9e9e9e", // medium light gray
106+ },
107+ "table-oddRow": {
108+ vars: ["--vscode-tree-tableOddRowsBackground"],
109+ default: "#2d2d2d", // dark gray
110+ },
111+ "badge-background": {
112+ vars: ["--vscode-badge-background"],
113+ default: "#4d4d4d", // medium dark gray
114+ },
115+ "badge-foreground": {
116+ vars: ["--vscode-badge-foreground"],
117+ default: "#ffffff", // white
118+ },
119+ success: {
120+ vars: [
121+ "--vscode-notebookStatusSuccessIcon-foreground",
122+ "--vscode-testing-iconPassed",
123+ "--vscode-gitDecoration-addedResourceForeground",
124+ "--vscode-charts-green",
125+ ],
126+ default: "#4caf50", // green
127+ },
128+ warning: {
129+ vars: [
130+ "--vscode-editorWarning-foreground",
131+ "--vscode-list-warningForeground",
132+ ],
133+ default: "#ffb74d", // amber/yellow
134+ },
135+ error: {
136+ vars: ["--vscode-editorError-foreground", "--vscode-list-errorForeground"],
137+ default: "#f44336", // red
138+ },
139+ link: {
140+ vars: ["--vscode-textLink-foreground"],
141+ default: "#5c9ce6", // medium blue
142+ },
143+ accent: {
144+ vars: ["--vscode-tab-activeBorderTop", "--vscode-focusBorder"],
145+ default: "#4d8bf0", // bright blue
146+ },
147+ "find-match": {
148+ vars: ["--vscode-editor-findMatchBackground"], // Can't get "var(--vscode-editor-findMatchBackground, rgba(237, 18, 146, 0.5))" to work
149+ default: "#264f7840", // translucent blue
150+ },
151+ "find-match-selected": {
152+ vars: ["--vscode-editor-findMatchHighlightBackground"],
153+ default: "#ffb74d40", // translucent amber
154+ },
155+ "list-hover": {
156+ // --vscode-tab-hoverBackground
157+ vars: ["--vscode-list-hoverBackground"],
158+ default: "#383838", // medium dark gray
159+ },
160+ "list-active": {
161+ vars: ["--vscode-list-activeSelectionBackground"],
162+ default: "#2c5aa050", // translucent medium blue
163+ },
164+ "list-active-foreground": {
165+ vars: ["--vscode-list-activeSelectionForeground"],
166+ default: "#ffffff", // white
167+ },
168+};
169+
170+// TODO: add fonts - GUI fonts in jetbrains differ from IDE:
171+// --vscode-editor-font-family;
172+// --vscode-font-family;
173+export const THEME_CSS_VARS = Object.values(THEME_COLORS)
174+ .map((value) => value.vars)
175+ .flat();
176+
177+export const THEME_CSS_VAR_DEFAULTS = Object.entries(THEME_COLORS).reduce(
178+ (acc, [_, value]) => {
179+ value.vars.forEach((varName) => {
180+ acc[varName] = value.default;
181+ });
182+ return acc;
183+ },
184+ {} as Record<string, string>,
185+);
186+
187+export const THEME_DEFAULTS = Object.entries(THEME_COLORS).reduce(
188+ (acc, [key, value]) => {
189+ acc[key] = value.default;
190+ return acc;
191+ },
192+ {} as Record<string, string>,
193+);
194+
195+// Generates recursive CSS variable fallback for a given color name
196+// e.g. var(--vscode-button-background, var(--vscode-button-foreground, #ffffff))
197+export const getRecursiveVar = (vars: string[], defaultColor: string) => {
198+ return [...vars].reverse().reduce((curr, varName) => {
199+ return `var(${varName}, ${curr})`;
200+ }, defaultColor);
201+};
202+
203+export const varWithFallback = (colorName: keyof typeof THEME_COLORS) => {
204+ const themeVals = THEME_COLORS[colorName];
205+ if (!themeVals) {
206+ throw new Error(`Invalid theme color name ${colorName}`);
207+ }
208+ return getRecursiveVar(themeVals.vars, themeVals.default);
209+};
210+
211+export const setDocumentStylesFromTheme = (
212+ theme: Record<string, string | undefined | null>,
213+) => {
214+ // Check for extraneous theme items
215+ Object.entries(theme).forEach(([colorName, value]) => {
216+ const themeVals = THEME_COLORS[colorName as keyof typeof THEME_COLORS];
217+ if (!themeVals) {
218+ console.warn(
219+ `Receieved theme color ${colorName} which is not used by the theme`,
220+ );
221+ return;
222+ }
223+ });
224+
225+ // Write theme values to document
226+ const missingColors: string[] = [];
227+ Object.entries(THEME_COLORS).forEach(([colorName, settings]) => {
228+ let colorVal = settings.default;
229+ const newColor = theme[colorName];
230+ if (newColor) {
231+ colorVal = newColor;
232+ // Remove alpha channel from all hex colors (seems to cause bad colors)
233+ if (newColor.startsWith("#") && newColor.length > 7) {
234+ colorVal = colorVal.slice(0, 7);
235+ }
236+ } else {
237+ missingColors.push(colorName);
238+ // console.warn(
239+ // `Missing theme color: ${colorName}. Falling back to default ${colorVal}`,
240+ // );
241+ }
242+
243+ localStorage.setItem(colorName, colorVal);
244+ for (const cssVar of settings.vars) {
245+ document.body.style.setProperty(cssVar, colorVal);
246+ document.documentElement.style.setProperty(cssVar, colorVal);
247+ }
248+ });
249+
250+ return missingColors;
251+};
252+
253+export const setDocumentStylesFromLocalStorage = (checkCache: boolean) => {
254+ for (const [colorName, themeVals] of Object.entries(THEME_COLORS)) {
255+ for (const cssVar of themeVals.vars) {
256+ // Get cached values (for non-vscode IDEs)
257+ if (checkCache) {
258+ const cached = localStorage.getItem(colorName);
259+ if (cached) {
260+ document.body.style.setProperty(cssVar, cached);
261+ }
262+ }
263+ }
264+ }
265+};
266+
267+export const clearThemeLocalCache = () => {
268+ for (const colorName of Object.keys(THEME_COLORS)) {
269+ localStorage.removeItem(colorName);
270+ }
271+};
added gui/src/styles/utils.ts +45 −0
@@ -0,0 +1,45 @@
1+export function parseHexColor(hexColor: string): {
2+ r: number;
3+ g: number;
4+ b: number;
5+} {
6+ if (hexColor.startsWith("#")) {
7+ hexColor = hexColor.slice(1);
8+ }
9+
10+ if (hexColor.length > 6) {
11+ hexColor = hexColor.slice(0, 6);
12+ }
13+
14+ const r = parseInt(hexColor.substring(0, 2), 16);
15+ const g = parseInt(hexColor.substring(2, 4), 16);
16+ const b = parseInt(hexColor.substring(4, 6), 16);
17+
18+ return { r, g, b };
19+}
20+
21+export function parseColorForHex(colorVar: string): string {
22+ const value = getComputedStyle(document.documentElement).getPropertyValue(
23+ colorVar,
24+ );
25+ if (value.startsWith("#")) {
26+ return value.slice(0, 7);
27+ }
28+
29+ // Parse rgb/rgba
30+ const rgbValues = value
31+ .slice(value.startsWith("rgba") ? 5 : 4, -1)
32+ .split(",")
33+ .map((x) => x.trim())
34+ .filter((_, i) => i < 3) // Only take the first 3 values (RGB, ignore alpha)
35+ .map((x) => parseInt(x, 10));
36+
37+ let hex =
38+ "#" +
39+ rgbValues
40+ .map((x) => x.toString(16))
41+ .map((x) => (x.length === 1 ? "0" + x : x))
42+ .join("");
43+
44+ return hex;
45+}
modified gui/src/util/navigation.ts +1 −0
@@ -2,5 +2,6 @@
22 export const ROUTES = {
33 HOME: "/",
44 CONFIG: "/config",
5+ THEME: "/theme",
56 // EXAMPLE_ROUTE_WITH_PARAMS: (params: ParamsType) => `/route/${params}`,
67 };
modified gui/tailwind.config.cjs +69 −18
@@ -1,5 +1,6 @@
11 /** @type {import('tailwindcss').Config} */
22 const defaultTheme = require("tailwindcss/defaultTheme");
3+const { varWithFallback, THEME_COLORS } = require("./src/styles/theme");
34
45 module.exports = {
56 content: [
@@ -29,25 +30,75 @@
2930 default: "5px",
3031 },
3132 colors: {
32- lightgray: "#999998",
33- "vsc-input-background": "var(--vscode-input-background, rgb(45 45 45))",
34- "vsc-background": "var(--vscode-sideBar-background, rgb(30 30 30))",
35- "vsc-foreground": "var(--vscode-editor-foreground, #fff)",
36- "vsc-editor-background":
37- "var(--vscode-editor-background, var(--vscode-sideBar-background, rgb(30 30 30)))",
38- "vsc-input-border": "var(--vscode-input-border, #999998)",
39- "vsc-commandCenter-inactiveBorder":
40- "var(--vscode-commandCenter-inactiveBorder, #999998)",
33+ background: varWithFallback("background"),
34+ foreground: varWithFallback("foreground"),
35+ editor: {
36+ DEFAULT: varWithFallback("editor-background"),
37+ foreground: varWithFallback("editor-foreground"),
38+ },
39+ primary: {
40+ DEFAULT: varWithFallback("primary-background"),
41+ foreground: varWithFallback("primary-foreground"),
42+ hover: varWithFallback("primary-hover"),
43+ },
44+ secondary: {
45+ DEFAULT: varWithFallback("secondary-background"),
46+ foreground: varWithFallback("secondary-foreground"),
47+ hover: varWithFallback("secondary-hover"),
48+ },
49+ border: {
50+ DEFAULT: varWithFallback("border"),
51+ focus: varWithFallback("border-focus"),
52+ },
53+ command: {
54+ DEFAULT: varWithFallback("command-background"),
55+ foreground: varWithFallback("command-foreground"),
56+ border: {
57+ DEFAULT: varWithFallback("command-border"),
58+ focus: varWithFallback("command-border-focus"),
59+ },
60+ },
61+ description: {
62+ DEFAULT: varWithFallback("description"),
63+ muted: varWithFallback("description-muted"),
64+ },
65+ input: {
66+ DEFAULT: varWithFallback("input-background"),
67+ foreground: varWithFallback("input-foreground"),
68+ border: varWithFallback("input-border"),
69+ placeholder: varWithFallback("input-placeholder"),
70+ },
71+ table: {
72+ oddRow: varWithFallback("table-oddRow"),
73+ },
74+ badge: {
75+ DEFAULT: varWithFallback("badge-background"),
76+ foreground: varWithFallback("badge-foreground"),
77+ },
78+ success: varWithFallback("success"),
79+ warning: varWithFallback("warning"),
80+ error: varWithFallback("error"),
81+ link: varWithFallback("link"),
82+ accent: varWithFallback("accent"),
83+ findMatch: {
84+ DEFAULT: THEME_COLORS["find-match"].default,
85+ selected: varWithFallback("find-match-selected"),
86+ },
87+ list: {
88+ hover: varWithFallback("list-hover"),
89+ active: {
90+ DEFAULT: varWithFallback("list-active"),
91+ foreground: varWithFallback("list-active-foreground"),
92+ },
93+ },
4194
42- // Starting to make things less vsc-specific
43- // TODO make it all non-IDE-specific naming
44- "find-match-selected":
45- "var(--vscode-editor-findMatchHighlightBackground, rgba(255, 223, 0))",
46- "table-odd-rows":"var(--vscode-tree-tableOddRowsBackground, #1bbe84)",
47- "list-active": "var(--vscode-list-activeSelectionBackground, #1bbe84)",
48- "list-active-foreground":
49- "var(--vscode-quickInputList-focusForeground, var(--vscode-editor-foreground))",
50- badge: "var(--vscode-badge-background, #1bbe84)",
95+ // DEPRECATED, slowly remove usages of these ide-named or explicit colors
96+ lightgray: "#999998", // use border, description, or description-muted instead - AVOID
97+ "vsc-input-background": varWithFallback("input-background"), // use "input-background" instead
98+ "vsc-background": varWithFallback("background"), // use "background" instead
99+ "vsc-foreground": varWithFallback("editor-foreground"), // use "foreground" instead
100+ "vsc-editor-background": varWithFallback("editor-background"), // use "editor" instead
101+ "vsc-input-border": varWithFallback("input-border"), // use "input-border" instead
51102 },
52103 },
53104 },
modified packages/config-yaml/package-lock.json +2 −2
@@ -1,12 +1,12 @@
11 {
22 "name": "@continuedev/config-yaml",
3- "version": "1.0.87",
3+ "version": "1.0.88",
44 "lockfileVersion": 3,
55 "requires": true,
66 "packages": {
77 "": {
88 "name": "@continuedev/config-yaml",
9- "version": "1.0.87",
9+ "version": "1.0.88",
1010 "license": "Apache-2.0",
1111 "dependencies": {
1212 "@continuedev/config-types": "^1.0.14",
modified packages/config-yaml/package.json +1 −1
@@ -1,6 +1,6 @@
11 {
22 "name": "@continuedev/config-yaml",
3- "version": "1.0.87",
3+ "version": "1.0.88",
44 "description": "",
55 "main": "dist/index.js",
66 "types": "dist/index.d.ts",
modified packages/config-yaml/src/load/clientRender.ts +1 −0
@@ -160,6 +160,7 @@
160160 apiKeyLocation: z.string().optional(),
161161 apiBase: z.string().optional(),
162162 orgScopeId: z.string().nullable(),
163+ env: z.record(z.string(), z.any()).optional(),
163164 });
164165
165166 export type ContinueProperties = z.infer<typeof continuePropertiesSchema>;
modified packages/config-yaml/src/schemas/index.ts +4 −1
@@ -9,9 +9,12 @@
99 params: z.any().optional(),
1010 });
1111
12+// TODO: This should be a discriminated union by type
1213 const mcpServerSchema = z.object({
1314 name: z.string(),
14- command: z.string(),
15+ command: z.string().optional(),
16+ type: z.enum(["sse", "stdio"]).optional(),
17+ url: z.string().optional(),
1518 faviconUrl: z.string().optional(),
1619 args: z.array(z.string()).optional(),
1720 env: z.record(z.string()).optional(),
modified packages/openai-adapters/README.md +1 −1
@@ -64,7 +64,7 @@
6464 - [x] Vllm
6565 - [ ] Vertex AI
6666 - [x] Voyage AI
67-- [ ] WatsonX
67+- [x] WatsonX
6868 - [x] xAI
6969 - [x] Fireworks
7070 - [x] Moonshot
modified packages/openai-adapters/package.json +1 −1
@@ -1,6 +1,6 @@
11 {
22 "name": "@continuedev/openai-adapters",
3- "version": "1.0.21",
3+ "version": "1.0.26",
44 "description": "",
55 "main": "dist/index.js",
66 "types": "dist/index.d.ts",
added packages/openai-adapters/src/apis/WatsonX.ts +314 −0
@@ -0,0 +1,314 @@
1+import { streamSse } from "@continuedev/fetch";
2+import { OpenAI } from "openai/index";
3+import {
4+ ChatCompletion,
5+ ChatCompletionChunk,
6+ ChatCompletionCreateParamsNonStreaming,
7+ ChatCompletionCreateParamsStreaming,
8+ Completion,
9+ CompletionCreateParamsNonStreaming,
10+ CompletionCreateParamsStreaming,
11+} from "openai/resources/index";
12+import { ChatCompletionCreateParams } from "openai/src/resources/index.js";
13+import { WatsonXConfig } from "../types.js";
14+import { chatCompletion, customFetch } from "../util.js";
15+import {
16+ BaseLlmApi,
17+ CreateRerankResponse,
18+ FimCreateParamsStreaming,
19+ RerankCreateParams,
20+} from "./base.js";
21+
22+export class WatsonXApi implements BaseLlmApi {
23+ apiBase: string;
24+ apiVersion: string = "2023-05-29";
25+ projectId?: string;
26+ deploymentId?: string;
27+
28+ constructor(protected config: WatsonXConfig) {
29+ this.apiBase = config.apiBase ?? "https://us-south.ml.cloud.ibm.com";
30+ if (!this.apiBase.endsWith("/")) {
31+ this.apiBase += "/";
32+ }
33+ this.apiVersion = config.env.apiVersion ?? this.apiVersion;
34+ this.projectId = config.env.projectId;
35+ this.deploymentId = config.env.deploymentId;
36+ }
37+
38+ private async getHeaders(): Promise<Record<string, string>> {
39+ const bearer = await this.getBearerToken();
40+ return {
41+ "Content-Type": "application/json",
42+ Authorization: `Bearer ${bearer.token}`,
43+ };
44+ }
45+
46+ async getBearerToken(): Promise<{ token: string; expiration: number }> {
47+ if (this.apiBase?.includes("cloud.ibm.com")) {
48+ // watsonx SaaS
49+ const wxToken = (await (
50+ await customFetch(this.config.requestOptions)(
51+ `https://iam.cloud.ibm.com/identity/token?apikey=${this.config.apiKey}&grant_type=urn:ibm:params:oauth:grant-type:apikey`,
52+ {
53+ method: "POST",
54+ headers: {
55+ "Content-Type": "application/x-www-form-urlencoded",
56+ Accept: "application/json",
57+ },
58+ },
59+ )
60+ ).json()) as any;
61+ return {
62+ token: wxToken["access_token"],
63+ expiration: wxToken["expiration"],
64+ };
65+ } else {
66+ // watsonx Software
67+ if (!this.config.apiKey?.includes(":")) {
68+ // Using ZenApiKey auth
69+ return {
70+ token: this.config.apiKey ?? "",
71+ expiration: -1,
72+ };
73+ } else {
74+ // Using username/password auth
75+ const userPass = this.config.apiKey?.split(":");
76+ const wxToken = (await (
77+ await customFetch(this.config.requestOptions)(
78+ `${this.apiBase}/icp4d-api/v1/authorize`,
79+ {
80+ method: "POST",
81+ headers: {
82+ "Content-Type": "application/json",
83+ Accept: "application/json",
84+ },
85+ body: JSON.stringify({
86+ username: userPass[0],
87+ password: userPass[1],
88+ }),
89+ },
90+ )
91+ ).json()) as any;
92+ const wxTokenExpiry = (await (
93+ await customFetch(this.config.requestOptions)(
94+ `${this.apiBase}/usermgmt/v1/user/tokenExpiry`,
95+ {
96+ method: "GET",
97+ headers: {
98+ Accept: "application/json",
99+ Authorization: `Bearer ${wxToken["token"]}`,
100+ },
101+ },
102+ )
103+ ).json()) as any;
104+ return {
105+ token: wxToken["token"],
106+ expiration: wxTokenExpiry["exp"],
107+ };
108+ }
109+ }
110+ }
111+
112+ private getEndpoint(endpoint: string): string {
113+ return `${this.apiBase}ml/v1/${this.deploymentId ? `deployments/${this.deploymentId}/` : ""}text/${endpoint}_stream?version=${this.apiVersion}`;
114+ }
115+
116+ private _convertBody(oaiBody: ChatCompletionCreateParams) {
117+ const stopSequences = oaiBody.stop
118+ ? Array.isArray(oaiBody.stop)
119+ ? oaiBody.stop.filter((s) => s.trim() !== "")
120+ : [oaiBody.stop]
121+ : undefined;
122+
123+ const payload: any = {
124+ messages: oaiBody.messages,
125+ max_tokens: oaiBody.max_tokens ?? 1024,
126+ stop: stopSequences,
127+ frequency_penalty: oaiBody.frequency_penalty,
128+ presence_penalty: oaiBody.presence_penalty,
129+ };
130+
131+ if (!this.deploymentId) {
132+ payload.model_id = oaiBody.model;
133+ payload.project_id = this.projectId;
134+ }
135+
136+ if (oaiBody.temperature !== undefined) {
137+ payload.temperature = oaiBody.temperature;
138+ }
139+
140+ if (oaiBody.top_p !== undefined) {
141+ payload.top_p = oaiBody.top_p;
142+ }
143+
144+ if (oaiBody.tools) {
145+ payload.tools = oaiBody.tools;
146+ if (oaiBody.tool_choice) {
147+ payload.tool_choice = oaiBody.tool_choice;
148+ } else {
149+ payload.tool_choice_option = "auto";
150+ }
151+ }
152+
153+ return payload;
154+ }
155+
156+ async chatCompletionNonStream(
157+ body: ChatCompletionCreateParamsNonStreaming,
158+ signal: AbortSignal,
159+ ): Promise<ChatCompletion> {
160+ const generator = this.chatCompletionStream(
161+ {
162+ ...body,
163+ stream: true,
164+ },
165+ signal,
166+ );
167+
168+ let content = "";
169+ for await (const chunk of generator) {
170+ content += chunk.choices[0].delta.content ?? "";
171+ }
172+ return chatCompletion({
173+ content,
174+ model: body.model,
175+ });
176+ }
177+
178+ async *chatCompletionStream(
179+ body: ChatCompletionCreateParamsStreaming,
180+ signal: AbortSignal,
181+ ): AsyncGenerator<ChatCompletionChunk, any, unknown> {
182+ const url = this.getEndpoint("chat");
183+ const headers = await this.getHeaders();
184+ const stringifiedBody = JSON.stringify(this._convertBody(body));
185+ const response = await customFetch(this.config.requestOptions)(url, {
186+ method: "POST",
187+ headers,
188+ body: stringifiedBody,
189+ signal,
190+ });
191+
192+ if (!response.ok || !response.body) {
193+ throw new Error(
194+ `Failed to stream chat completion: ${await response.text()}`,
195+ );
196+ }
197+
198+ for await (const value of streamSse(response as any)) {
199+ if (!value.choices?.[0]) {
200+ continue;
201+ }
202+ yield value;
203+ }
204+ }
205+
206+ async completionNonStream(
207+ body: CompletionCreateParamsNonStreaming,
208+ signal: AbortSignal,
209+ ): Promise<Completion> {
210+ throw new Error("Method not implemented.");
211+ }
212+
213+ async *completionStream(
214+ body: CompletionCreateParamsStreaming,
215+ signal: AbortSignal,
216+ ): AsyncGenerator<Completion, any, unknown> {
217+ const params = {
218+ decoding_method: body.temperature ? "sample" : "greedy",
219+ max_new_tokens: body.max_tokens ?? 1024,
220+ min_new_tokens: 1,
221+ stop_sequences: body.stop
222+ ? Array.isArray(body.stop)
223+ ? body.stop
224+ : [body.stop]
225+ : [],
226+ include_stop_sequence: false,
227+ repetition_penalty: body.frequency_penalty || 1,
228+ temperature: body.temperature,
229+ top_p: body.top_p,
230+ top_k: 100,
231+ };
232+
233+ const payload: any = {
234+ input: body.prompt,
235+ parameters: params,
236+ };
237+
238+ if (!this.deploymentId) {
239+ payload.model_id = body.model;
240+ payload.project_id = this.projectId;
241+ }
242+
243+ const url = this.getEndpoint("generation");
244+ const response = await customFetch(this.config.requestOptions)(url, {
245+ method: "POST",
246+ headers: await this.getHeaders(),
247+ body: JSON.stringify(payload),
248+ signal,
249+ });
250+
251+ if (!response.ok || !response.body) {
252+ throw new Error(`Failed to stream completion: ${await response.text()}`);
253+ }
254+
255+ let generatedText = "";
256+ for await (const value of streamSse(response as any)) {
257+ const lines = value.toString().split("\n");
258+ let generatedChunk = "";
259+
260+ lines.forEach((line: string) => {
261+ if (line.startsWith("data:")) {
262+ const dataStr = line.replace(/^data:\s+/, "");
263+ try {
264+ const data = JSON.parse(dataStr);
265+ data.results.forEach((result: any) => {
266+ generatedChunk += result.generated_text || "";
267+ });
268+ } catch (e) {
269+ // parsing error is expected with streaming response
270+ }
271+ }
272+ });
273+
274+ if (generatedChunk) {
275+ generatedText += generatedChunk;
276+ yield {
277+ id: `watsonx-${Date.now()}`,
278+ object: "text_completion",
279+ created: Date.now(),
280+ model: body.model,
281+ choices: [
282+ {
283+ text: generatedChunk,
284+ index: 0,
285+ logprobs: null,
286+ finish_reason: "stop",
287+ },
288+ ],
289+ };
290+ }
291+ }
292+ }
293+
294+ async *fimStream(
295+ body: FimCreateParamsStreaming,
296+ signal: AbortSignal,
297+ ): AsyncGenerator<ChatCompletionChunk, any, unknown> {
298+ throw new Error("Method not implemented.");
299+ }
300+
301+ async embed(
302+ body: OpenAI.Embeddings.EmbeddingCreateParams,
303+ ): Promise<OpenAI.Embeddings.CreateEmbeddingResponse> {
304+ throw new Error("Method not implemented.");
305+ }
306+
307+ async rerank(body: RerankCreateParams): Promise<CreateRerankResponse> {
308+ throw new Error("Method not implemented.");
309+ }
310+
311+ async list(): Promise<OpenAI.Models.Model[]> {
312+ throw new Error("Method not implemented.");
313+ }
314+}
modified packages/openai-adapters/src/index.ts +8 −3
@@ -11,6 +11,7 @@
1111 import { MoonshotApi } from "./apis/Moonshot.js";
1212 import { OpenAIApi } from "./apis/OpenAI.js";
1313 import { RelaceApi } from "./apis/Relace.js";
14+import { WatsonXApi } from "./apis/WatsonX.js";
1415 import { BaseLlmApi } from "./apis/base.js";
1516 import { LLMConfig, OpenAIConfigSchema } from "./types.js";
1617
@@ -48,6 +49,8 @@
4849 return new RelaceApi(config);
4950 case "inception":
5051 return new InceptionApi(config);
52+ case "watsonx":
53+ return new WatsonXApi(config);
5154 case "x-ai":
5255 return openAICompatible("https://api.x.ai/v1/", config);
5356 case "voyage":
@@ -75,7 +78,10 @@
7578 case "nvidia":
7679 return openAICompatible("https://integrate.api.nvidia.com/v1/", config);
7780 case "ovhcloud":
78- return openAICompatible("https://oai.endpoints.kepler.ai.cloud.ovh.net/v1/", config);
81+ return openAICompatible(
82+ "https://oai.endpoints.kepler.ai.cloud.ovh.net/v1/",
83+ config,
84+ );
7985 case "scaleway":
8086 return openAICompatible("https://api.scaleway.ai/v1/", config);
8187 case "fireworks":
@@ -111,10 +117,9 @@
111117 type Completion,
112118 type CompletionCreateParams,
113119 type CompletionCreateParamsNonStreaming,
114- type CompletionCreateParamsStreaming
120+ type CompletionCreateParamsStreaming,
115121 } from "openai/resources/index";
116122
117123 // export
118124 export type { BaseLlmApi } from "./apis/base.js";
119125 export type { LLMConfig } from "./types.js";
120-
modified packages/openai-adapters/src/test/main.test.ts +1 −0
@@ -10,6 +10,7 @@
1010 provider: config.provider as any,
1111 apiKey: config.apiKey,
1212 apiBase: config.apiBase,
13+ env: config.env,
1314 });
1415
1516 if (false) {
modified packages/openai-adapters/src/types.ts +12 −0
@@ -99,6 +99,17 @@
9999 });
100100 export type AnthropicConfig = z.infer<typeof AnthropicConfigSchema>;
101101
102+export const WatsonXConfigSchema = BasePlusConfig.extend({
103+ provider: z.literal("watsonx"),
104+ apiKey: z.string(),
105+ env: z.object({
106+ apiVersion: z.string().optional(),
107+ projectId: z.string().optional(),
108+ deploymentId: z.string().optional(),
109+ }),
110+});
111+export type WatsonXConfig = z.infer<typeof WatsonXConfigSchema>;
112+
102113 export const JinaConfigSchema = OpenAIConfigSchema.extend({
103114 provider: z.literal("jina"),
104115 });
@@ -118,6 +129,7 @@
118129 AzureConfigSchema,
119130 GeminiConfigSchema,
120131 AnthropicConfigSchema,
132+ WatsonXConfigSchema,
121133 JinaConfigSchema,
122134 MockConfigSchema,
123135 InceptionConfigSchema,