paseo-quick-prompts 0.1.0 → 0.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,35 +1,30 @@
1
- import { useSettings, type PluginSurfaceProps, type SettingsState } from "@getpaseo/plugin/client";
2
- import { copyText, useToast } from "@getpaseo/plugin/client/react-native";
1
+ import { usePaseo, useRpc, useSettings, type PluginSurfaceProps, type SettingsState } from "@getpaseo/plugin/client";
2
+ import { copyText, Icon, useToast } from "@getpaseo/plugin/client/react-native";
3
+ import { SettingsAction, SettingsCard, SettingsSection, SettingsSelect } from "@getpaseo/plugin/client/ui";
4
+ import { useEffect, useMemo, useRef, useState, useSyncExternalStore, type ReactNode } from "react";
3
5
  import {
4
- SettingsAction,
5
- SettingsCard,
6
- SettingsInput,
7
- SettingsRow,
8
- SettingsSection,
9
- SettingsSelect,
10
- } from "@getpaseo/plugin/client/ui";
11
- import { useMemo, useState } from "react";
12
- import { Pressable, Text, TextInput, View } from "react-native";
6
+ ActivityIndicator,
7
+ Pressable,
8
+ Text,
9
+ TextInput,
10
+ View,
11
+ type StyleProp,
12
+ type ViewStyle,
13
+ } from "react-native";
13
14
  import {
14
15
  LABEL_MAX_LENGTH,
15
16
  MAX_PROMPTS,
16
- newPromptId,
17
+ QuickPromptSchema,
17
18
  quickPromptsSettings,
18
- TEXT_MAX_LENGTH,
19
19
  type PromptDisplay,
20
20
  type QuickPrompt,
21
- type QuickPromptsSettings,
22
21
  } from "../shared/prompts";
22
+ import { createAutosave, draftKey, orphanedDrafts, type Autosave, type AutosaveState, type Field } from "./autosave";
23
+ import { movePrompt, setDisplay, settingsContract, type SettingsDoc } from "./edits";
24
+ import { followPromptChanges } from "./follow";
23
25
 
24
- type ReadySettings = Extract<SettingsState<typeof quickPromptsSettings.schema>, { status: "ready" }>;
26
+ type Settings = SettingsState<typeof quickPromptsSettings.schema>;
25
27
  type Theme = PluginSurfaceProps["theme"];
26
- type Field = "label" | "text";
27
-
28
- /** Unsaved edits with the revision they started from, so a save over another client's change conflicts. */
29
- interface Draft {
30
- values: QuickPromptsSettings;
31
- revision: string;
32
- }
33
28
 
