@narumitw/pi-starship 0.59.2 → 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.
- package/README.md +28 -3
- package/dist/chunks/{chunk-MTFSZ63Q.ts → chunk-KZZKGGFW.ts} +327 -42
- package/dist/chunks/chunk-KZZKGGFW.ts.map +7 -0
- package/dist/chunks/{commands-K6T7PNEM.ts → commands-C2VJ6ZBN.ts} +1279 -111
- package/dist/chunks/commands-C2VJ6ZBN.ts.map +7 -0
- package/dist/index.ts +25 -9
- package/dist/index.ts.map +2 -2
- package/package.json +2 -2
- package/skills/configure-pi-starship/SKILL.md +5 -1
- package/skills/configure-pi-starship/references/configuration.md +122 -11
- package/skills/configure-pi-starship/scripts/apply.mjs +87 -33
- package/skills/configure-pi-starship/scripts/backup.mjs +17 -0
- package/src/command-commit.ts +169 -0
- package/src/command-configuration.ts +78 -34
- package/src/command-gist.ts +11 -3
- package/src/command-preset-picker.ts +6 -2
- package/src/command-profiles.ts +664 -0
- package/src/commands.ts +223 -77
- package/src/config.ts +112 -14
- package/src/format/formatter.ts +8 -4
- package/src/format/style.ts +54 -15
- package/src/format/terminal-safety.ts +80 -0
- package/src/format/theme-colors.ts +69 -0
- package/src/modules/model.ts +1 -1
- package/src/modules/render.ts +75 -5
- package/src/pi-starship.ts +22 -6
- package/src/profile-store.ts +526 -0
- package/dist/chunks/chunk-MTFSZ63Q.ts.map +0 -7
- package/dist/chunks/commands-K6T7PNEM.ts.map +0 -7
|
@@ -0,0 +1,664 @@
|
|
|
1
|
+
import type { ExtensionCommandContext } from "@earendil-works/pi-coding-agent";
|
|
2
|
+
import { isKeyRelease, Key, matchesKey } from "@earendil-works/pi-tui";
|
|
3
|
+
import { defineMenu, runLiveChoice, runMenu } from "@narumitw/pi-tui-kit";
|
|
4
|
+
import { sanitizeTerminalText } from "@narumitw/pi-tui-kit/terminal-text";
|
|
5
|
+
import type { WorkflowOwner } from "./command-configuration.js";
|
|
6
|
+
import type { StarshipCommandOptions } from "./commands.js";
|
|
7
|
+
import { BUILT_IN_EXAMPLE, type LoadedStarshipConfig, validateConfigDocument } from "./config.js";
|
|
8
|
+
import {
|
|
9
|
+
createProfile,
|
|
10
|
+
deleteHistory,
|
|
11
|
+
deleteProfile,
|
|
12
|
+
duplicateProfile,
|
|
13
|
+
type HistoryDocument,
|
|
14
|
+
listHistory,
|
|
15
|
+
listProfiles,
|
|
16
|
+
type ProfileDocument,
|
|
17
|
+
readHistory,
|
|
18
|
+
readProfile,
|
|
19
|
+
renameProfile,
|
|
20
|
+
saveProfile,
|
|
21
|
+
} from "./profile-store.js";
|
|
22
|
+
|
|
23
|
+
export type ProfileApplyCandidate = (
|
|
24
|
+
loaded: LoadedStarshipConfig,
|
|
25
|
+
owner: WorkflowOwner,
|
|
26
|
+
checkCandidate: () => void,
|
|
27
|
+
name: string,
|
|
28
|
+
) => Promise<"applied" | "stay" | "close">;
|
|
29
|
+
|
|
30
|
+
type Document = ProfileDocument | HistoryDocument;
|
|
31
|
+
type Exit = "back" | "close";
|
|
32
|
+
interface Action {
|
|
33
|
+
id: string;
|
|
34
|
+
label: string;
|
|
35
|
+
description?: string;
|
|
36
|
+
disabled?: boolean;
|
|
37
|
+
disabledReason?: string;
|
|
38
|
+
}
|
|
39
|
+
interface Candidate {
|
|
40
|
+
loaded?: LoadedStarshipConfig;
|
|
41
|
+
lines: string[];
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
const PREVIEW_NOTICE = "Preview uses the current runtime snapshot only; unavailable module data can be empty.";
|
|
45
|
+
const SAVE_CURRENT = "save-current";
|
|
46
|
+
class FlowEnded extends Error {}
|
|
47
|
+
|
|
48
|
+
/** Profiles are independent copies. Only applyCandidate may replace active settings. */
|
|
49
|
+
export async function showProfiles(
|
|
50
|
+
ctx: ExtensionCommandContext,
|
|
51
|
+
options: StarshipCommandOptions,
|
|
52
|
+
owner: WorkflowOwner,
|
|
53
|
+
applyCandidate: ProfileApplyCandidate,
|
|
54
|
+
): Promise<Exit> {
|
|
55
|
+
return browseDocuments(ctx, options, owner, applyCandidate, "profile");
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
export async function showHistory(
|
|
59
|
+
ctx: ExtensionCommandContext,
|
|
60
|
+
options: StarshipCommandOptions,
|
|
61
|
+
owner: WorkflowOwner,
|
|
62
|
+
applyCandidate: ProfileApplyCandidate,
|
|
63
|
+
): Promise<Exit> {
|
|
64
|
+
return browseDocuments(ctx, options, owner, applyCandidate, "history");
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
/** Reusable by reviewed preset/Gist candidates; never writes the active file. */
|
|
68
|
+
export async function saveAsProfile(
|
|
69
|
+
ctx: ExtensionCommandContext,
|
|
70
|
+
options: StarshipCommandOptions,
|
|
71
|
+
owner: WorkflowOwner,
|
|
72
|
+
raw: string,
|
|
73
|
+
): Promise<ProfileDocument | "close" | undefined> {
|
|
74
|
+
if (!interactive(ctx) || !current(owner)) return undefined;
|
|
75
|
+
const flow = createFlow(ctx, options, owner);
|
|
76
|
+
try {
|
|
77
|
+
candidateFor(options, raw, true);
|
|
78
|
+
const saved = await saveNamedCopy(ctx, options, flow, raw);
|
|
79
|
+
flow.ensure();
|
|
80
|
+
return saved;
|
|
81
|
+
} catch (error) {
|
|
82
|
+
if (flow.signal.aborted || !flow.sessionCurrent()) return "close";
|
|
83
|
+
report(ctx, flow, error);
|
|
84
|
+
return undefined;
|
|
85
|
+
} finally {
|
|
86
|
+
flow.dispose();
|
|
87
|
+
}
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
async function browseDocuments(
|
|
91
|
+
ctx: ExtensionCommandContext,
|
|
92
|
+
options: StarshipCommandOptions,
|
|
93
|
+
owner: WorkflowOwner,
|
|
94
|
+
applyCandidate: ProfileApplyCandidate,
|
|
95
|
+
kind: Document["kind"],
|
|
96
|
+
): Promise<Exit> {
|
|
97
|
+
if (!interactive(ctx) || !current(owner)) return "close";
|
|
98
|
+
const flow = createFlow(ctx, options, owner);
|
|
99
|
+
let selectedId: string | undefined;
|
|
100
|
+
try {
|
|
101
|
+
while (flow.current()) {
|
|
102
|
+
let interacted = false;
|
|
103
|
+
try {
|
|
104
|
+
const documents: Document[] =
|
|
105
|
+
kind === "profile" ? listProfiles(options.settingsPath) : listHistory(options.settingsPath);
|
|
106
|
+
const active = options.getLoaded();
|
|
107
|
+
const matches = documents.filter(
|
|
108
|
+
(document) => document.rawDocument !== undefined && document.rawDocument === active.rawDocument,
|
|
109
|
+
);
|
|
110
|
+
const candidates = new Map(
|
|
111
|
+
documents.map((document) => [documentId(document), candidateFor(options, document.rawDocument)]),
|
|
112
|
+
);
|
|
113
|
+
const selection = await runLiveChoice(ctx, {
|
|
114
|
+
title: kind === "profile" ? "Profiles" : "History",
|
|
115
|
+
lines: [
|
|
116
|
+
active.rawDocument === undefined && active.diagnostics.length === 0
|
|
117
|
+
? "Active: Built-in defaults"
|
|
118
|
+
: active.diagnostics.some((item) => item.severity === "error")
|
|
119
|
+
? "Active: Invalid settings document · replacement requires explicit recovery"
|
|
120
|
+
: "Active: Independent settings document",
|
|
121
|
+
...(kind === "profile" && matches.length === 0 ? ["Current settings are not saved as a profile"] : []),
|
|
122
|
+
PREVIEW_NOTICE,
|
|
123
|
+
],
|
|
124
|
+
items: [
|
|
125
|
+
...(kind === "profile"
|
|
126
|
+
? [
|
|
127
|
+
{
|
|
128
|
+
id: SAVE_CURRENT,
|
|
129
|
+
label: "Save current as…",
|
|
130
|
+
description: "Copy exact loaded TOML; keep active settings unchanged",
|
|
131
|
+
},
|
|
132
|
+
]
|
|
133
|
+
: []),
|
|
134
|
+
...documents.map((document) => ({
|
|
135
|
+
id: documentId(document),
|
|
136
|
+
label: safe(document.name),
|
|
137
|
+
description: [
|
|
138
|
+
...(document.kind === "history"
|
|
139
|
+
? [safe(document.createdAt), ...(document.legacy ? ["Legacy · read-only"] : [])]
|
|
140
|
+
: []),
|
|
141
|
+
...(document.rawDocument !== undefined && document.rawDocument === active.rawDocument
|
|
142
|
+
? ["Matches active settings"]
|
|
143
|
+
: []),
|
|
144
|
+
...(!candidates.get(documentId(document))?.loaded ? ["Invalid document · review or repair"] : []),
|
|
145
|
+
].join(" · "),
|
|
146
|
+
details: [
|
|
147
|
+
`Selected: ${safe(document.name)}`,
|
|
148
|
+
`Path: ${safe(document.path)}`,
|
|
149
|
+
...(candidates.get(documentId(document))?.lines ?? []),
|
|
150
|
+
],
|
|
151
|
+
})),
|
|
152
|
+
],
|
|
153
|
+
initialItemId: selectedId,
|
|
154
|
+
enableSearch: true,
|
|
155
|
+
viewportSize: 10,
|
|
156
|
+
hint: "back",
|
|
157
|
+
confirmLabel: "actions",
|
|
158
|
+
navigationLabel: "live preview",
|
|
159
|
+
signal: flow.signal,
|
|
160
|
+
isCurrent: flow.current,
|
|
161
|
+
onSelectionChange: ({ item, signal }) => {
|
|
162
|
+
if (signal.aborted || !flow.current()) return;
|
|
163
|
+
selectedId = item.id;
|
|
164
|
+
flow.preview(candidates.get(item.id)?.loaded);
|
|
165
|
+
},
|
|
166
|
+
});
|
|
167
|
+
flow.ensure();
|
|
168
|
+
interacted = true;
|
|
169
|
+
if (selection.kind !== "selected") {
|
|
170
|
+
return selection.kind === "closed" && selection.reason === "back" ? "back" : "close";
|
|
171
|
+
}
|
|
172
|
+
selectedId = selection.itemId;
|
|
173
|
+
if (selectedId === SAVE_CURRENT) {
|
|
174
|
+
flow.preview(undefined);
|
|
175
|
+
const loaded = options.getLoaded();
|
|
176
|
+
if (loaded.diagnostics.some((item) => item.severity === "error")) {
|
|
177
|
+
throw new Error(
|
|
178
|
+
"Cannot save unreadable or malformed active settings as a profile. Repair the settings document first.",
|
|
179
|
+
);
|
|
180
|
+
}
|
|
181
|
+
const raw = loaded.rawDocument ?? BUILT_IN_EXAMPLE;
|
|
182
|
+
candidateFor(options, raw, true);
|
|
183
|
+
const saved = await saveNamedCopy(ctx, options, flow, raw);
|
|
184
|
+
flow.ensure();
|
|
185
|
+
if (saved) selectedId = documentId(saved);
|
|
186
|
+
continue;
|
|
187
|
+
}
|
|
188
|
+
const document = documents.find((item) => documentId(item) === selectedId);
|
|
189
|
+
if (!document) continue;
|
|
190
|
+
flow.ensure(document);
|
|
191
|
+
const outcome = await documentActions(ctx, options, flow, document, applyCandidate);
|
|
192
|
+
flow.ensure();
|
|
193
|
+
if (outcome === "close") return "close";
|
|
194
|
+
if (outcome) selectedId = documentId(outcome);
|
|
195
|
+
} catch (error) {
|
|
196
|
+
if (error instanceof FlowEnded || !flow.current()) return "close";
|
|
197
|
+
flow.preview(undefined);
|
|
198
|
+
report(ctx, flow, error);
|
|
199
|
+
if (!interacted) return "close";
|
|
200
|
+
}
|
|
201
|
+
}
|
|
202
|
+
return "close";
|
|
203
|
+
} finally {
|
|
204
|
+
flow.dispose();
|
|
205
|
+
}
|
|
206
|
+
}
|
|
207
|
+
|
|
208
|
+
async function documentActions(
|
|
209
|
+
ctx: ExtensionCommandContext,
|
|
210
|
+
options: StarshipCommandOptions,
|
|
211
|
+
flow: ReturnType<typeof createFlow>,
|
|
212
|
+
document: Document,
|
|
213
|
+
applyCandidate: ProfileApplyCandidate,
|
|
214
|
+
): Promise<Document | "close" | undefined> {
|
|
215
|
+
const candidate = candidateFor(options, document.rawDocument);
|
|
216
|
+
const profile = document.kind === "profile";
|
|
217
|
+
const activeInvalid = profile && options.getLoaded().diagnostics.some((item) => item.severity === "error");
|
|
218
|
+
const action = await actionScreen(ctx, flow, {
|
|
219
|
+
title: `${profile ? "Profile" : "Recovery copy"}: ${safe(document.name)}`,
|
|
220
|
+
lines: [
|
|
221
|
+
`Path: ${safe(document.path)}`,
|
|
222
|
+
...(document.kind === "history"
|
|
223
|
+
? [`Recovery time: ${safe(document.createdAt)}`, "A recovery copy is not proof that an application succeeded."]
|
|
224
|
+
: []),
|
|
225
|
+
...(document.kind === "history" && document.legacy
|
|
226
|
+
? ["Legacy backup · read-only; restore copies bytes without changing this backup."]
|
|
227
|
+
: []),
|
|
228
|
+
...(document.readError ? [safe(document.readError)] : []),
|
|
229
|
+
...candidate.lines,
|
|
230
|
+
PREVIEW_NOTICE,
|
|
231
|
+
],
|
|
232
|
+
raw: document.rawDocument,
|
|
233
|
+
actions: [
|
|
234
|
+
{
|
|
235
|
+
id: "apply",
|
|
236
|
+
label: profile ? "Apply…" : "Restore…",
|
|
237
|
+
disabled: !candidate.loaded || activeInvalid,
|
|
238
|
+
disabledReason: activeInvalid
|
|
239
|
+
? "Repair active settings or use explicit recovery first"
|
|
240
|
+
: "Invalid TOML cannot be applied",
|
|
241
|
+
},
|
|
242
|
+
...(profile
|
|
243
|
+
? [
|
|
244
|
+
{ id: "edit", label: "Edit TOML…" },
|
|
245
|
+
{ id: "rename", label: "Rename…" },
|
|
246
|
+
{ id: "duplicate", label: "Duplicate…" },
|
|
247
|
+
]
|
|
248
|
+
: [
|
|
249
|
+
{
|
|
250
|
+
id: "save-as",
|
|
251
|
+
label: "Save as a profile…",
|
|
252
|
+
disabled: !candidate.loaded,
|
|
253
|
+
disabledReason: "Invalid TOML cannot be saved as a validated profile",
|
|
254
|
+
},
|
|
255
|
+
]),
|
|
256
|
+
{
|
|
257
|
+
id: "delete",
|
|
258
|
+
label: "Delete…",
|
|
259
|
+
disabled: document.kind === "history" && document.legacy,
|
|
260
|
+
disabledReason: "Legacy backups are read-only",
|
|
261
|
+
},
|
|
262
|
+
],
|
|
263
|
+
});
|
|
264
|
+
flow.ensure(document);
|
|
265
|
+
if (action === "close") return "close";
|
|
266
|
+
if (action === "back") return undefined;
|
|
267
|
+
if (action === "apply" && candidate.loaded) {
|
|
268
|
+
const result = await applyReviewedCandidate(flow, candidate.loaded, applyCandidate, document);
|
|
269
|
+
flow.ensure(document);
|
|
270
|
+
return result === "close" ? "close" : document;
|
|
271
|
+
}
|
|
272
|
+
if (action === "edit" && profile) {
|
|
273
|
+
const result = await editProfile(ctx, options, flow, document, applyCandidate);
|
|
274
|
+
flow.ensure();
|
|
275
|
+
return result;
|
|
276
|
+
}
|
|
277
|
+
if (action === "rename" && profile) {
|
|
278
|
+
const name = await flow.dialog(() =>
|
|
279
|
+
ctx.ui.input(`Rename profile: ${safe(document.name)}`, "New profile name", { signal: flow.signal }),
|
|
280
|
+
);
|
|
281
|
+
flow.ensure(document);
|
|
282
|
+
if (name === undefined) return document;
|
|
283
|
+
return renameProfile(options.settingsPath, document.name, name, document);
|
|
284
|
+
}
|
|
285
|
+
if (action === "duplicate" || (action === "save-as" && document.rawDocument !== undefined)) {
|
|
286
|
+
const saved = await saveNamedCopy(ctx, options, flow, document.rawDocument, document);
|
|
287
|
+
flow.ensure(document);
|
|
288
|
+
return action === "duplicate" || document.kind === "history" ? document : (saved ?? document);
|
|
289
|
+
}
|
|
290
|
+
if (action === "delete" && !(document.kind === "history" && document.legacy)) {
|
|
291
|
+
const confirmed = await flow.dialog(() =>
|
|
292
|
+
ctx.ui.confirm(
|
|
293
|
+
`Delete ${profile ? "profile" : "recovery copy"}: ${safe(document.name)}?`,
|
|
294
|
+
`Path: ${safe(document.path)}\n${profile ? "This deletes only the saved profile. The active settings copy remains unchanged." : "This permanently deletes only this recovery copy. Active settings remain unchanged."}`,
|
|
295
|
+
{ signal: flow.signal },
|
|
296
|
+
),
|
|
297
|
+
);
|
|
298
|
+
flow.ensure(document);
|
|
299
|
+
if (confirmed) {
|
|
300
|
+
if (document.kind === "profile") deleteProfile(options.settingsPath, document.name, document);
|
|
301
|
+
else deleteHistory(options.settingsPath, document.name, document);
|
|
302
|
+
}
|
|
303
|
+
}
|
|
304
|
+
return undefined;
|
|
305
|
+
}
|
|
306
|
+
|
|
307
|
+
async function editProfile(
|
|
308
|
+
ctx: ExtensionCommandContext,
|
|
309
|
+
options: StarshipCommandOptions,
|
|
310
|
+
flow: ReturnType<typeof createFlow>,
|
|
311
|
+
original: ProfileDocument,
|
|
312
|
+
applyCandidate: ProfileApplyCandidate,
|
|
313
|
+
): Promise<ProfileDocument | "close"> {
|
|
314
|
+
let draft = original.rawDocument ?? "";
|
|
315
|
+
if (original.rawDocument === undefined) {
|
|
316
|
+
const repair = await flow.dialog(() =>
|
|
317
|
+
ctx.ui.confirm(
|
|
318
|
+
`Repair invalid UTF-8 profile: ${safe(original.name)}?`,
|
|
319
|
+
`Path: ${safe(original.path)}\nThe original bytes cannot be edited as TOML text. Open an empty repair draft? Saving replaces these invalid bytes; the saved copy stays unchanged until you select Save profile. Duplicate it first to keep the original bytes.`,
|
|
320
|
+
{ signal: flow.signal },
|
|
321
|
+
),
|
|
322
|
+
);
|
|
323
|
+
flow.ensure(original);
|
|
324
|
+
if (!repair) return original;
|
|
325
|
+
}
|
|
326
|
+
while (flow.current()) {
|
|
327
|
+
// Pi's editor has no signal or public dismissal API. Drain it, then reject
|
|
328
|
+
// stale completion. The owner abort listener clears the footer immediately.
|
|
329
|
+
const edited = await flow.dialog(() => ctx.ui.editor(`Edit profile: ${safe(original.name)}`, draft));
|
|
330
|
+
flow.ensure(original);
|
|
331
|
+
if (edited === undefined) return original;
|
|
332
|
+
draft = edited;
|
|
333
|
+
const candidate = candidateFor(options, draft);
|
|
334
|
+
flow.preview(candidate.loaded);
|
|
335
|
+
const action = await actionScreen(ctx, flow, {
|
|
336
|
+
title: candidate.loaded ? "Profile draft preview" : "Profile draft needs attention",
|
|
337
|
+
lines: [
|
|
338
|
+
"Save profile changes only the saved copy, even when it matches active settings.",
|
|
339
|
+
...candidate.lines,
|
|
340
|
+
PREVIEW_NOTICE,
|
|
341
|
+
],
|
|
342
|
+
raw: draft,
|
|
343
|
+
actions: [
|
|
344
|
+
{
|
|
345
|
+
id: "save",
|
|
346
|
+
label: "Save profile",
|
|
347
|
+
disabled: !candidate.loaded,
|
|
348
|
+
disabledReason: "Repair the draft before saving",
|
|
349
|
+
},
|
|
350
|
+
{
|
|
351
|
+
id: "save-apply",
|
|
352
|
+
label: "Save profile and apply…",
|
|
353
|
+
description: "Two operations: a failed apply retains the saved profile",
|
|
354
|
+
disabled: !candidate.loaded,
|
|
355
|
+
disabledReason: "Repair the draft before saving",
|
|
356
|
+
},
|
|
357
|
+
{ id: "continue", label: "Continue editing" },
|
|
358
|
+
{ id: "discard", label: "Discard draft" },
|
|
359
|
+
],
|
|
360
|
+
});
|
|
361
|
+
flow.ensure(original);
|
|
362
|
+
if (action === "close") return "close";
|
|
363
|
+
if (action === "discard") return original;
|
|
364
|
+
if (action === "continue" || action === "back") continue;
|
|
365
|
+
if (!candidate.loaded || (action !== "save" && action !== "save-apply")) continue;
|
|
366
|
+
const saved = saveProfile(options.settingsPath, original.name, draft, original);
|
|
367
|
+
ctx.ui.notify(`Profile saved: ${safe(saved.name)}. Active settings are unchanged.`, "info");
|
|
368
|
+
if (action === "save-apply") {
|
|
369
|
+
try {
|
|
370
|
+
const result = await applyReviewedCandidate(flow, candidate.loaded, applyCandidate, saved);
|
|
371
|
+
flow.ensure(saved);
|
|
372
|
+
if (result === "close") return "close";
|
|
373
|
+
if (result !== "applied")
|
|
374
|
+
ctx.ui.notify(
|
|
375
|
+
"The profile was saved. Application did not complete; review the configuration result before retrying.",
|
|
376
|
+
"warning",
|
|
377
|
+
);
|
|
378
|
+
} catch (error) {
|
|
379
|
+
if (!flow.current()) throw error;
|
|
380
|
+
ctx.ui.notify(
|
|
381
|
+
`The saved profile was retained, but application did not complete: ${safeError(error)}. Review active settings before retrying.`,
|
|
382
|
+
"error",
|
|
383
|
+
);
|
|
384
|
+
}
|
|
385
|
+
}
|
|
386
|
+
return saved;
|
|
387
|
+
}
|
|
388
|
+
throw new FlowEnded();
|
|
389
|
+
}
|
|
390
|
+
|
|
391
|
+
async function applyReviewedCandidate(
|
|
392
|
+
flow: ReturnType<typeof createFlow>,
|
|
393
|
+
loaded: LoadedStarshipConfig,
|
|
394
|
+
applyCandidate: ProfileApplyCandidate,
|
|
395
|
+
document: Document,
|
|
396
|
+
) {
|
|
397
|
+
flow.ensure(document);
|
|
398
|
+
const result = await applyCandidate(
|
|
399
|
+
loaded,
|
|
400
|
+
{
|
|
401
|
+
signal: flow.signal,
|
|
402
|
+
// The shared commit policy captures the active revision before applying.
|
|
403
|
+
// A successful apply changes it; session ownership must remain valid after it.
|
|
404
|
+
isCurrent: () => !flow.signal.aborted && flow.sessionCurrent(),
|
|
405
|
+
isSessionCurrent: flow.sessionCurrent,
|
|
406
|
+
},
|
|
407
|
+
() => flow.ensure(document),
|
|
408
|
+
document.name,
|
|
409
|
+
);
|
|
410
|
+
// Only this operation may advance the loaded revision. Other awaits must keep
|
|
411
|
+
// the reviewed active revision; failed or cancelled applies cannot adopt it.
|
|
412
|
+
if (result === "applied") flow.adoptAppliedRevision();
|
|
413
|
+
flow.ensure(document);
|
|
414
|
+
flow.preview(undefined);
|
|
415
|
+
return result;
|
|
416
|
+
}
|
|
417
|
+
|
|
418
|
+
async function saveNamedCopy(
|
|
419
|
+
ctx: ExtensionCommandContext,
|
|
420
|
+
options: StarshipCommandOptions,
|
|
421
|
+
flow: ReturnType<typeof createFlow>,
|
|
422
|
+
raw: string | undefined,
|
|
423
|
+
source?: Document,
|
|
424
|
+
): Promise<ProfileDocument | undefined> {
|
|
425
|
+
while (flow.current()) {
|
|
426
|
+
const name = await flow.dialog(() =>
|
|
427
|
+
ctx.ui.input("Save as a profile", "Profile name (without .toml)", { signal: flow.signal }),
|
|
428
|
+
);
|
|
429
|
+
flow.ensure(source);
|
|
430
|
+
if (name === undefined) return undefined;
|
|
431
|
+
try {
|
|
432
|
+
const saved =
|
|
433
|
+
source?.kind === "profile"
|
|
434
|
+
? duplicateProfile(options.settingsPath, source.name, name, source)
|
|
435
|
+
: createProfile(options.settingsPath, name, requireText(raw));
|
|
436
|
+
ctx.ui.notify(`Profile saved: ${safe(saved.name)}. Active settings are unchanged.`, "info");
|
|
437
|
+
return saved;
|
|
438
|
+
} catch (error) {
|
|
439
|
+
report(ctx, flow, error);
|
|
440
|
+
}
|
|
441
|
+
}
|
|
442
|
+
throw new FlowEnded();
|
|
443
|
+
}
|
|
444
|
+
|
|
445
|
+
async function actionScreen(
|
|
446
|
+
ctx: ExtensionCommandContext,
|
|
447
|
+
flow: ReturnType<typeof createFlow>,
|
|
448
|
+
screen: { title: string; lines: string[]; actions: Action[]; raw: string | undefined },
|
|
449
|
+
): Promise<string> {
|
|
450
|
+
let selected: string | undefined;
|
|
451
|
+
const menu = defineMenu<undefined, "actions" | "document", "select">({
|
|
452
|
+
start: "actions",
|
|
453
|
+
screens: {
|
|
454
|
+
actions: () => ({
|
|
455
|
+
kind: "actions",
|
|
456
|
+
title: screen.title,
|
|
457
|
+
lines: screen.lines,
|
|
458
|
+
items: [
|
|
459
|
+
{
|
|
460
|
+
id: "review",
|
|
461
|
+
label: "Review TOML",
|
|
462
|
+
to: "document",
|
|
463
|
+
disabled: screen.raw === undefined,
|
|
464
|
+
disabledReason: "The document is not valid UTF-8",
|
|
465
|
+
},
|
|
466
|
+
...screen.actions.map((action) => ({ ...action, action: "select" as const })),
|
|
467
|
+
],
|
|
468
|
+
hint: "back",
|
|
469
|
+
}),
|
|
470
|
+
document: () => ({
|
|
471
|
+
kind: "review",
|
|
472
|
+
title: screen.title,
|
|
473
|
+
lines: ["Exact UTF-8 text · display controls sanitized · read-only"],
|
|
474
|
+
content: screen.raw ?? "The document is not valid UTF-8; no decoded fallback is shown.",
|
|
475
|
+
format: { kind: "code", language: "toml" },
|
|
476
|
+
enableSearch: true,
|
|
477
|
+
viewportSize: "adaptive",
|
|
478
|
+
hint: "back",
|
|
479
|
+
}),
|
|
480
|
+
},
|
|
481
|
+
actions: {
|
|
482
|
+
select: ({ itemId }) => {
|
|
483
|
+
flow.ensure();
|
|
484
|
+
selected = itemId;
|
|
485
|
+
return { kind: "close" };
|
|
486
|
+
},
|
|
487
|
+
},
|
|
488
|
+
});
|
|
489
|
+
const result = await runMenu(ctx, menu, { getState: () => undefined, signal: flow.signal, isCurrent: flow.current });
|
|
490
|
+
flow.ensure();
|
|
491
|
+
return selected ?? (result.kind === "closed" && result.reason === "back" ? "back" : "close");
|
|
492
|
+
}
|
|
493
|
+
|
|
494
|
+
function createFlow(ctx: ExtensionCommandContext, options: StarshipCommandOptions, owner: WorkflowOwner) {
|
|
495
|
+
const controller = new AbortController();
|
|
496
|
+
const signal = AbortSignal.any([controller.signal, owner.signal]);
|
|
497
|
+
let revision = options.getLoadedRevision?.();
|
|
498
|
+
let activeDocument = activeFingerprint(options.getLoaded());
|
|
499
|
+
let previewOwned = false;
|
|
500
|
+
const isCurrent = () =>
|
|
501
|
+
!signal.aborted &&
|
|
502
|
+
owner.isCurrent() &&
|
|
503
|
+
(revision === undefined
|
|
504
|
+
? activeFingerprint(options.getLoaded()) === activeDocument
|
|
505
|
+
: options.getLoadedRevision?.() === revision);
|
|
506
|
+
const clearPreview = () => {
|
|
507
|
+
if (!previewOwned) return;
|
|
508
|
+
previewOwned = false;
|
|
509
|
+
// The session owner, not a captured footer snapshot, decides whether cleanup
|
|
510
|
+
// can touch the UI, even after command cancellation. Runtime lifecycle
|
|
511
|
+
// cleanup owns a replaced session.
|
|
512
|
+
if (owner.isSessionCurrent?.() ?? owner.isCurrent()) {
|
|
513
|
+
try {
|
|
514
|
+
options.preview?.(undefined, ctx);
|
|
515
|
+
} catch (error) {
|
|
516
|
+
ctx.ui.notify(`Could not clear the footer preview: ${safeError(error)}`, "error");
|
|
517
|
+
}
|
|
518
|
+
}
|
|
519
|
+
};
|
|
520
|
+
const matches = (expected?: Document) => {
|
|
521
|
+
if (!isCurrent()) return false;
|
|
522
|
+
if (!expected) return true;
|
|
523
|
+
try {
|
|
524
|
+
const fresh =
|
|
525
|
+
expected.kind === "profile"
|
|
526
|
+
? readProfile(options.settingsPath, expected.name)
|
|
527
|
+
: readHistory(options.settingsPath, expected.name);
|
|
528
|
+
return (
|
|
529
|
+
fresh.rawDocument === expected.rawDocument &&
|
|
530
|
+
fresh.identity.dev === expected.identity.dev &&
|
|
531
|
+
fresh.identity.ino === expected.identity.ino &&
|
|
532
|
+
fresh.identity.size === expected.identity.size &&
|
|
533
|
+
fresh.identity.mtimeNs === expected.identity.mtimeNs &&
|
|
534
|
+
fresh.identity.ctimeNs === expected.identity.ctimeNs &&
|
|
535
|
+
fresh.rawBytes.equals(expected.rawBytes)
|
|
536
|
+
);
|
|
537
|
+
} catch {
|
|
538
|
+
return false;
|
|
539
|
+
}
|
|
540
|
+
};
|
|
541
|
+
const ensure = (expected?: Document) => {
|
|
542
|
+
if (!isCurrent()) throw new FlowEnded();
|
|
543
|
+
if (!matches(expected))
|
|
544
|
+
throw new Error("The selected document changed or was removed. Review the latest copy before trying again.");
|
|
545
|
+
};
|
|
546
|
+
signal.addEventListener("abort", clearPreview, { once: true });
|
|
547
|
+
return {
|
|
548
|
+
signal,
|
|
549
|
+
current: isCurrent,
|
|
550
|
+
sessionCurrent: () => owner.isSessionCurrent?.() ?? owner.isCurrent(),
|
|
551
|
+
ensure,
|
|
552
|
+
preview(loaded: LoadedStarshipConfig | undefined) {
|
|
553
|
+
ensure();
|
|
554
|
+
if (!loaded) {
|
|
555
|
+
clearPreview();
|
|
556
|
+
return;
|
|
557
|
+
}
|
|
558
|
+
previewOwned = true;
|
|
559
|
+
try {
|
|
560
|
+
options.preview?.(loaded, ctx);
|
|
561
|
+
} catch (error) {
|
|
562
|
+
clearPreview();
|
|
563
|
+
throw error;
|
|
564
|
+
}
|
|
565
|
+
},
|
|
566
|
+
async dialog<Value>(run: () => Promise<Value>): Promise<Value> {
|
|
567
|
+
ensure();
|
|
568
|
+
// Native dialogs collapse Escape and Ctrl+C into one result. Observe only
|
|
569
|
+
// hard cancellation; never consume, rewrite, or forward editor content.
|
|
570
|
+
const unsubscribe = ctx.ui.onTerminalInput((data) => {
|
|
571
|
+
if (!isKeyRelease(data) && matchesKey(data, Key.ctrl("c"))) {
|
|
572
|
+
// Abort after native input dispatch, before its promise continuation.
|
|
573
|
+
// Synchronous abort could restore focus and leak this key to Pi's editor.
|
|
574
|
+
queueMicrotask(() => controller.abort());
|
|
575
|
+
}
|
|
576
|
+
return undefined;
|
|
577
|
+
});
|
|
578
|
+
let released = false;
|
|
579
|
+
const release = () => {
|
|
580
|
+
if (released) return;
|
|
581
|
+
released = true;
|
|
582
|
+
unsubscribe();
|
|
583
|
+
};
|
|
584
|
+
signal.addEventListener("abort", release, { once: true });
|
|
585
|
+
try {
|
|
586
|
+
if (signal.aborted) release();
|
|
587
|
+
ensure();
|
|
588
|
+
const result = await run();
|
|
589
|
+
ensure();
|
|
590
|
+
return result;
|
|
591
|
+
} finally {
|
|
592
|
+
signal.removeEventListener("abort", release);
|
|
593
|
+
release();
|
|
594
|
+
}
|
|
595
|
+
},
|
|
596
|
+
adoptAppliedRevision() {
|
|
597
|
+
if (signal.aborted || !(owner.isSessionCurrent?.() ?? owner.isCurrent())) throw new FlowEnded();
|
|
598
|
+
revision = options.getLoadedRevision?.();
|
|
599
|
+
activeDocument = activeFingerprint(options.getLoaded());
|
|
600
|
+
},
|
|
601
|
+
dispose() {
|
|
602
|
+
try {
|
|
603
|
+
clearPreview();
|
|
604
|
+
} finally {
|
|
605
|
+
signal.removeEventListener("abort", clearPreview);
|
|
606
|
+
controller.abort();
|
|
607
|
+
}
|
|
608
|
+
},
|
|
609
|
+
};
|
|
610
|
+
}
|
|
611
|
+
|
|
612
|
+
function candidateFor(options: StarshipCommandOptions, raw: string | undefined, required = false): Candidate {
|
|
613
|
+
try {
|
|
614
|
+
if (raw === undefined) throw new Error("The document is not valid UTF-8; no decoded fallback is shown.");
|
|
615
|
+
const loaded = (options.validate ?? validateConfigDocument)(options.settingsPath, raw);
|
|
616
|
+
if (loaded.diagnostics.some((item) => item.severity === "error"))
|
|
617
|
+
throw new Error(loaded.diagnostics.map((item) => item.message).join("; "));
|
|
618
|
+
return {
|
|
619
|
+
loaded,
|
|
620
|
+
lines:
|
|
621
|
+
loaded.diagnostics.length === 0
|
|
622
|
+
? ["No configuration warnings."]
|
|
623
|
+
: loaded.diagnostics.map((item) => `${safe(item.path || "root")}: ${safe(item.message)}`),
|
|
624
|
+
};
|
|
625
|
+
} catch (error) {
|
|
626
|
+
if (required) throw error;
|
|
627
|
+
return { lines: [`Invalid TOML: ${safeError(error)}`, "No candidate footer preview is shown."] };
|
|
628
|
+
}
|
|
629
|
+
}
|
|
630
|
+
|
|
631
|
+
function requireText(raw: string | undefined): string {
|
|
632
|
+
if (raw === undefined) throw new Error("The document is not valid UTF-8; no decoded fallback can be saved.");
|
|
633
|
+
return raw;
|
|
634
|
+
}
|
|
635
|
+
|
|
636
|
+
function activeFingerprint(loaded: LoadedStarshipConfig) {
|
|
637
|
+
return JSON.stringify([loaded.source, loaded.rawDocument, loaded.diagnostics]);
|
|
638
|
+
}
|
|
639
|
+
|
|
640
|
+
function current(owner: WorkflowOwner) {
|
|
641
|
+
return !owner.signal.aborted && owner.isCurrent();
|
|
642
|
+
}
|
|
643
|
+
|
|
644
|
+
function interactive(ctx: ExtensionCommandContext) {
|
|
645
|
+
if (ctx.mode === "tui" && ctx.hasUI) return true;
|
|
646
|
+
if (ctx.hasUI) ctx.ui.notify("Profiles and History require TUI mode.", "info");
|
|
647
|
+
return false;
|
|
648
|
+
}
|
|
649
|
+
|
|
650
|
+
function documentId(document: Document) {
|
|
651
|
+
return `${document.kind}:${document.name}`;
|
|
652
|
+
}
|
|
653
|
+
|
|
654
|
+
function report(ctx: ExtensionCommandContext, flow: ReturnType<typeof createFlow>, error: unknown) {
|
|
655
|
+
if (!(error instanceof FlowEnded) && flow.current()) ctx.ui.notify(safeError(error), "error");
|
|
656
|
+
}
|
|
657
|
+
|
|
658
|
+
function safeError(error: unknown) {
|
|
659
|
+
return safe(error instanceof Error ? error.message : String(error));
|
|
660
|
+
}
|
|
661
|
+
|
|
662
|
+
function safe(value: string) {
|
|
663
|
+
return sanitizeTerminalText(value);
|
|
664
|
+
}
|