@cueloop/client 0.1.0-alpha.5 → 0.1.0-alpha.50

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.
Files changed (152) hide show
  1. package/native/build-pty.sh +51 -0
  2. package/native/build.sh +82 -0
  3. package/native/darwin-arm64/libcuelooppty.dylib +0 -0
  4. package/native/darwin-arm64/libcueloopvt.dylib +0 -0
  5. package/native/src/pty.zig +193 -0
  6. package/native/src/shim.zig +114 -0
  7. package/package.json +36 -31
  8. package/src/App.autoclose.test.tsx +137 -0
  9. package/src/App.diff.test.tsx +158 -22
  10. package/src/App.export.test.tsx +44 -37
  11. package/src/App.plan-review.test.tsx +672 -0
  12. package/src/App.prototype.test.tsx +155 -0
  13. package/src/App.readonly.test.tsx +60 -36
  14. package/src/App.rendering.test.tsx +132 -0
  15. package/src/App.review-panel.test.tsx +136 -0
  16. package/src/App.submit-confirm.test.tsx +218 -0
  17. package/src/App.test.tsx +128 -69
  18. package/src/App.toast.test.tsx +75 -0
  19. package/src/App.tsx +0 -0
  20. package/src/App.walk.test.tsx +289 -0
  21. package/src/__snapshots__/view-plan.regression.test.ts.snap +100 -0
  22. package/src/attribution.test.ts +31 -0
  23. package/src/attribution.ts +38 -0
  24. package/src/clipboard.test.ts +23 -0
  25. package/src/clipboard.ts +30 -0
  26. package/src/components/AnnotationCard.compose-rows.test.ts +49 -0
  27. package/src/components/AnnotationCard.stories.tsx +94 -0
  28. package/src/components/AnnotationCard.tsx +241 -0
  29. package/src/components/Breadcrumb.stories.tsx +19 -0
  30. package/src/components/Breadcrumb.tsx +44 -0
  31. package/src/components/CodeBlock.stories.tsx +42 -0
  32. package/src/components/CodeBlock.tsx +83 -0
  33. package/src/components/CompletionOverlay.stories.tsx +23 -0
  34. package/src/components/CompletionOverlay.tsx +59 -0
  35. package/src/components/ConfirmCard.stories.tsx +35 -0
  36. package/src/components/ConfirmCard.tsx +127 -0
  37. package/src/components/ConfirmDialog.stories.tsx +21 -0
  38. package/src/components/ConfirmDialog.tsx +64 -0
  39. package/src/components/DiffSheet.scroll.test.tsx +123 -0
  40. package/src/components/DiffSheet.stories.tsx +78 -0
  41. package/src/components/DiffSheet.syntax.test.tsx +62 -0
  42. package/src/components/DiffSheet.tsx +355 -0
  43. package/src/components/InboxList.stories.tsx +31 -0
  44. package/src/components/InboxList.tsx +62 -0
  45. package/src/components/KeybindsDialog.stories.tsx +31 -0
  46. package/src/components/KeybindsDialog.tsx +58 -0
  47. package/src/components/MarkerPopover.stories.tsx +58 -0
  48. package/src/components/MarkerPopover.tsx +108 -0
  49. package/src/components/MenuBar.stories.tsx +37 -0
  50. package/src/components/MenuBar.tsx +74 -0
  51. package/src/components/PlanSheet.stories.tsx +113 -0
  52. package/src/components/PlanSheet.tsx +456 -0
  53. package/src/components/PromptDialog.stories.tsx +36 -0
  54. package/src/components/PromptDialog.tsx +78 -0
  55. package/src/components/PrototypeSheet.stories.tsx +20 -0
  56. package/src/components/PrototypeSheet.tsx +358 -0
  57. package/src/components/ReviewPanel.stories.tsx +86 -0
  58. package/src/components/ReviewPanel.tsx +101 -0
  59. package/src/components/ReviewRail.stories.tsx +218 -0
  60. package/src/components/ReviewRail.tsx +317 -0
  61. package/src/components/SettingsDialog.stories.tsx +111 -0
  62. package/src/components/SettingsDialog.tsx +141 -0
  63. package/src/components/SettingsRows.stories.tsx +18 -0
  64. package/src/components/SettingsRows.tsx +108 -0
  65. package/src/components/Toast.stories.tsx +12 -0
  66. package/src/components/Toast.tsx +44 -0
  67. package/src/components/WalkWizard.stories.tsx +100 -0
  68. package/src/components/WalkWizard.tsx +152 -0
  69. package/src/components/__snapshots__/stories.test.tsx.snap +1857 -0
  70. package/src/components/agent-launcher.stories.tsx +26 -0
  71. package/src/components/agent-launcher.test.tsx +49 -0
  72. package/src/components/agent-launcher.tsx +147 -0
  73. package/src/components/diff-sheet-layout.test.ts +127 -0
  74. package/src/components/diff-sheet-layout.ts +167 -0
  75. package/src/components/primitives/Button.stories.tsx +32 -0
  76. package/src/components/primitives/Button.tsx +51 -0
  77. package/src/components/primitives/Card.stories.tsx +25 -0
  78. package/src/components/primitives/Card.tsx +59 -0
  79. package/src/components/primitives/Dialog.stories.tsx +24 -0
  80. package/src/components/primitives/Dialog.tsx +64 -0
  81. package/src/components/primitives/StatusBar.stories.tsx +11 -0
  82. package/src/components/primitives/StatusBar.tsx +22 -0
  83. package/src/components/primitives/Tabs.stories.tsx +29 -0
  84. package/src/components/primitives/Tabs.tsx +98 -0
  85. package/src/components/primitives/Toolbar.stories.tsx +17 -0
  86. package/src/components/primitives/Toolbar.tsx +14 -0
  87. package/src/components/primitives/frame.test.ts +12 -0
  88. package/src/components/primitives/frame.ts +14 -0
  89. package/src/components/quick-actions-editor.stories.tsx +54 -0
  90. package/src/components/quick-actions-editor.tsx +136 -0
  91. package/src/components/stories-app.tsx +123 -0
  92. package/src/components/stories.test.tsx +62 -0
  93. package/src/components/story-fixtures.ts +98 -0
  94. package/src/components/story.ts +69 -0
  95. package/src/components/syntax-highlight.ts +92 -0
  96. package/src/components/terminal-pane.test.tsx +40 -0
  97. package/src/components/terminal-pane.ts +181 -0
  98. package/src/components/theme-context.stories.tsx +46 -0
  99. package/src/components/theme-context.tsx +36 -0
  100. package/src/components/truncate-text.ts +6 -0
  101. package/src/config.test.ts +430 -31
  102. package/src/config.ts +304 -26
  103. package/src/diff-hunk-curate.test.ts +315 -0
  104. package/src/diff-hunk-curate.ts +233 -0
  105. package/src/diff-intraline.test.ts +164 -0
  106. package/src/diff-intraline.ts +132 -0
  107. package/src/diff-syntax.test.ts +96 -0
  108. package/src/diff-syntax.ts +154 -0
  109. package/src/editor.test.ts +143 -0
  110. package/src/editor.ts +123 -9
  111. package/src/ghostty-terminal.test.ts +82 -0
  112. package/src/ghostty-terminal.ts +168 -0
  113. package/src/herdr.test.ts +41 -0
  114. package/src/herdr.ts +27 -0
  115. package/src/index.ts +10 -0
  116. package/src/integrations.test.ts +41 -0
  117. package/src/integrations.ts +30 -0
  118. package/src/intent-dispatch.test.ts +493 -0
  119. package/src/intent-dispatch.ts +428 -0
  120. package/src/key-bindings.test.ts +152 -0
  121. package/src/key-bindings.ts +430 -0
  122. package/src/keymap.test.ts +622 -0
  123. package/src/keymap.ts +339 -0
  124. package/src/kitty-image.test.ts +20 -0
  125. package/src/kitty-image.ts +75 -0
  126. package/src/prototype-browser.test.ts +55 -0
  127. package/src/prototype-browser.ts +243 -0
  128. package/src/pty.test.ts +78 -0
  129. package/src/pty.ts +222 -0
  130. package/src/review-panel.test.ts +113 -0
  131. package/src/review-panel.ts +83 -0
  132. package/src/run.ts +9 -5
  133. package/src/serve.test.ts +24 -9
  134. package/src/serve.ts +7 -7
  135. package/src/session-controller.curate.test.ts +253 -0
  136. package/src/session-controller.share.test.ts +309 -0
  137. package/src/session-controller.ts +914 -0
  138. package/src/share.ts +113 -0
  139. package/src/test-support.test.ts +55 -0
  140. package/src/test-support.ts +187 -0
  141. package/src/theme-presets.ts +168 -0
  142. package/src/theme.ts +38 -17
  143. package/src/version.ts +5 -0
  144. package/src/view-diff.test.ts +19 -8
  145. package/src/view-diff.ts +34 -23
  146. package/src/view-plan.regression.test.ts +60 -0
  147. package/src/view-plan.test.ts +399 -0
  148. package/src/view-plan.ts +495 -0
  149. package/src/walk.test.ts +121 -0
  150. package/src/walk.ts +70 -0
  151. package/src/view.test.ts +0 -157
  152. package/src/view.ts +0 -0
