@narumitw/pi-starship 0.59.1 → 0.60.0

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,9 +1,17 @@
1
- import type { ExtensionCommandContext } from "@earendil-works/pi-coding-agent";
1
+ import { type ExtensionCommandContext, withFileMutationQueue } from "@earendil-works/pi-coding-agent";
2
2
  import { sanitizeTerminalText } from "@narumitw/pi-tui-kit/terminal-text";
3
3
  import { type PreviewMenuResult, showPreviewActionMenu } from "./command-preview.js";
4
- import { BUILT_IN_EXAMPLE, type LoadedStarshipConfig, loadStarshipConfig } from "./config.js";
4
+ import {
5
+ assertConfigDocumentUnchanged,
6
+ BUILT_IN_EXAMPLE,
7
+ type ConfigDocumentSnapshot,
8
+ type LoadedStarshipConfig,
9
+ loadStarshipConfig,
10
+ readConfigDocumentSnapshot,
11
+ } from "./config.js";
5
12
  import { serializeEffectiveConfig } from "./effective-config.js";
6
13
  import { presetForDocument } from "./presets/catalog.js";
14
+ import { archiveConfigDocument } from "./profile-store.js";
7
15
 
8
16
  const RELOAD_ACTIONS = {
9
17
  apply: "apply",
@@ -13,6 +21,8 @@ const RELOAD_ACTIONS = {
13
21
  export interface WorkflowOwner {
14
22
  signal: AbortSignal;
15
23
  isCurrent(): boolean;
24
+ /** Session ownership independent of command cancellation and candidate/revision guards. */
25
+ isSessionCurrent?(): boolean;
16
26
  }
17
27
 
18
28
  export interface ConfigurationCommandOptions {
@@ -22,6 +32,7 @@ export interface ConfigurationCommandOptions {
22
32
  settingsPath: string;
23
33
  renderPreview?(loaded: LoadedStarshipConfig, width: number, ctx: ExtensionCommandContext): string[];
24
34
  read?: (settingsPath: string) => LoadedStarshipConfig;
35
+ archive?: typeof archiveConfigDocument;
25
36
  }
26
37
 
27
38
  export interface ConfigurationPresentation {
@@ -111,6 +122,12 @@ export function configurationMenuScreen(loaded: LoadedStarshipConfig) {
111
122
  description: "Review and preview remote TOML before replacing settings · requires gh",
112
123
  action: "gist-import" as const,
113
124
  },
125
+ {
126
+ id: "history",
127
+ label: "History",
128
+ description: "Review and restore recovery copies; legacy skill backups are read-only",
129
+ action: "history" as const,
130
+ },
114
131
  ],
115
132
  hint: "back" as const,
116
133
  };
@@ -141,6 +158,7 @@ export function effectiveConfigurationScreen(loaded: LoadedStarshipConfig) {
141
158
  "Normalized public TOML; comments and unknown fields are intentionally excluded.",
142
159
  ],
143
160
  content: serializeEffectiveConfig(loaded.config),
161
+ enableSearch: true,
144
162
  format: { kind: "code" as const, language: "toml" },
145
163
  viewportSize: "adaptive" as const,
146
164
  hint: "back" as const,
@@ -155,6 +173,7 @@ export function settingsDocumentScreen(loaded: LoadedStarshipConfig, settingsPat
155
173
  title: "Settings document",
156
174
  lines: ["Exact loaded UTF-8 text · display controls sanitized · read-only", `Path: ${path}`],
157
175
  content: loaded.rawDocument,
176
+ enableSearch: true,
158
177
  format: { kind: "code" as const, language: "toml" },
159
178
  viewportSize: "adaptive" as const,
160
179
  hint: "back" as const,
@@ -182,6 +201,13 @@ export async function reloadConfiguration(
182
201
  const previous = options.getLoaded();
183
202
  const revision = options.getLoadedRevision?.();
184
203
  const candidate = readReloadCandidate(options);
204
+ let disk: ConfigDocumentSnapshot;
205
+ try {
206
+ disk = readConfigDocumentSnapshot(options.settingsPath);
207
+ } catch (error) {
208
+ ctx.ui.notify(`Footer reload was blocked: ${safeError(error)}`, "error");
209
+ return "stay";
210
+ }
185
211
  if (!candidate.ok) {
186
212
  ctx.ui.notify(`Footer reload was blocked: ${safeError(candidate.error)}`, "error");
187
213
  return "stay";
@@ -210,47 +236,67 @@ export async function reloadConfiguration(
210
236
  "Apply configuration from disk?",
211
237
  candidate.loaded.rawDocument === undefined
212
238
  ? "Use built-in defaults for this session? No settings file will be created."
213
- : "Apply the validated settings document to this session without changing its bytes?",
239
+ : "Apply the validated settings document to this session without changing its bytes? The previous loaded document will be kept in History.",
240
+ { signal: owner.signal },
214
241
  );
215
242
  if (!isCurrentOwner(owner) || activeRevisionChanged(options, revision) || !confirmed) {
216
243
  return "stay";
217
244
  }
218
245
 
219
- const fresh = readReloadCandidate(options);
220
- if (!fresh.ok) {
221
- ctx.ui.notify(
222
- `Footer reload was blocked after confirmation: ${safeError(fresh.error)}. The previous footer remains active.`,
223
- "error",
224
- );
225
- return "stay";
226
- }
227
- if (!sameLoadedDocument(candidate.loaded, fresh.loaded)) {
228
- ctx.ui.notify(
229
- "The settings document changed after preview. The previous footer remains active; reload again to review the latest version.",
230
- "warning",
231
- );
232
- return "stay";
233
- }
234
-
246
+ let warnings = 0;
235
247
  try {
236
- options.apply(fresh.loaded, ctx);
248
+ const applied = await withFileMutationQueue(options.settingsPath, async () => {
249
+ if (
250
+ !isCurrentOwner(owner) ||
251
+ activeRevisionChanged(options, revision) ||
252
+ !sameLoadedDocument(previous, options.getLoaded())
253
+ )
254
+ return false;
255
+ assertConfigDocumentUnchanged(options.settingsPath, disk);
256
+ const fresh = readReloadCandidate(options);
257
+ if (!fresh.ok) throw new Error(fresh.error);
258
+ if (!sameLoadedDocument(candidate.loaded, fresh.loaded)) {
259
+ throw new Error(
260
+ "The settings document changed after preview. The previous footer remains active; reload again to review the latest version.",
261
+ );
262
+ }
263
+ let recoveryPath: string | undefined;
264
+ const previousBytes = previous.rawBytes ?? previous.rawDocument;
265
+ if (previousBytes !== undefined) {
266
+ recoveryPath = (options.archive ?? archiveConfigDocument)(options.settingsPath, previousBytes).path;
267
+ }
268
+ assertConfigDocumentUnchanged(options.settingsPath, disk);
269
+ if (!isCurrentOwner(owner) || activeRevisionChanged(options, revision)) return false;
270
+ try {
271
+ options.apply(fresh.loaded, ctx);
272
+ } catch (error) {
273
+ let rollbackError: unknown;
274
+ try {
275
+ if (!isCurrentOwner(owner)) throw new Error("The session owner changed; stale restoration was blocked");
276
+ const current = options.getLoaded();
277
+ if (!sameLoadedDocument(current, previous) && !sameLoadedDocument(current, fresh.loaded))
278
+ throw new Error("The active runtime changed; stale restoration was blocked");
279
+ options.apply(previous, ctx);
280
+ } catch (rollback) {
281
+ rollbackError = rollback;
282
+ }
283
+ throw new Error(
284
+ `Footer reload failed: ${formatError(error)}. ${
285
+ rollbackError
286
+ ? `Restoring the previous configuration also failed: ${formatError(rollbackError)}.`
287
+ : "The previous configuration was restored."
288
+ }${recoveryPath ? ` Recovery copy retained: ${recoveryPath}.` : ""}`,
289
+ );
290
+ }
291
+ warnings = fresh.loaded.diagnostics.length;
292
+ return true;
293
+ });
294
+ if (!isCurrentOwner(owner) || !applied) return "stay";
237
295
  } catch (error) {
238
- let rollbackError: unknown;
239
- try {
240
- options.apply(previous, ctx);
241
- } catch (rollback) {
242
- rollbackError = rollback;
243
- }
244
- ctx.ui.notify(
245
- rollbackError
246
- ? `Footer reload failed: ${safeError(error)}. Restoring the previous configuration also failed: ${safeError(rollbackError)}.`
247
- : `Footer reload failed: ${safeError(error)}. The previous configuration was restored.`,
248
- "error",
249
- );
296
+ if (isCurrentOwner(owner))
297
+ ctx.ui.notify(`Footer reload was blocked after confirmation: ${safeError(error)}`, "error");
250
298
  return "stay";
251
299
  }
252
-
253
- const warnings = fresh.loaded.diagnostics.length;
254
300
  ctx.ui.notify(
255
301
  warnings === 0
256
302
  ? "Footer configuration reloaded and applied."
@@ -8,6 +8,7 @@ import {
8
8
  BUILT_IN_EXAMPLE,
9
9
  type LoadedStarshipConfig,
10
10
  loadStarshipConfig,
11
+ readConfigDocumentSnapshot,
11
12
  validateConfigDocument,
12
13
  } from "./config.js";
13
14
  import { checkGistDocument, createSettingsGist, fetchSettingsGist, type GhApi, gistId } from "./gist.js";
@@ -91,8 +92,10 @@ export async function importSettingsGist(
91
92
  const previous = options.getLoaded();
92
93
  const revision = options.getLoadedRevision?.();
93
94
  const disk = diskSnapshot(options);
95
+ const initialDisk = readConfigDocumentSnapshot(options.settingsPath);
94
96
  const guardedOwner: WorkflowOwner = {
95
97
  signal: owner.signal,
98
+ isSessionCurrent: () => owner.isSessionCurrent?.() ?? owner.isCurrent(),
96
99
  isCurrent: () =>
97
100
  current(owner) &&
98
101
  options.getLoadedRevision?.() === revision &&
@@ -138,7 +141,7 @@ export async function importSettingsGist(
138
141
  [
139
142
  `Source: https://gist.github.com/${id}`,
140
143
  "Untrusted settings can enable local commands and network requests. Review the complete TOML before applying.",
141
- "Import replaces the entire local document, including comments and unknown fields; no backup is kept after success.",
144
+ "Import replaces the entire local document, including comments and unknown fields; its previous bytes will be kept in History.",
142
145
  ],
143
146
  "Preview imported footer…",
144
147
  );
@@ -152,7 +155,7 @@ export async function importSettingsGist(
152
155
  if (!current(guardedOwner) || diskSnapshot(options) !== disk) {
153
156
  throw new Error("Settings changed during import. Start a new import to review the latest state.");
154
157
  }
155
- return (options.save ?? atomicSaveConfigDocument)(path, raw);
158
+ return options.save ? options.save(path, raw) : atomicSaveConfigDocument(path, raw, {}, initialDisk);
156
159
  },
157
160
  },
158
161
  guardedOwner,
@@ -196,7 +199,12 @@ async function reviewDocument(
196
199
 
197
200
  function diskSnapshot(options: StarshipCommandOptions): string {
198
201
  const loaded = (options.read ?? loadStarshipConfig)(options.settingsPath);
199
- return JSON.stringify([loaded.rawDocument, loaded.source, loaded.diagnostics]);
202
+ return JSON.stringify([
203
+ loaded.rawDocument,
204
+ loaded.source,
205
+ loaded.diagnostics,
206
+ readConfigDocumentSnapshot(options.settingsPath),
207
+ ]);
200
208
  }
201
209
 
202
210
  function current(owner: WorkflowOwner): boolean {
@@ -5,6 +5,7 @@ import type { StarshipPreset } from "./presets/catalog.js";
5
5
  export type PresetPickerResult =
6
6
  | { kind: "apply"; presetId: StarshipPreset["id"] }
7
7
  | { kind: "customize"; presetId: StarshipPreset["id"] }
8
+ | { kind: "save-profile"; presetId: StarshipPreset["id"] }
8
9
  | { kind: "back" }
9
10
  | { kind: "close" };
10
11
 
@@ -40,7 +41,10 @@ export async function showPresetPicker(
40
41
  hint: "back",
41
42
  navigationLabel: "live preview",
42
43
  confirmLabel: "apply",
43
- shortcuts: [{ id: "customize", keys: ["e", "shift+e"], label: "customize" }],
44
+ shortcuts: [
45
+ { id: "customize", keys: ["e", "shift+e"], label: "customize" },
46
+ { id: "save-profile", keys: ["s", "shift+s"], label: "save as profile" },
47
+ ],
44
48
  onSelectionChange: ({ item }) => {
45
49
  const preset = options.presets.find((candidate) => candidate.id === item.id);
46
50
  if (preset) options.preview(preset);
@@ -50,7 +54,7 @@ export async function showPresetPicker(
50
54
  });
51
55
  if (result.kind === "selected") return { kind: "apply", presetId: result.itemId };
52
56
  if (result.kind === "shortcut") {
53
- return { kind: "customize", presetId: result.itemId };
57
+ return { kind: result.shortcutId === "save-profile" ? "save-profile" : "customize", presetId: result.itemId };
54
58
  }
55
59
  if (result.kind === "closed" && result.reason === "back") return { kind: "back" };
56
60
  return { kind: "close" };