Elffuss BraidHub

kikocis/continue public

627d7d0d1f85 · 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};
43
44/**
45 * A way to persist global state
46 */
47export class GlobalContext {
48 update<T extends keyof GlobalContextType>(
49 key: T,
50 value: GlobalContextType[T],
51 ) {
52 const filepath = getGlobalContextFilePath();
53 if (!fs.existsSync(filepath)) {
54 fs.writeFileSync(
55 filepath,
56 JSON.stringify(
57 {
58 [key]: value,
59 },
60 null,
61 2,
62 ),
63 );
64 } else {
65 const data = fs.readFileSync(filepath, "utf-8");
66
67 let parsed;
68 try {
69 parsed = JSON.parse(data);
70 } catch (e: any) {
71 console.warn(
72 `Error updating global context, deleting corrupted file: ${e}`,
73 );
74 // Delete the corrupted file and recreate it fresh
75 try {
76 fs.unlinkSync(filepath);
77 } catch (deleteError) {
78 console.warn(
79 `Error deleting corrupted global context file: ${deleteError}`,
80 );
81 }
82 // Recreate the file with just the new value
83 fs.writeFileSync(
84 filepath,
85 JSON.stringify(
86 {
87 [key]: value,
88 },
89 null,
90 2,
91 ),
92 );
93 return;
94 }
95
96 parsed[key] = value;
97 fs.writeFileSync(filepath, JSON.stringify(parsed, null, 2));
98 }
99 }
100
101 get<T extends keyof GlobalContextType>(
102 key: T,
103 ): GlobalContextType[T] | undefined {
104 const filepath = getGlobalContextFilePath();
105 if (!fs.existsSync(filepath)) {
106 return undefined;
107 }
108
109 const data = fs.readFileSync(filepath, "utf-8");
110 try {
111 const parsed = JSON.parse(data);
112 return parsed[key];
113 } catch (e: any) {
114 console.warn(
115 `Error parsing global context, deleting corrupted file: ${e}`,
116 );
117 // Delete the corrupted file so it can be recreated fresh
118 try {
119 fs.unlinkSync(filepath);
120 } catch (deleteError) {
121 console.warn(
122 `Error deleting corrupted global context file: ${deleteError}`,
123 );
124 }
125 return undefined;
126 }
127 }
128
129 getSharedConfig(): SharedConfigSchema {
130 const sharedConfig = this.get("sharedConfig") ?? {};
131 const result = sharedConfigSchema.safeParse(sharedConfig);
132 if (result.success) {
133 return result.data;
134 } else {
135 // in case of damaged shared config, repair it
136 // Attempt to salvage any values that are security concerns
137 console.error("Failed to load shared config, salvaging...", result.error);
138 const salvagedConfig = salvageSharedConfig(sharedConfig);
139 this.update("sharedConfig", salvagedConfig);
140 return salvagedConfig;
141 }
142 }
143
144 updateSharedConfig(
145 newValues: Partial<SharedConfigSchema>,
146 ): SharedConfigSchema {
147 const currentSharedConfig = this.getSharedConfig();
148 const updatedSharedConfig = {
149 ...currentSharedConfig,
150 ...newValues,
151 };
152 this.update("sharedConfig", updatedSharedConfig);
153 return updatedSharedConfig;
154 }
155
156 updateSelectedModel(
157 profileId: string,
158 role: ModelRole,
159 title: string | null,
160 ): GlobalContextModelSelections {
161 const currentSelections = this.get("selectedModelsByProfileId") ?? {};
162 const forProfile = currentSelections[profileId] ?? {};
163 const newSelections = {
164 ...forProfile,
165 [role]: title,
166 };
167
168 this.update("selectedModelsByProfileId", {
169 ...currentSelections,
170 [profileId]: newSelections,
171 });
172 return newSelections;
173 }
174}