Elffuss BraidHub

kikocis/continue public

245005345e6e · 4.6 KiBRawPermalink
1import fs from "node:fs";
2
3import { ModelRole } from "@continuedev/config-yaml";
4
5import { SiteIndexingConfig } from "..";
6import {
7 salvageSharedConfig,
8 sharedConfigSchema,
9 SharedConfigSchema,
10} from "../config/sharedConfig";
11
12import { getGlobalContextFilePath } from "./paths";
13
14export type GlobalContextModelSelections = Partial<
15 Record<ModelRole, string | null>
16>;
17
18export type GlobalContextType = {
19 indexingPaused: boolean;
20 lastSelectedProfileForWorkspace: {
21 [workspaceIdentifier: string]: string | null;
22 };
23 lastSelectedOrgIdForWorkspace: {
24 [workspaceIdentifier: string]: string | null;
25 };
26 selectedModelsByProfileId: {
27 [profileId: string]: GlobalContextModelSelections;
28 };
29
30 /**
31 * This is needed to handle the case where a JetBrains user has created
32 * docs embeddings using one provider, and then updates to a new provider.
33 *
34 * For VS Code users, it is unnecessary since we use transformers.js by default.
35 */
36 hasDismissedConfigTsNoticeJetBrains: boolean;
37 hasAlreadyCreatedAPromptFile: boolean;
38 showConfigUpdateToast: boolean;
39 isSupportedLanceDbCpuTargetForLinux: boolean;
40 sharedConfig: SharedConfigSchema;
41 failedDocs: SiteIndexingConfig[];
42 shownDeprecatedProviderWarnings: {
43 [providerTitle: string]: boolean;
44 };
45};
46
47/**
48 * A way to persist global state
49 */
50export class GlobalContext {
51 update<T extends keyof GlobalContextType>(
52 key: T,
53 value: GlobalContextType[T],
54 ) {
55 const filepath = getGlobalContextFilePath();
56 if (!fs.existsSync(filepath)) {
57 fs.writeFileSync(
58 filepath,
59 JSON.stringify(
60 {
61 [key]: value,
62 },
63 null,
64 2,
65 ),
66 );
67 } else {
68 const data = fs.readFileSync(filepath, "utf-8");
69
70 let parsed;
71 try {
72 parsed = JSON.parse(data);
73 } catch (e: any) {
74 console.warn(
75 `Error updating global context, deleting corrupted file: ${e}`,
76 );
77 // Delete the corrupted file and recreate it fresh
78 try {
79 fs.unlinkSync(filepath);
80 } catch (deleteError) {
81 console.warn(
82 `Error deleting corrupted global context file: ${deleteError}`,
83 );
84 }
85 // Recreate the file with just the new value
86 fs.writeFileSync(
87 filepath,
88 JSON.stringify(
89 {
90 [key]: value,
91 },
92 null,
93 2,
94 ),
95 );
96 return;
97 }
98
99 parsed[key] = value;
100 fs.writeFileSync(filepath, JSON.stringify(parsed, null, 2));
101 }
102 }
103
104 get<T extends keyof GlobalContextType>(
105 key: T,
106 ): GlobalContextType[T] | undefined {
107 const filepath = getGlobalContextFilePath();
108 if (!fs.existsSync(filepath)) {
109 return undefined;
110 }
111
112 const data = fs.readFileSync(filepath, "utf-8");
113 try {
114 const parsed = JSON.parse(data);
115 return parsed[key];
116 } catch (e: any) {
117 console.warn(
118 `Error parsing global context, deleting corrupted file: ${e}`,
119 );
120 // Delete the corrupted file so it can be recreated fresh
121 try {
122 fs.unlinkSync(filepath);
123 } catch (deleteError) {
124 console.warn(
125 `Error deleting corrupted global context file: ${deleteError}`,
126 );
127 }
128 return undefined;
129 }
130 }
131
132 getSharedConfig(): SharedConfigSchema {
133 const sharedConfig = this.get("sharedConfig") ?? {};
134 const result = sharedConfigSchema.safeParse(sharedConfig);
135 if (result.success) {
136 return result.data;
137 } else {
138 // in case of damaged shared config, repair it
139 // Attempt to salvage any values that are security concerns
140 console.error("Failed to load shared config, salvaging...", result.error);
141 const salvagedConfig = salvageSharedConfig(sharedConfig);
142 this.update("sharedConfig", salvagedConfig);
143 return salvagedConfig;
144 }
145 }
146
147 updateSharedConfig(
148 newValues: Partial<SharedConfigSchema>,
149 ): SharedConfigSchema {
150 const currentSharedConfig = this.getSharedConfig();
151 const updatedSharedConfig = {
152 ...currentSharedConfig,
153 ...newValues,
154 };
155 this.update("sharedConfig", updatedSharedConfig);
156 return updatedSharedConfig;
157 }
158
159 updateSelectedModel(
160 profileId: string,
161 role: ModelRole,
162 title: string | null,
163 ): GlobalContextModelSelections {
164 const currentSelections = this.get("selectedModelsByProfileId") ?? {};
165 const forProfile = currentSelections[profileId] ?? {};
166 const newSelections = {
167 ...forProfile,
168 [role]: title,
169 };
170
171 this.update("selectedModelsByProfileId", {
172 ...currentSelections,
173 [profileId]: newSelections,
174 });
175 return newSelections;
176 }
177}