34
29
  const DISPLAY_OPTIONS: ReadonlyArray<{ label: string; value: PromptDisplay }> = [
35
30
  { label: "Separate pills", value: "pills" },
@@ -42,55 +37,55 @@ const FIND_PROMPTS_PROMPT =
42
37
  "for me. For each one give a short label (40 characters or fewer) and the full prompt text, written so " +
43
38
  "it works for any task. Do not change anything; just list them so I can add them in Quick prompts.";
44
39
 
45
- interface Validation {
46
- valid: boolean;
47
- fields: Array<Partial<Record<Field, string>>>;
48
- list: string | null;
40
+ /** The first validation message for one field, or `null` when it would save. */
41
+ function fieldError(field: Field, value: string): string | null {
42
+ return QuickPromptSchema.shape[field].safeParse(value).error?.issues[0]?.message ?? null;
49
43
  }
50
44
 
51
- function validate(values: QuickPromptsSettings): Validation {
52
- const parsed = quickPromptsSettings.schema.safeParse(values);
53
- const fields: Validation["fields"] = values.prompts.map(() => ({}));
54
- let list: string | null = null;
55
- for (const issue of parsed.error?.issues ?? []) {
56
- const [, index, field] = issue.path;
57
- if (typeof index === "number" && (field === "label" || field === "text")) {
58
- fields[index] = { ...fields[index], [field]: fields[index]?.[field] ?? issue.message };
59
- } else {
60
- list ??= issue.message;
61
- }
62
- }
63
- return { valid: parsed.success, fields, list };
64
- }
45
+ const LINE_HEIGHT = 20;
46
+ /** The prompt input grows with its text up to this many lines, then scrolls. */
47
+ const MAX_LINES = 5;
65
48
 
66
49
  function useStyles(theme: Theme, compact: boolean) {
67
50
  return useMemo(
68
51
  () => ({
69
52
  intro: { color: theme.colors.foregroundMuted, fontSize: 13, lineHeight: 18 },
53
+ caption: { color: theme.colors.foregroundMuted, fontSize: 12 },
70
54
  message: { color: theme.colors.foreground },
71
- editor: { paddingHorizontal: compact ? 12 : 16, paddingVertical: compact ? 10 : 12 },
72
- textInput: {
73
- minHeight: 88,
74
- padding: 10,
75
- borderRadius: 8,
76
- borderWidth: 1,
77
- borderColor: theme.colors.border,
78
- backgroundColor: theme.colors.surface2,
79
- color: theme.colors.foreground,
80
- fontSize: 14,
81
- textAlignVertical: "top" as const,
82
- },
83
- buttons: { flexDirection: "row" as const, flexWrap: "wrap" as const, gap: 8 },
84
- button: {
55
+ status: { color: theme.colors.foregroundMuted, fontSize: 13 },
56
+ statusError: { color: theme.colors.statusDanger, fontSize: 13 },
57
+ editor: { paddingHorizontal: compact ? 12 : 16, paddingVertical: 8 },
58
+ row: { paddingHorizontal: compact ? 12 : 16, paddingVertical: 8, gap: 6 },
59
+ line: { flexDirection: "row" as const, alignItems: "flex-start" as const, gap: 6 },
60
+ labelColumn: compact ? { flex: 1 } : { width: 160 },
61
+ textColumn: compact ? {} : { flex: 1 },
62
+ field: {
85
63
  paddingHorizontal: 10,
86
64
  paddingVertical: 6,
87
65
  borderRadius: 6,
88
66
  borderWidth: 1,
89
67
  borderColor: theme.colors.border,
68
+ backgroundColor: theme.colors.surface2,
69
+ },
70
+ input: { padding: 0, color: theme.colors.foreground, fontSize: 14, lineHeight: LINE_HEIGHT },
71
+ error: { color: theme.colors.statusDanger, fontSize: 12, marginTop: 2 },
72
+ actions: { flexDirection: "row" as const, gap: 2, paddingTop: 3 },
73
+ iconButton: {
74
+ width: 28,
75
+ height: 28,
76
+ borderRadius: 6,
77
+ alignItems: "center" as const,
78
+ justifyContent: "center" as const,
79
+ },
80
+ addButton: {
81
+ height: 34,
82
+ paddingHorizontal: 12,
83
+ borderRadius: 6,
84
+ justifyContent: "center" as const,
85
+ backgroundColor: theme.colors.accent,
90
86
  },
91
- buttonDisabled: { opacity: 0.4 },
92
- buttonText: { color: theme.colors.foreground, fontSize: 13 },
93
- dangerText: { color: theme.colors.statusDanger, fontSize: 13 },
87
+ addText: { color: theme.colors.accentForeground, fontSize: 13 },
88
+ disabled: { opacity: 0.4 },
94
89
  tipPrompt: { color: theme.colors.foreground, fontSize: 13, lineHeight: 18 },
95
90
  }),
96
91
  [theme, compact],
@@ -99,111 +94,292 @@ function useStyles(theme: Theme, compact: boolean) {
99
94
 
100
95
  type Styles = ReturnType<typeof useStyles>;
101
96
 
102
- function SmallButton({
103
- label,
97
+ function IconButton({
98
+ icon,
104
99
  accessibilityLabel,
105
- danger,
100
+ color,
106
101
  disabled,
102
+ busy,
107
103
  styles,
108
104
  onPress,
109
105
  }: {
110
- label: string;
106
+ icon: string;
111
107
  accessibilityLabel: string;
112
- danger?: boolean;
108
+ color: string;
113
109
  disabled?: boolean;
110
+ busy?: boolean;
114
111
  styles: Styles;
115
112
  onPress(): void;
116
113
  }) {
114
+ const inactive = Boolean(disabled || busy);
117
115
  return (
118
116
  <Pressable
119
117
  accessibilityRole="button"
120
118
  accessibilityLabel={accessibilityLabel}
121
- accessibilityState={{ disabled: Boolean(disabled) }}
122
- disabled={disabled}
119
+ accessibilityState={{ disabled: inactive, busy: Boolean(busy) }}
120
+ disabled={inactive}
121
+ hitSlop={6}
123
122
  onPress={onPress}
124
- style={disabled ? [styles.button, styles.buttonDisabled] : styles.button}
123
+ style={disabled ? [styles.iconButton, styles.disabled] : styles.iconButton}
125
124
  >
126
- <Text style={danger ? styles.dangerText : styles.buttonText}>{label}</Text>
125
+ {busy ? <ActivityIndicator size="small" color={color} /> : <Icon name={icon} size={16} color={color} />}
127
126
  </Pressable>
128
127
  );
129
128
  }
130
129
 
130
+ /** A bordered input with its validation error underneath when there is one. */
131
+ function CompactInput({
132
+ field,
133
+ value,
134
+ error,
135
+ accessibilityLabel,
136
+ style,
137
+ theme,
138
+ styles,
139
+ onChangeText,
140
+ onBlur,
141
+ }: {
142
+ field: Field;
143
+ value: string;
144
+ error: string | null;
145
+ accessibilityLabel: string;
146
+ style: StyleProp<ViewStyle>;
147
+ theme: Theme;
148
+ styles: Styles;
149
+ onChangeText(text: string): void;
150
+ onBlur?(): void;
151
+ }) {
152
+ const multiline = field === "text";
153
+ // The input has no padding of its own, so its content height is the height of its text.
154
+ const [contentHeight, setContentHeight] = useState(LINE_HEIGHT);
155
+ const maxHeight = LINE_HEIGHT * MAX_LINES;
156
+ const height = multiline ? Math.min(Math.max(contentHeight, LINE_HEIGHT), maxHeight) : LINE_HEIGHT;
157
+ return (
158
+ <View style={style}>
159
+ <View style={styles.field}>
160
+ <TextInput
161
+ multiline={multiline}
162
+ scrollEnabled={multiline && contentHeight > maxHeight}
163
+ accessibilityLabel={accessibilityLabel}
164
+ value={value}
165
+ placeholder={multiline ? "Prompt sent to the agent" : "Label"}
166
+ placeholderTextColor={theme.colors.foregroundMuted}
167
+ onChangeText={onChangeText}
168
+ onBlur={onBlur}
169
+ onContentSizeChange={multiline ? (event) => setContentHeight(event.nativeEvent.contentSize.height) : undefined}
170
+ style={[styles.input, { height }]}
171
+ />
172
+ </View>
173
+ {error ? <Text style={styles.error}>{error}</Text> : null}
174
+ </View>
175
+ );
176
+ }
177
+
178
+ /** One line on wide layouts; on compact ones the label and actions, then the prompt underneath. */
179
+ function PromptRow({
180
+ compact,
181
+ label,
182
+ text,
183
+ actions,
184
+ styles,
185
+ }: {
186
+ compact: boolean;
187
+ label: ReactNode;
188
+ text: ReactNode;
189
+ actions: ReactNode;
190
+ styles: Styles;
191
+ }) {
192
+ if (compact) {
193
+ return (
194
+ <View style={styles.row}>
195
+ <View style={styles.line}>
196
+ {label}
197
+ {actions}
198
+ </View>
199
+ {text}
200
+ </View>
201
+ );
202
+ }
203
+ return (
204
+ <View style={[styles.row, styles.line]}>
205
+ {label}
206
+ {text}
207
+ {actions}
208
+ </View>
209
+ );
210
+ }
211
+
131
212
  function PromptEditor({
132
213
  prompt,
133
214
  index,
134
215
  count,
135
- errors,
136
- inputKey,
137
- disabled,
216
+ compact,
217
+ state,
218
+ store,
138
219
  theme,
139
220
  styles,
140
- onChange,
141
- onMove,
142
- onDelete,
143
221
  }: {
144
222
  prompt: QuickPrompt;
145
223
  index: number;
146
224
  count: number;
147
- errors: Partial<Record<Field, string>>;
148
- inputKey: string;
149
- disabled: boolean;
225
+ compact: boolean;
226
+ state: AutosaveState;
227
+ store: Autosave;
150
228
  theme: Theme;
151
229
  styles: Styles;
152
- onChange(field: Field, value: string): void;
153
- onMove(offset: -1 | 1): void;
154
- onDelete(): void;
155
230
  }) {
156
- const name = prompt.label.trim() || `quick prompt ${index + 1}`;
157
- return (
158
- <SettingsCard>
159
- <SettingsInput
160
- key={inputKey}
161
- label="Label"
162
- hint="Shown on the pill."
163
- initialValue={prompt.label}
164
- placeholder="Review changes"
165
- error={errors.label}
166
- disabled={disabled}
167
- onChangeText={(text) => onChange("label", text)}
231
+ const name = prompt.label || `quick prompt ${index + 1}`;
232
+ const input = (field: Field, accessibilityLabel: string) => {
233
+ const draft = state.drafts.get(draftKey(prompt.id, field));
234
+ return (
235
+ <CompactInput
236
+ field={field}
237
+ value={draft?.text ?? prompt[field]}
238
+ error={draft?.showError ? fieldError(field, draft.text) : null}
239
+ accessibilityLabel={accessibilityLabel}
240
+ style={field === "label" ? styles.labelColumn : styles.textColumn}
241
+ theme={theme}
242
+ styles={styles}
243
+ onChangeText={(text) => store.setDraft(prompt.id, field, text)}
244
+ onBlur={() => store.submit(prompt.id, field)}
168
245
  />
169
- <SettingsRow label="Prompt" hint="Sent to the agent as your message." error={errors.text} />
170
- <View style={styles.editor}>
171
- <TextInput
172
- multiline
173
- accessibilityLabel={`Prompt for ${name}`}
174
- value={prompt.text}
175
- editable={!disabled}
176
- maxLength={TEXT_MAX_LENGTH}
177
- placeholder="Review the uncommitted changes and list any bugs."
178
- placeholderTextColor={theme.colors.foregroundMuted}
179
- onChangeText={(text) => onChange("text", text)}
180
- style={styles.textInput}
181
- />
182
- </View>
183
- <View style={[styles.editor, styles.buttons]}>
184
- <SmallButton
185
- label="Move up"
186
- accessibilityLabel={`Move ${name} up`}
187
- disabled={disabled || index === 0}
246
+ );
247
+ };
248
+ return (
249
+ <PromptRow
250
+ compact={compact}
251
+ styles={styles}
252
+ label={input("label", `Label for ${name}`)}
253
+ text={input("text", `Prompt for ${name}`)}
254
+ actions={
255
+ <View style={styles.actions}>
256
+ <IconButton
257
+ icon="ArrowUp"
258
+ accessibilityLabel={`Move ${name} up`}
259
+ color={theme.colors.foreground}
260
+ disabled={index === 0}
261
+ styles={styles}
262
+ onPress={() => void store.save(movePrompt(prompt.id, -1))}
263
+ />
264
+ <IconButton
265
+ icon="ArrowDown"
266
+ accessibilityLabel={`Move ${name} down`}
267
+ color={theme.colors.foreground}
268
+ disabled={index === count - 1}
269
+ styles={styles}
270
+ onPress={() => void store.save(movePrompt(prompt.id, 1))}
271
+ />
272
+ <IconButton
273
+ icon="Trash2"
274
+ accessibilityLabel={`Delete ${name}`}
275
+ color={theme.colors.statusDanger}
276
+ busy={state.deleting.has(prompt.id)}
277
+ styles={styles}
278
+ onPress={() => void store.remove(prompt.id)}
279
+ />
280
+ </View>
281
+ }
282
+ />
283
+ );
284
+ }
285
+
286
+ function NewPromptRow({
287
+ count,
288
+ compact,
289
+ state,
290
+ store,
291
+ theme,
292
+ styles,
293
+ }: {
294
+ count: number;
295
+ compact: boolean;
296
+ state: AutosaveState;
297
+ store: Autosave;
298
+ theme: Theme;
299
+ styles: Styles;
300
+ }) {
301
+ const { label, text, showErrors } = state.newPrompt;
302
+ const disabled = state.adding || count >= MAX_PROMPTS;
303
+ return (
304
+ <PromptRow
305
+ compact={compact}
306
+ styles={styles}
307
+ label={
308
+ <CompactInput
309
+ field="label"
310
+ value={label}
311
+ error={showErrors ? fieldError("label", label) : null}
312
+ accessibilityLabel="Label for the new quick prompt"
313
+ style={styles.labelColumn}
314
+ theme={theme}
188
315
  styles={styles}
189
- onPress={() => onMove(-1)}
316
+ onChangeText={(value) => store.setNewPrompt("label", value)}
190
317
  />
191
- <SmallButton
192
- label="Move down"
193
- accessibilityLabel={`Move ${name} down`}
194
- disabled={disabled || index === count - 1}
318
+ }
319
+ text={
320
+ <CompactInput
321
+ field="text"
322
+ value={text}
323
+ error={showErrors ? fieldError("text", text) : null}
324
+ accessibilityLabel="Prompt for the new quick prompt"
325
+ style={styles.textColumn}
326
+ theme={theme}
195
327
  styles={styles}
196
- onPress={() => onMove(1)}
328
+ onChangeText={(value) => store.setNewPrompt("text", value)}
197
329
  />
198
- <SmallButton
199
- label="Delete"
200
- accessibilityLabel={`Delete ${name}`}
201
- danger
330
+ }
331
+ actions={
332
+ <Pressable
333
+ accessibilityRole="button"
334
+ accessibilityLabel="Add quick prompt"
335
+ accessibilityState={{ disabled, busy: state.adding }}
202
336
  disabled={disabled}
203
- styles={styles}
204
- onPress={onDelete}
205
- />
337
+ onPress={() => void store.add()}
338
+ style={disabled ? [styles.addButton, styles.disabled] : styles.addButton}
339
+ >
340
+ <Text style={styles.addText}>{state.adding ? "Adding…" : "Add"}</Text>
341
+ </Pressable>
342
+ }
343
+ />
344
+ );
345
+ }
346
+
347
+ /** Text typed into prompts that were deleted on another device, kept until copied or dismissed. */
348
+ function UnsavedEdits({ state, store, styles }: { state: AutosaveState; store: Autosave; styles: Styles }) {
349
+ const toast = useToast();
350
+ const orphans = orphanedDrafts(state);
351
+ if (orphans.length === 0) return null;
352
+ const promptIds = [...new Set(orphans.map(({ promptId }) => promptId))];
353
+ const text = promptIds
354
+ .map((promptId) =>
355
+ orphans
356
+ .filter((draft) => draft.promptId === promptId)
357
+ .map((draft) => `${draft.field === "label" ? "Label" : "Prompt"}: ${draft.text}`)
358
+ .join("\n"),
359
+ )
360
+ .join("\n\n");
361
+ const copy = async (): Promise<void> => {
362
+ try {
363
+ await copyText(text);
364
+ toast.show("Copied", { variant: "success" });
365
+ } catch {
366
+ toast.error("Could not copy. Select the text and use Copy.");
367
+ }
368
+ };
369
+ return (
370
+ <SettingsCard>
371
+ <SettingsAction
372
+ label="Unsaved edits"
373
+ hint="These prompts were deleted on another device before your edits were saved."
374
+ actionLabel="Copy"
375
+ onPress={() => void copy()}
376
+ />
377
+ <View style={styles.editor}>
378
+ <Text selectable style={styles.tipPrompt}>
379
+ {text}
380
+ </Text>
206
381
  </View>
382
+ <SettingsAction label="Discard these edits" actionLabel="Dismiss" onPress={() => store.dismissOrphans()} />
207
383
  </SettingsCard>
208
384
  );
209
385
  }
@@ -235,109 +411,135 @@ function FindPromptsTip({ styles }: { styles: Styles }) {
235
411
  );
236
412
  }
237
413
 
238
- function PromptLibrary({ settings, theme, layout }: { settings: ReadySettings } & PluginSurfaceProps) {
239
- const styles = useStyles(theme, layout.compact);
240
- const [draft, setDraft] = useState<Draft | null>(null);
241
- // Remounts the label inputs, which own their text, when a draft is discarded.
242
- const [generation, setGeneration] = useState(0);
414
+ /** A failed or unreadable settings read, with a way to read again or reset. */
415
+ function LoadProblem({ settings, styles, onReload }: { settings: Settings; styles: Styles; onReload(): void }) {
416
+ const toast = useToast();
417
+ if (settings.status !== "error" && settings.status !== "invalid") return null;
418
+ const reset = async (): Promise<void> => {
419
+ if (!(await settings.reset())) toast.error("Could not reset quick prompts. Try again.");
420
+ };
421
+ return (
422
+ <>
423
+ <Text style={styles.message}>{settings.error}</Text>
424
+ <SettingsCard>
425
+ <SettingsAction label="Try again" actionLabel="Reload" onPress={onReload} />
426
+ {settings.status === "invalid" ? (
427
+ <SettingsAction
428
+ label="Delete the saved quick prompts"
429
+ hint="The stored data cannot be read."
430
+ actionLabel={settings.saving ? "Resetting…" : "Reset"}
431
+ disabled={settings.saving}
432
+ onPress={() => void reset()}
433
+ />
434
+ ) : null}
435
+ </SettingsCard>
436
+ </>
437
+ );
438
+ }
243
439
 
244
- const saved = settings.values;
245
- const isChanged = (candidate: Draft | null): candidate is Draft =>
246
- candidate !== null &&
247
- (candidate.values.display !== saved.display ||
248
- JSON.stringify(candidate.values.prompts) !== JSON.stringify(saved.prompts));
249
- // A draft edited back to the saved settings is no draft: show live values again.
250
- const editing = isChanged(draft) ? draft : null;
251
- const values = editing?.values ?? saved;
252
- const prompts = values.prompts;
253
- const validation = validate(values);
254
- const disabled = settings.saving;
255
- const inputKeyPrefix = `${editing?.revision ?? settings.revision}-${generation}`;
440
+ function PromptLibrary({
441
+ initial,
442
+ settings,
443
+ theme,
444
+ layout,
445
+ }: { initial: SettingsDoc; settings: Settings } & PluginSurfaceProps) {
446
+ const styles = useStyles(theme, layout.compact);
447
+ const toast = useToast();
448
+ const paseo = usePaseo();
449
+ // The store outlives renders; it reaches the current RPCs and toast through this ref.
450
+ const write = useRpc(settingsContract.write);
451
+ const read = useRpc(settingsContract.read);
452
+ const host = useRef({ write, read, toast });
453
+ host.current = { write, read, toast };
454
+ const [store] = useState(() =>
455
+ createAutosave(initial, {
456
+ io: { write: (input) => host.current.write(input), read: () => host.current.read({}) },
457
+ onProblem(problem, error) {
458
+ if (problem === "stale") {
459
+ host.current.toast.error("Quick prompts changed elsewhere, so this change was not saved.");
460
+ return;
461
+ }
462
+ console.error("[paseo-quick-prompts] failed to save quick prompts", error);
463
+ host.current.toast.error("Could not save quick prompts. Try again.");
464
+ },
465
+ }),
466
+ );
467
+ const state = useSyncExternalStore(store.subscribe, store.getState);
256
468
 
257
- const editValues = (change: (current: QuickPromptsSettings) => QuickPromptsSettings): void => {
258
- setDraft((current) => {
259
- const base = isChanged(current) ? current : { values: saved, revision: settings.revision };
260
- return { ...base, values: change(base.values) };
261
- });
262
- };
263
- const edit = (change: (current: QuickPrompt[]) => QuickPrompt[]): void =>
264
- editValues((current) => ({ ...current, prompts: change(current.prompts) }));
469
+ // Read again whenever any client saves.
470
+ useEffect(() => {
471
+ const lifetime = new AbortController();
472
+ followPromptChanges(paseo, lifetime.signal, () => store.refresh());
473
+ return () => lifetime.abort();
474
+ }, [paseo, store]);
265
475
 
266
- const discard = (): void => {
267
- setDraft(null);
268
- setGeneration((value) => value + 1);
269
- void settings.reload();
270
- };
476
+ // Closing the screen saves what can be saved and says when something could not be.
477
+ useEffect(
478
+ () => () => {
479
+ if (store.flush() > 0) host.current.toast.error("Some quick prompt edits could not be saved.");
480
+ },
481
+ [store],
482
+ );
271
483
 
272
- const save = async (): Promise<void> => {
273
- if (!editing) return;
274
- const parsed = quickPromptsSettings.schema.safeParse(editing.values);
275
- if (!parsed.success) return;
276
- if (await settings.save(parsed.data, editing.revision)) setDraft(null);
277
- };
484
+ const prompts = state.doc.values.prompts;
485
+ const status = state.saving ? "Saving…" : state.last === "saved" ? "Saved" : state.last === "failed" ? "Not saved" : null;
278
486
 
279
487
  return (
280
- <SettingsSection title="Quick prompts">
488
+ <SettingsSection
489
+ title="Quick prompts"
490
+ trailing={
491
+ status ? <Text style={state.last === "failed" && !state.saving ? styles.statusError : styles.status}>{status}</Text> : undefined
492
+ }
493
+ >
281
494
  <Text style={styles.intro}>
282
495
  Quick prompts appear above every agent's composer, as separate pills or in one Prompts menu. Choosing one
283
- sends the prompt to that agent as your message.
496
+ sends the prompt to that agent as your message. Changes save automatically.
284
497
  </Text>
285
- {prompts.map((prompt, index) => (
286
- <PromptEditor
287
- key={prompt.id}
288
- prompt={prompt}
289
- index={index}
498
+ <LoadProblem
499
+ settings={settings}
500
+ styles={styles}
501
+ onReload={() => {
502
+ void settings.reload();
503
+ store.refresh();
504
+ }}
505
+ />
506
+ <UnsavedEdits state={state} store={store} styles={styles} />
507
+ <SettingsCard>
508
+ {prompts.map((prompt, index) => (
509
+ <PromptEditor
510
+ key={prompt.id}
511
+ prompt={prompt}
512
+ index={index}
513
+ count={prompts.length}
514
+ compact={layout.compact}
515
+ state={state}
516
+ store={store}
517
+ theme={theme}
518
+ styles={styles}
519
+ />
520
+ ))}
521
+ <NewPromptRow
290
522
  count={prompts.length}
291
- errors={validation.fields[index] ?? {}}
292
- inputKey={`${prompt.id}-${inputKeyPrefix}`}
293
- disabled={disabled}
523
+ compact={layout.compact}
524
+ state={state}
525
+ store={store}
294
526
  theme={theme}
295
527
  styles={styles}
296
- onChange={(field, value) =>
297
- edit((current) => current.map((item) => (item.id === prompt.id ? { ...item, [field]: value } : item)))
298
- }
299
- onMove={(offset) =>
300
- edit((current) => {
301
- const next = [...current];
302
- const [moved] = next.splice(index, 1);
303
- if (moved) next.splice(index + offset, 0, moved);
304
- return next;
305
- })
306
- }
307
- onDelete={() => edit((current) => current.filter((item) => item.id !== prompt.id))}
308
- />
309
- ))}
310
- <SettingsCard>
311
- <SettingsAction
312
- label={prompts.length === 0 ? "No quick prompts yet" : `${prompts.length} of ${MAX_PROMPTS} quick prompts`}
313
- hint={`Labels can be up to ${LABEL_MAX_LENGTH} characters.`}
314
- actionLabel="Add quick prompt"
315
- disabled={disabled || prompts.length >= MAX_PROMPTS}
316
- onPress={() => edit((current) => [...current, { id: newPromptId(), label: "", text: "" }])}
317
528
  />
318
529
  </SettingsCard>
530
+ <Text style={styles.caption}>
531
+ {prompts.length === 0 ? "No quick prompts yet." : `${prompts.length} of ${MAX_PROMPTS} quick prompts.`} Labels
532
+ can be up to {LABEL_MAX_LENGTH} characters.
533
+ </Text>
319
534
  <SettingsCard>
320
535
  <SettingsSelect
321
536
  label="Show prompts as"
322
537
  hint="Separate pills show one pill per prompt; one menu pill keeps them in a single menu."
323
- value={values.display}
538
+ value={state.doc.values.display}
324
539
  options={DISPLAY_OPTIONS}
325
- disabled={disabled}
326
- onValueChange={(display) => editValues((current) => ({ ...current, display }))}
540
+ onValueChange={(display) => void store.save(setDisplay(display))}
327
541
  />
328
542
  </SettingsCard>
329
- {editing ? (
330
- <SettingsCard>
331
- <SettingsAction
332
- label="Unsaved changes"
333
- error={settings.saveError ?? validation.list}
334
- actionLabel={disabled ? "Saving…" : "Save"}
335
- disabled={disabled || !validation.valid}
336
- onPress={() => void save()}
337
- />
338
- <SettingsAction label="Discard changes" actionLabel="Discard" disabled={disabled} onPress={discard} />
339
- </SettingsCard>
340
- ) : null}
341
543
  <FindPromptsTip styles={styles} />
342
544
  </SettingsSection>
343
545
  );
@@ -345,25 +547,18 @@ function PromptLibrary({ settings, theme, layout }: { settings: ReadySettings }
345
547
 
346
548
  export function QuickPromptsSettingsScreen(props: PluginSurfaceProps) {
347
549
  const settings = useSettings(quickPromptsSettings);
348
- const style = useMemo(() => ({ color: props.theme.colors.foreground }), [props.theme]);
349
- if (settings.status === "loading") return <Text style={style}>Loading quick prompts…</Text>;
350
- if (settings.status !== "ready") {
351
- return (
352
- <SettingsSection title="Quick prompts">
353
- <Text style={style}>{settings.error}</Text>
354
- <SettingsCard>
355
- <SettingsAction label="Try again" actionLabel="Reload" onPress={() => void settings.reload()} />
356
- {settings.status === "invalid" ? (
357
- <SettingsAction
358
- label="Delete the saved quick prompts"
359
- hint="The stored data cannot be read."
360
- actionLabel="Reset"
361
- onPress={() => void settings.reset()}
362
- />
363
- ) : null}
364
- </SettingsCard>
365
- </SettingsSection>
366
- );
550
+ const styles = useStyles(props.theme, props.layout.compact);
551
+ // The editor starts from the first successful read and then stays mounted, so a later failed
552
+ // read does not take typed text with it.
553
+ const initial = useRef<SettingsDoc | null>(null);
554
+ if (!initial.current && settings.status === "ready") {
555
+ initial.current = { values: settings.values, revision: settings.revision };
367
556
  }
368
- return <PromptLibrary settings={settings} {...props} />;
557
+ if (initial.current) return <PromptLibrary initial={initial.current} settings={settings} {...props} />;
558
+ if (settings.status === "loading") return <Text style={styles.message}>Loading quick prompts…</Text>;
559
+ return (
560
+ <SettingsSection title="Quick prompts">
561
+ <LoadProblem settings={settings} styles={styles} onReload={() => void settings.reload()} />
562
+ </SettingsSection>
563
+ );
369
564
  }