package/src/config.ts CHANGED
@@ -1,14 +1,20 @@
1
1
  /**
2
- * Layered TOML config (#20): built-in defaults → user config → trusted repo
2
+ * Layered TOML config: built-in defaults → user config → trusted repo
3
3
  * config → env. Sections: [keys] action = "combo" (every action rebindable),
4
- * [theme] per-token overrides, [integrations.obsidian] notes-vault export.
4
+ * [theme] per-token overrides, [ui] auto_close + editor + theme (a named
5
+ * preset) + the review-panel layout (review_width + review_state),
6
+ * [integrations.obsidian] notes-vault export.
5
7
  */
6
8
 
7
9
  import { existsSync, readFileSync } from "node:fs";
8
10
  import { homedir } from "node:os";
9
11
  import { join } from "node:path";
10
12
  import { OBSIDIAN_DEFAULTS, type ObsidianConfig } from "@cueloop/integration-obsidian";
13
+ import { writeFileSync, mkdirSync } from "node:fs";
14
+ import { dirname } from "node:path";
11
15
  import { DARK, type Theme } from "./theme";
16
+ import { DEFAULT_THEME_NAME, isThemeName, themeForName, type ThemeName } from "./theme-presets";
17
+ import { REVIEW_DEFAULT_WIDTH, clampWidth, type ReviewPanelMode } from "./review-panel";
12
18
 
