This repository was archived by the owner on Jul 8, 2025. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathworkspace-custom-instructions.tsx
More file actions
381 lines (353 loc) · 11 KB
/
Copy pathworkspace-custom-instructions.tsx
File metadata and controls
381 lines (353 loc) · 11 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
import Editor, { type Theme } from "@monaco-editor/react";
import {
Button,
Card,
CardBody,
CardFooter,
DarkModeContext,
Dialog,
DialogCloseButton,
DialogContent,
DialogFooter,
DialogHeader,
DialogModal,
DialogModalOverlay,
DialogTitle,
DialogTrigger,
FieldGroup,
Form,
Input,
Link,
Loader,
SearchField,
SearchFieldClearButton,
Text,
TextLink,
} from "@stacklok/ui-kit";
import {
Dispatch,
FormEvent,
SetStateAction,
useCallback,
useContext,
useEffect,
useMemo,
useState,
} from "react";
import { twMerge } from "tailwind-merge";
import {
V1GetWorkspaceCustomInstructionsData,
V1GetWorkspaceCustomInstructionsResponse,
V1SetWorkspaceCustomInstructionsData,
} from "@/api/generated";
import {
QueryCacheNotifyEvent,
QueryClient,
useQueryClient,
} from "@tanstack/react-query";
import { v1GetWorkspaceCustomInstructionsQueryKey } from "@/api/generated/@tanstack/react-query.gen";
import { useQueryGetWorkspaceCustomInstructions } from "../hooks/use-query-get-workspace-custom-instructions";
import { useMutationSetWorkspaceCustomInstructions } from "../hooks/use-mutation-set-workspace-custom-instructions";
import Fuse from "fuse.js";
import systemPrompts from "../constants/built-in-system-prompts.json";
import { MessageTextSquare02, SearchMd } from "@untitled-ui/icons-react";
import { invalidateQueries } from "@/lib/react-query-utils";
import { useFormState } from "@/hooks/useFormState";
import { FormButtons } from "@/components/FormButtons";
type DarkModeContextValue = {
preference: "dark" | "light" | null;
override: "dark" | "light" | null;
};
function inferDarkMode(
contextValue:
| null
| [DarkModeContextValue, Dispatch<SetStateAction<DarkModeContextValue>>],
): Theme {
if (contextValue === null) return "light";
// Handle override
if (contextValue[0].override === "dark") return "vs-dark";
if (contextValue[0].override === "light") return "light";
// Handle preference
if (contextValue[0].preference === "dark") return "vs-dark";
return "light";
}
function EditorLoadingUI() {
return (
// arbitrary value to match the monaco editor height
// eslint-disable-next-line tailwindcss/no-unnecessary-arbitrary-value
<div className="min-h-[20rem] w-full flex items-center justify-center">
<Loader className="my-auto" />
</div>
);
}
function isGetWorkspaceCustomInstructionsQuery(
queryKey: unknown,
options: V1GetWorkspaceCustomInstructionsData,
): boolean {
return (
Array.isArray(queryKey) &&
queryKey[0]._id ===
v1GetWorkspaceCustomInstructionsQueryKey(options)[0]?._id
);
}
function getCustomInstructionsFromEvent(
event: QueryCacheNotifyEvent,
): string | null {
if ("action" in event === false || "data" in event.action === false)
return null;
return (
(
event.action.data as
| V1GetWorkspaceCustomInstructionsResponse
| undefined
| null
)?.prompt ?? null
);
}
function useCustomInstructionsValue({
initialValue,
options,
queryClient,
}: {
initialValue: string;
options: V1GetWorkspaceCustomInstructionsData;
queryClient: QueryClient;
}) {
const initialFormValues = useMemo(
() => ({ prompt: initialValue }),
[initialValue],
);
const formState = useFormState(initialFormValues);
const { values, updateFormValues } = formState;
// Subscribe to changes in the workspace system prompt value in the query cache
useEffect(() => {
const queryCache = queryClient.getQueryCache();
const unsubscribe = queryCache.subscribe((event) => {
if (
event.type === "updated" &&
event.action.type === "success" &&
isGetWorkspaceCustomInstructionsQuery(
event.query.options.queryKey,
options,
)
) {
const prompt: string | null = getCustomInstructionsFromEvent(event);
if (prompt === values.prompt || prompt === null) return;
updateFormValues({ prompt });
}
});
return () => {
return unsubscribe();
};
}, [options, queryClient, updateFormValues, values.prompt]);
return { ...formState };
}
type PromptPresetPickerProps = {
onActivate: (text: string) => void;
};
function PromptPresetPicker({ onActivate }: PromptPresetPickerProps) {
const [query, setQuery] = useState<string>("");
const fuse = new Fuse(systemPrompts, {
keys: ["name", "text"],
});
const handleActivate = useCallback(
(prompt: string) => {
onActivate(prompt);
},
[onActivate],
);
return (
<>
<DialogHeader>
<DialogTitle>Choose a prompt template</DialogTitle>
<DialogCloseButton />
</DialogHeader>
<DialogContent className="p-0 relative">
<div
className="bg-base pt-4 px-4 pb-2 mb-2 sticky top-0 z-10"
style={{
boxShadow: "0px 4px 4px 4px var(--bg-base)",
}}
>
<SearchField className="w-full" value={query} onChange={setQuery}>
<FieldGroup>
<Input
isBorderless
icon={<SearchMd />}
placeholder="Type to search"
autoFocus
/>
{query.length > 0 ? <SearchFieldClearButton /> : null}
</FieldGroup>
</SearchField>
</div>
<div className="grid grid-cols-1 lg:grid-cols-2 xl:grid-cols-3 gap-4 px-4 pb-4">
{fuse.search(query.length > 0 ? query : " ").map(({ item }) => {
return (
<Card className="min-h-96">
<h2 className="font-bold p-2 flex gap-2 items-center">
<MessageTextSquare02 className="size-4" />
<div className="truncate">{item.name}</div>
</h2>
<pre className="h-72 overflow-hidden text-wrap text-sm bg-gray-50 p-2 overflow-y-auto">
{item.text}
</pre>
<div className="flex gap-4 justify-between p-2">
<div className="h-full items-center">
<div className="flex h-full items-center max-w-52 text-clip">
{item.contributors.map((contributor) => (
<Link
className="font-bold text-sm no-underline text-secondary flex gap-1 items-center hover:bg-gray-200 h-full px-2 rounded-md"
target="_blank"
href={`https://github.com/${contributor}/`}
>
<img
className="size-6 rounded-full"
src={`https://github.com/${contributor}.png?size=24`}
/>
<span className="truncate">{contributor}</span>
</Link>
))}
</div>
</div>
<Button
slot="close"
variant="secondary"
onPress={() => {
handleActivate(item.text);
}}
>
Use prompt
</Button>
</div>
</Card>
);
})}
</div>
</DialogContent>
<DialogFooter>
<span className="ml-auto">
Prompt templates sourced from{" "}
<TextLink
className="text-primary"
href="https://github.com/PatrickJS/awesome-cursorrules"
>
PatrickJS/awesome-cursorrules
</TextLink>
</span>
</DialogFooter>
</>
);
}
export function WorkspaceCustomInstructions({
className,
workspaceName,
isArchived,
}: {
className?: string;
workspaceName: string;
isArchived: boolean | undefined;
}) {
const context = useContext(DarkModeContext);
const theme: Theme = inferDarkMode(context);
const options: V1GetWorkspaceCustomInstructionsData &
Omit<V1SetWorkspaceCustomInstructionsData, "body"> = useMemo(
() => ({
path: { workspace_name: workspaceName },
}),
[workspaceName],
);
const queryClient = useQueryClient();
const {
data: customInstructionsResponse,
isPending: isCustomInstructionsPending,
} = useQueryGetWorkspaceCustomInstructions(options);
const { mutateAsync, isPending: isMutationPending } =
useMutationSetWorkspaceCustomInstructions(options);
const formState = useCustomInstructionsValue({
initialValue: customInstructionsResponse?.prompt ?? "",
options,
queryClient,
});
const { values, updateFormValues } = formState;
const handleSubmit = useCallback(
(value: string) => {
mutateAsync(
{ ...options, body: { prompt: value } },
{
onSuccess: () =>
invalidateQueries(queryClient, [
v1GetWorkspaceCustomInstructionsQueryKey,
]),
},
);
},
[mutateAsync, options, queryClient],
);
return (
<Form
onSubmit={(e: FormEvent) => {
e.preventDefault();
handleSubmit(values.prompt);
}}
validationBehavior="aria"
>
<Card className={twMerge(className, "shrink-0")}>
<CardBody>
<Text className="text-primary">Custom instructions</Text>
<Text className="text-secondary mb-4">
Pass custom instructions to your LLM to augment its behavior, and
save time & tokens.
</Text>
<div className="border border-gray-200 rounded overflow-hidden">
{isCustomInstructionsPending ? (
<EditorLoadingUI />
) : (
<Editor
options={{
minimap: { enabled: false },
wordWrap: "on",
readOnly: isArchived,
}}
value={values.prompt}
onChange={(v) => updateFormValues({ prompt: v ?? "" })}
height="20rem"
defaultLanguage="Markdown"
theme={theme}
className={twMerge("bg-base", isArchived ? "opacity-25" : "")}
/>
)}
</div>
</CardBody>
<CardFooter className="justify-end gap-2">
<FormButtons
isPending={isMutationPending}
formState={formState}
canSubmit={
!isArchived && !isCustomInstructionsPending && !isMutationPending
}
>
<DialogTrigger>
<Button variant="secondary">Use a preset</Button>
<DialogModalOverlay isDismissable>
<DialogModal isDismissable>
<Dialog
width="lg"
className="min-h-[44rem]"
style={{ maxWidth: "min(calc(100vw - 64px), 1200px)" }}
>
<PromptPresetPicker
onActivate={(prompt: string) => {
updateFormValues({ prompt });
}}
/>
</Dialog>
</DialogModal>
</DialogModalOverlay>
</DialogTrigger>
</FormButtons>
</CardFooter>
</Card>
</Form>
);
}