13
19
  export interface KeymapConfig {
14
20
  [action: string]: string | string[];
@@ -18,9 +24,88 @@ export interface IntegrationsConfig {
18
24
  obsidian: ObsidianConfig;
19
25
  }
20
26
 
27
+ /** Post-submit behavior: "off" prompts, 0 closes instantly, N counts down. */
28
+ export type AutoClose = "off" | number;
29
+
30
+ /** One marker-popover quick action: a preset comment body, plus optional extra lines. */
31
+ export interface QuickAction {
32
+ prompt: string;
33
+ metadata?: string;
34
+ }
35
+
36
+ /** The built-in quick-actions for the marker popover when no `[[actions]]` are configured. */
37
+ export const DEFAULT_QUICK_ACTIONS: QuickAction[] = [
38
+ {
39
+ prompt: "Zoom out, research in depth",
40
+ metadata: "Research the broader problem, prior art, and alternatives before changing anything.",
41
+ },
42
+ {
43
+ prompt: "Restate simplified",
44
+ metadata: "Restate this as the simplest thing that works and cut the incidental complexity.",
45
+ },
46
+ {
47
+ prompt: "Out of scope",
48
+ metadata:
49
+ "This is out of scope for the task, so capture it as a follow-up instead of doing it now.",
50
+ },
51
+ {
52
+ prompt: "Let's chat about this",
53
+ metadata:
54
+ "Do not implement yet, and surface the open questions and trade-offs so we decide together.",
55
+ },
56
+ {
57
+ prompt: "Prototype this",
58
+ metadata: "Build a throwaway prototype to answer the question, skipping tests and polish.",
59
+ },
60
+ {
61
+ prompt: "Ensure 0 regressions",
62
+ metadata:
63
+ "Characterize the current behavior with tests first, then keep them green through the change.",
64
+ },
65
+ {
66
+ prompt: "Consider existing repo patterns",
67
+ metadata:
68
+ "Follow the nearest existing pattern in this codebase rather than introducing a new one.",
69
+ },
70
+ ];
71
+
72
+ /** The comment body a quick action expands to: the prompt, then its system prompt when set. */
73
+ export function quickActionBody(action: QuickAction): string {
74
+ return action.metadata ? `${action.prompt}\n\n${action.metadata}` : action.prompt;
75
+ }
76
+
77
+ /** Resolve a quick action by 1-based index or case-insensitive prompt; undefined when no match. */
78
+ export function resolveQuickAction(
79
+ actions: QuickAction[],
80
+ actionRef: string,
81
+ ): QuickAction | undefined {
82
+ const index = Number(actionRef);
83
+ if (Number.isInteger(index) && index >= 1 && index <= actions.length) return actions[index - 1];
84
+ const wanted = actionRef.trim().toLowerCase();
85
+ return actions.find((action) => action.prompt.toLowerCase() === wanted);
86
+ }
87
+
21
88
  export interface CueloopConfig {
22
89
  keys: Record<string, string[]>;
23
90
  theme: Theme;
91
+ /** The `[theme]` per-token overrides alone, so a live theme switch can re-compose them onto a new preset. */
92
+ themeOverrides: Partial<Theme>;
93
+ /**
94
+ * ui.reviewState / ui.reviewWidth are CLIENT VIEW STATE: the review panel's
95
+ * collapse mode and expanded-rail width, persisted so they survive restarts.
96
+ */
97
+ ui: {
98
+ autoClose: AutoClose;
99
+ editor?: string;
100
+ reviewState: ReviewPanelMode;
101
+ reviewWidth: number;
102
+ /** The selected theme preset name; its tokens are the base for `theme`, before any `[theme]` overrides. */
103
+ theme: ThemeName;
104
+ };
105
+ /** Planner-local author renames: identity id → display name ([authors] table). */
106
+ authors: Record<string, string>;
107
+ /** Marker-popover quick actions ([[actions]] tables); the 5 defaults when unset. */
108
+ actions: QuickAction[];
24
109
  integrations: IntegrationsConfig;
25
110
  }
26
111
 
@@ -32,14 +117,21 @@ export const DEFAULT_KEYS: Record<string, string[]> = {
32
117
  bottom: ["G"],
33
118
  span: ["v"],
34
119
  comment: ["c"],
35
- suggest: ["s"],
36
120
  cut: ["x"],
121
+ reject_hunk: ["X"],
122
+ restore_curation: ["u"],
37
123
  edit: ["e"],
38
124
  next_annotation: ["n"],
39
125
  prev_annotation: ["p"],
40
126
  delete_annotation: ["backspace"],
127
+ rename: ["r"],
41
128
  submit: ["return", "enter"],
129
+ share: ["S"],
42
130
  quit: ["q"],
131
+ walk: ["w"],
132
+ review_cycle: ["b"],
133
+ review_wider: ["]"],
134
+ review_narrower: ["["],
43
135
  };
44
136
 
45
137
  function parseToml(text: string): Record<string, unknown> {
@@ -47,67 +139,253 @@ function parseToml(text: string): Record<string, unknown> {
47
139
  return Bun.TOML.parse(text) as Record<string, unknown>;
48
140
  }
49
141
 
142
+ /**
143
+ * Parse a `[[actions]]` array-of-tables. A table without a non-empty `prompt`
144
+ * is skipped; any valid table REPLACES the defaults (the whole set is the
145
+ * user's, not merged). Returns undefined when nothing usable is present.
146
+ */
147
+ function parseActions(raw: unknown): QuickAction[] | undefined {
148
+ if (!Array.isArray(raw)) return undefined;
149
+ const actions: QuickAction[] = [];
150
+ for (const entry of raw) {
151
+ if (!entry || typeof entry !== "object") continue;
152
+ const table = entry as Record<string, unknown>;
153
+ const prompt = table["prompt"];
154
+ if (typeof prompt !== "string" || !prompt.trim()) continue;
155
+ const metadata = table["metadata"];
156
+ actions.push(
157
+ typeof metadata === "string" && metadata.trim() ? { prompt, metadata } : { prompt },
158
+ );
159
+ }
160
+ return actions.length ? actions : undefined;
161
+ }
162
+
50
163
  function layer(base: CueloopConfig, raw: Record<string, unknown>): CueloopConfig {
51
164
  const out: CueloopConfig = {
52
165
  keys: { ...base.keys },
53
166
  theme: { ...base.theme },
167
+ themeOverrides: { ...base.themeOverrides },
168
+ ui: { ...base.ui },
169
+ authors: { ...base.authors },
170
+ actions: [...base.actions],
54
171
  integrations: { obsidian: { ...base.integrations.obsidian } },
55
172
  };
173
+ const actions = parseActions(raw["actions"]);
174
+ if (actions) out.actions = actions;
175
+ const authors = raw["authors"] as Record<string, unknown> | undefined;
176
+ if (authors) {
177
+ for (const [id, value] of Object.entries(authors)) {
178
+ if (typeof value === "string") out.authors[id] = value;
179
+ }
180
+ }
56
181
  const keys = raw["keys"] as KeymapConfig | undefined;
57
182
  if (keys) {
58
183
  for (const [action, combo] of Object.entries(keys)) {
59
184
  out.keys[action] = Array.isArray(combo) ? combo : [combo];
60
185
  }
61
186
  }
62
- const theme = raw["theme"] as Partial<Record<keyof Theme, string>> | undefined;
63
- if (theme) {
64
- for (const [token, value] of Object.entries(theme)) {
65
- if (token in out.theme && typeof value === "string") {
66
- (out.theme as unknown as Record<string, string>)[token] = value;
67
- }
68
- }
187
+ const ui = raw["ui"] as
188
+ | { auto_close?: unknown; editor?: unknown; review_width?: unknown; review_state?: unknown }
189
+ | undefined;
190
+ if (ui && ui.auto_close !== undefined) {
191
+ if (ui.auto_close === "off") out.ui.autoClose = "off";
192
+ else if (typeof ui.auto_close === "number" && ui.auto_close >= 0)
193
+ out.ui.autoClose = ui.auto_close;
194
+ }
195
+ if (ui && typeof ui.editor === "string" && ui.editor.trim()) out.ui.editor = ui.editor.trim();
196
+ if (ui && typeof ui.review_width === "number" && Number.isFinite(ui.review_width)) {
197
+ out.ui.reviewWidth = clampWidth(ui.review_width);
198
+ }
199
+ if (
200
+ ui &&
201
+ (ui.review_state === "expanded" ||
202
+ ui.review_state === "compact" ||
203
+ ui.review_state === "hidden")
204
+ ) {
205
+ out.ui.reviewState = ui.review_state;
69
206
  }
70
207
  const integrations = raw["integrations"] as Record<string, unknown> | undefined;
71
208
  const obsidian = integrations?.["obsidian"] as Record<string, unknown> | undefined;
72
209
  if (obsidian) {
73
- const o = out.integrations.obsidian;
74
- if (typeof obsidian["vault"] === "string") o.vault = obsidian["vault"];
75
- if (typeof obsidian["folder"] === "string") o.folder = obsidian["folder"];
76
- if (typeof obsidian["filenameFormat"] === "string") o.filenameFormat = obsidian["filenameFormat"];
77
- const sep = obsidian["separator"];
78
- if (sep === "space" || sep === "dash" || sep === "underscore") o.separator = sep;
79
- const on = obsidian["exportOn"];
80
- if (on === "approve" || on === "resolve" || on === "manual") o.exportOn = on;
210
+ const obsidianConfig = out.integrations.obsidian;
211
+ if (typeof obsidian["vault"] === "string") obsidianConfig.vault = obsidian["vault"];
212
+ if (typeof obsidian["folder"] === "string") obsidianConfig.folder = obsidian["folder"];
213
+ if (typeof obsidian["filenameFormat"] === "string")
214
+ obsidianConfig.filenameFormat = obsidian["filenameFormat"];
215
+ const separator = obsidian["separator"];
216
+ if (separator === "space" || separator === "dash" || separator === "underscore")
217
+ obsidianConfig.separator = separator;
218
+ const exportOn = obsidian["exportOn"];
219
+ if (exportOn === "approve" || exportOn === "resolve" || exportOn === "manual")
220
+ obsidianConfig.exportOn = exportOn;
81
221
  }
82
222
  return out;
83
223
  }
84
224
 
85
- export function loadConfig(opts: { repoRoot?: string; userConfigPath?: string } = {}): CueloopConfig {
225
+ export function loadConfig(
226
+ options: { repoRoot?: string; userConfigPath?: string } = {},
227
+ ): CueloopConfig {
86
228
  let config: CueloopConfig = {
87
229
  keys: { ...DEFAULT_KEYS },
88
230
  theme: { ...DARK },
231
+ themeOverrides: {},
232
+ ui: {
233
+ autoClose: "off",
234
+ reviewState: "expanded",
235
+ reviewWidth: REVIEW_DEFAULT_WIDTH,
236
+ theme: DEFAULT_THEME_NAME,
237
+ },
238
+ authors: {},
239
+ actions: [...DEFAULT_QUICK_ACTIONS],
89
240
  integrations: { obsidian: { ...OBSIDIAN_DEFAULTS } },
90
241
  };
91
- const userPath =
92
- opts.userConfigPath ??
93
- process.env.CUELOOP_CONFIG ??
94
- join(process.env.XDG_CONFIG_HOME ?? join(homedir(), ".config"), "cueloop", "config.toml");
95
- for (const path of [userPath, opts.repoRoot ? join(opts.repoRoot, ".cueloop", "config.toml") : undefined]) {
242
+ // Theme name and per-token overrides are separate concerns, composed once
243
+ // after all layers: the last file to set [ui] theme wins, and every [theme]
244
+ // override from every file lands on top - so a later preset never discards an
245
+ // earlier file's token overrides.
246
+ let themeName = DEFAULT_THEME_NAME;
247
+ const themeOverrides: Partial<Record<keyof Theme, string>> = {};
248
+ const userPath = userConfigPathFrom(options.userConfigPath);
249
+ for (const path of [
250
+ userPath,
251
+ options.repoRoot ? join(options.repoRoot, ".cueloop", "config.toml") : undefined,
252
+ ]) {
96
253
  if (!path || !existsSync(path)) continue;
97
254
  try {
98
- config = layer(config, parseToml(readFileSync(path, "utf8")));
255
+ const raw = parseToml(readFileSync(path, "utf8"));
256
+ config = layer(config, raw);
257
+ const rawTheme = (raw["ui"] as { theme?: unknown } | undefined)?.theme;
258
+ if (typeof rawTheme === "string" && isThemeName(rawTheme)) themeName = rawTheme;
259
+ collectThemeOverrides(raw["theme"], themeOverrides);
99
260
  } catch {
100
261
  // a broken config never blocks a review; defaults win
101
262
  }
102
263
  }
264
+ config.ui.theme = themeName;
265
+ config.themeOverrides = themeOverrides;
266
+ config.theme = { ...themeForName(themeName), ...themeOverrides };
103
267
  return config;
104
268
  }
105
269
 
270
+ /** Merge a raw `[theme]` table's known string tokens into the accumulated overrides. */
271
+ function collectThemeOverrides(raw: unknown, into: Partial<Record<keyof Theme, string>>): void {
272
+ if (!raw || typeof raw !== "object") return;
273
+ for (const [token, value] of Object.entries(raw)) {
274
+ if (token in DARK && typeof value === "string") into[token as keyof Theme] = value;
275
+ }
276
+ }
277
+
106
278
  /** Reverse lookup: key name (+shift) → action, per the loaded keymap. */
107
- export function actionFor(keys: Record<string, string[]>, name: string, shift: boolean): string | undefined {
279
+ export function actionFor(
280
+ keys: Record<string, string[]>,
281
+ name: string,
282
+ shift: boolean,
283
+ ): string | undefined {
108
284
  const wanted = shift && name.length === 1 ? name.toUpperCase() : name;
109
285
  for (const [action, combos] of Object.entries(keys)) {
110
286
  if (combos.includes(wanted)) return action;
111
287
  }
112
288
  return undefined;
113
289
  }
290
+
291
+ function userConfigPathFrom(userConfigPath?: string): string {
292
+ return (
293
+ userConfigPath ??
294
+ process.env.CUELOOP_CONFIG ??
295
+ join(process.env.XDG_CONFIG_HOME ?? join(homedir(), ".config"), "cueloop", "config.toml")
296
+ );
297
+ }
298
+
299
+ /**
300
+ * Persist one `[ui]` key into the user config file. Line-level TOML surgery on
301
+ * the keys we own: replace the existing assignment, or drop it under an `[ui]`
302
+ * section (appending the section when absent) - a full TOML writer is not worth
303
+ * its weight here.
304
+ */
305
+ function persistUiSetting(key: string, rendered: string, userConfigPath?: string): void {
306
+ const path = userConfigPathFrom(userConfigPath);
307
+ let text = "";
308
+ if (existsSync(path)) text = readFileSync(path, "utf8");
309
+ const assignment = new RegExp(`^(\\s*)${key}\\s*=.*$`, "m");
310
+ if (assignment.test(text)) {
311
+ text = text.replace(assignment, `$1${key} = ${rendered}`);
312
+ } else if (/^\[ui\]/m.test(text)) {
313
+ text = text.replace(/^\[ui\]\s*$/m, `[ui]\n${key} = ${rendered}`);
314
+ } else {
315
+ text = text.trimEnd() + (text.trim() ? "\n\n" : "") + `[ui]\n${key} = ${rendered}\n`;
316
+ }
317
+ mkdirSync(dirname(path), { recursive: true });
318
+ writeFileSync(path, text);
319
+ }
320
+
321
+ /** A double-quoted TOML basic string with the quote-breaking characters escaped. */
322
+ function tomlString(value: string): string {
323
+ return `"${value.replace(/\\/g, "\\\\").replace(/"/g, '\\"').replace(/\n/g, "\\n")}"`;
324
+ }
325
+
326
+ /**
327
+ * Persist the whole quick-action set as `[[actions]]` tables, replacing any
328
+ * existing ones. The set is the user's entire vocabulary (not merged), so the
329
+ * old blocks are stripped and the new ones appended. An empty set clears them.
330
+ */
331
+ export function persistActions(actions: QuickAction[], userConfigPath?: string): void {
332
+ const path = userConfigPathFrom(userConfigPath);
333
+ let text = existsSync(path) ? readFileSync(path, "utf8") : "";
334
+ // strip every existing [[actions]] block (header through its key lines)
335
+ text = text.replace(/^\[\[actions\]\][^[]*/gm, "").trimEnd();
336
+ const blocks = actions
337
+ .map((action) => {
338
+ const lines = [`[[actions]]`, `prompt = ${tomlString(action.prompt)}`];
339
+ if (action.metadata) lines.push(`metadata = ${tomlString(action.metadata)}`);
340
+ return lines.join("\n");
341
+ })
342
+ .join("\n\n");
343
+ text = blocks ? `${text ? `${text}\n\n` : ""}${blocks}\n` : `${text}\n`;
344
+ mkdirSync(dirname(path), { recursive: true });
345
+ writeFileSync(path, text);
346
+ }
347
+
348
+ /** Persist the auto-close choice (`[ui] auto_close`) into the user config. */
349
+ export function persistAutoClose(value: AutoClose, userConfigPath?: string): void {
350
+ persistUiSetting("auto_close", value === "off" ? '"off"' : String(value), userConfigPath);
351
+ }
352
+
353
+ /** Persist the expanded-rail width (`[ui] review_width`) into the user config. */
354
+ export function persistReviewWidth(width: number, userConfigPath?: string): void {
355
+ persistUiSetting("review_width", String(clampWidth(width)), userConfigPath);
356
+ }
357
+
358
+ /** Persist the review-panel collapse mode (`[ui] review_state`) into the config. */
359
+ export function persistReviewState(state: ReviewPanelMode, userConfigPath?: string): void {
360
+ persistUiSetting("review_state", `"${state}"`, userConfigPath);
361
+ }
362
+
363
+ /** Persist the selected theme preset (`[ui] theme`) into the user config. */
364
+ export function persistTheme(name: ThemeName, userConfigPath?: string): void {
365
+ persistUiSetting("theme", `"${name}"`, userConfigPath);
366
+ }
367
+
368
+ function escapeRegExp(text: string): string {
369
+ return text.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
370
+ }
371
+
372
+ /**
373
+ * Persist an author rename into the `[authors]` table. The identity id (an SSH
374
+ * fingerprint) is not a bare TOML key, so it is written quoted.
375
+ */
376
+ export function persistAuthorName(id: string, name: string, userConfigPath?: string): void {
377
+ const path = userConfigPathFrom(userConfigPath);
378
+ let text = existsSync(path) ? readFileSync(path, "utf8") : "";
379
+ const key = `"${id.replace(/"/g, '\\"')}"`;
380
+ const value = `"${name.replace(/"/g, '\\"')}"`;
381
+ const assignment = new RegExp(`^(\\s*)${escapeRegExp(key)}\\s*=.*$`, "m");
382
+ if (assignment.test(text)) {
383
+ text = text.replace(assignment, `$1${key} = ${value}`);
384
+ } else if (/^\[authors\]/m.test(text)) {
385
+ text = text.replace(/^\[authors\]\s*$/m, `[authors]\n${key} = ${value}`);
386
+ } else {
387
+ text = text.trimEnd() + (text.trim() ? "\n\n" : "") + `[authors]\n${key} = ${value}\n`;
388
+ }
389
+ mkdirSync(dirname(path), { recursive: true });
390
+ writeFileSync(path, text);
391
+ }