claudeup 4.19.0 → 4.23.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.
Files changed (182) hide show
  1. package/bin/claudeup.js +43 -19
  2. package/package.json +14 -19
  3. package/scripts/build-binaries.ts +77 -0
  4. package/scripts/check-optional-deps.ts +49 -0
  5. package/scripts/test-isolated.ts +43 -0
  6. package/src/__tests__/cli-router.test.ts +65 -0
  7. package/src/__tests__/conventions-integration.test.ts +745 -0
  8. package/src/__tests__/conventions-manager.test.ts +1172 -0
  9. package/src/__tests__/doctor-bins.test.ts +35 -0
  10. package/src/__tests__/doctor.test.ts +450 -0
  11. package/src/__tests__/dual-write-prevention.test.ts +14 -4
  12. package/src/__tests__/file-locking.test.ts +208 -0
  13. package/src/__tests__/gitignore-prerun.test.ts +1 -0
  14. package/src/__tests__/install-command.test.ts +81 -0
  15. package/src/__tests__/install-plan.test.ts +98 -0
  16. package/src/__tests__/manifest.test.ts +136 -0
  17. package/src/__tests__/marketplace-badge.test.ts +91 -0
  18. package/src/__tests__/marketplace-refresh.test.ts +267 -0
  19. package/src/__tests__/plugin-requires.test.ts +133 -0
  20. package/src/__tests__/plugin-setup.test.ts +7 -0
  21. package/src/__tests__/profile-command.test.ts +116 -0
  22. package/src/__tests__/profile-materializer.test.ts +82 -0
  23. package/src/__tests__/profile-sync.test.ts +136 -0
  24. package/src/__tests__/registry-version-resolution.test.ts +74 -0
  25. package/src/__tests__/resolve-executable.test.ts +42 -0
  26. package/src/__tests__/resolver.test.ts +218 -0
  27. package/src/__tests__/symlink-manager.test.ts +99 -0
  28. package/src/__tests__/toolchain.test.ts +56 -0
  29. package/src/cli/claude.ts +21 -0
  30. package/src/cli/doctor.ts +132 -0
  31. package/src/cli/install.ts +360 -0
  32. package/src/cli/profile.ts +166 -0
  33. package/src/cli/router.ts +107 -0
  34. package/src/cli/update.ts +85 -0
  35. package/src/data/cli-tools.ts +7 -7
  36. package/src/data/gitignore-defaults.ts +4 -0
  37. package/src/data/marketplaces.ts +12 -0
  38. package/src/data/predefined-profiles.ts +3 -4
  39. package/src/main.tsx +11 -154
  40. package/src/prerunner/index.ts +62 -27
  41. package/src/services/claude-cli.ts +19 -22
  42. package/src/services/claude-settings.ts +99 -26
  43. package/src/services/conventions-manager.ts +865 -0
  44. package/src/services/doctor-bins.ts +49 -0
  45. package/src/services/doctor.ts +509 -0
  46. package/src/services/install-plan.ts +107 -0
  47. package/src/services/manifest.ts +166 -0
  48. package/src/services/marketplace-refresh.ts +173 -0
  49. package/src/services/plugin-manager.ts +7 -1
  50. package/src/services/plugin-requires.ts +215 -0
  51. package/src/services/plugin-version-check.ts +9 -4
  52. package/src/services/profile-materializer.ts +61 -0
  53. package/src/services/profile-sync.ts +150 -0
  54. package/src/services/resolver.ts +293 -0
  55. package/src/services/symlink-manager.ts +146 -0
  56. package/src/services/toolchain.ts +97 -0
  57. package/src/services/version-check.ts +10 -11
  58. package/src/types/index.ts +138 -31
  59. package/src/ui/App.tsx +0 -4
  60. package/src/ui/adapters/pluginsAdapter.ts +13 -0
  61. package/src/ui/screens/CliToolsScreen.tsx +11 -3
  62. package/src/ui/screens/index.ts +0 -1
  63. package/src/ui/state/reducer.ts +0 -101
  64. package/src/ui/state/types.ts +0 -35
  65. package/src/utils/command-utils.ts +23 -0
  66. package/src/utils/file-locking.ts +144 -0
  67. package/src/data/alias-flags.js +0 -205
  68. package/src/data/cli-tools.js +0 -123
  69. package/src/data/gitignore-defaults.js +0 -24
  70. package/src/data/gitignore-reasons.js +0 -97
  71. package/src/data/gitignore-templates.js +0 -21
  72. package/src/data/marketplaces.js +0 -138
  73. package/src/data/mcp-servers.js +0 -509
  74. package/src/data/predefined-profiles.js +0 -248
  75. package/src/data/settings-catalog.js +0 -625
  76. package/src/data/skill-repos.js +0 -160
  77. package/src/data/statuslines.js +0 -159
  78. package/src/data/statuslines.ts +0 -188
  79. package/src/index.js +0 -4
  80. package/src/index.ts +0 -5
  81. package/src/main.js +0 -170
  82. package/src/prerunner/index.js +0 -252
  83. package/src/services/alias-settings.js +0 -51
  84. package/src/services/alias-shell-writer.js +0 -1018
  85. package/src/services/alias-store.js +0 -129
  86. package/src/services/claude-cli.js +0 -189
  87. package/src/services/claude-runner.js +0 -28
  88. package/src/services/claude-settings.js +0 -1223
  89. package/src/services/gitignore-detector.js +0 -155
  90. package/src/services/gitignore-fixer.js +0 -231
  91. package/src/services/gitignore-prerun.js +0 -46
  92. package/src/services/gitignore-resolver.js +0 -143
  93. package/src/services/gitignore-service.js +0 -117
  94. package/src/services/local-marketplace.js +0 -339
  95. package/src/services/marketplace-fetcher.js +0 -96
  96. package/src/services/marketplace-sync.js +0 -94
  97. package/src/services/mcp-registry.js +0 -87
  98. package/src/services/plugin-manager.js +0 -473
  99. package/src/services/plugin-mcp-config.js +0 -177
  100. package/src/services/plugin-setup.js +0 -499
  101. package/src/services/plugin-version-check.js +0 -262
  102. package/src/services/profiles.js +0 -161
  103. package/src/services/settings-manager.js +0 -243
  104. package/src/services/skills-manager.js +0 -393
  105. package/src/services/skillsmp-client.js +0 -87
  106. package/src/services/update-cache.js +0 -52
  107. package/src/services/version-check.js +0 -99
  108. package/src/types/gitignore.js +0 -6
  109. package/src/types/index.js +0 -1
  110. package/src/ui/App.js +0 -355
  111. package/src/ui/adapters/pluginsAdapter.js +0 -139
  112. package/src/ui/adapters/settingsAdapter.js +0 -111
  113. package/src/ui/adapters/skillsAdapter.js +0 -154
  114. package/src/ui/components/CategoryHeader.js +0 -9
  115. package/src/ui/components/EmptyFilterState.js +0 -4
  116. package/src/ui/components/FlagDetailEditor.js +0 -0
  117. package/src/ui/components/ScopeIndicator.js +0 -30
  118. package/src/ui/components/ScrollableList.js +0 -36
  119. package/src/ui/components/SearchInput.js +0 -19
  120. package/src/ui/components/StyledText.js +0 -39
  121. package/src/ui/components/TabBar.js +0 -19
  122. package/src/ui/components/layout/FooterHints.js +0 -29
  123. package/src/ui/components/layout/Panel.js +0 -6
  124. package/src/ui/components/layout/ProgressBar.js +0 -14
  125. package/src/ui/components/layout/ScopeTabs.js +0 -6
  126. package/src/ui/components/layout/ScreenLayout.js +0 -16
  127. package/src/ui/components/layout/index.js +0 -5
  128. package/src/ui/components/modals/ConfirmModal.js +0 -14
  129. package/src/ui/components/modals/InputModal.js +0 -5
  130. package/src/ui/components/modals/LoadingModal.js +0 -17
  131. package/src/ui/components/modals/MessageModal.js +0 -16
  132. package/src/ui/components/modals/ModalContainer.js +0 -137
  133. package/src/ui/components/modals/SelectModal.js +0 -18
  134. package/src/ui/components/modals/VersionMismatchModal.js +0 -36
  135. package/src/ui/components/modals/index.js +0 -6
  136. package/src/ui/components/primitives/ActionHints.js +0 -13
  137. package/src/ui/components/primitives/DetailSection.js +0 -7
  138. package/src/ui/components/primitives/KeyValueLine.js +0 -8
  139. package/src/ui/components/primitives/ListCategoryRow.js +0 -8
  140. package/src/ui/components/primitives/MetaText.js +0 -8
  141. package/src/ui/components/primitives/ScopeDetail.js +0 -32
  142. package/src/ui/components/primitives/ScopeSquares.js +0 -11
  143. package/src/ui/components/primitives/SelectableRow.js +0 -5
  144. package/src/ui/components/primitives/index.js +0 -8
  145. package/src/ui/hooks/index.js +0 -4
  146. package/src/ui/hooks/useAsyncData.js +0 -77
  147. package/src/ui/hooks/useGitignoreModal.js +0 -74
  148. package/src/ui/hooks/useKeyboard.js +0 -13
  149. package/src/ui/hooks/useKeyboardHandler.js +0 -39
  150. package/src/ui/hooks/useMismatchModal.js +0 -77
  151. package/src/ui/registry.js +0 -1
  152. package/src/ui/renderers/cliToolRenderers.js +0 -54
  153. package/src/ui/renderers/gitignoreRenderers.js +0 -46
  154. package/src/ui/renderers/mcpRenderers.js +0 -26
  155. package/src/ui/renderers/pluginRenderers.js +0 -124
  156. package/src/ui/renderers/profileRenderers.js +0 -177
  157. package/src/ui/renderers/settingsRenderers.js +0 -73
  158. package/src/ui/renderers/skillRenderers.js +0 -138
  159. package/src/ui/screens/AliasScreen.js +0 -1111
  160. package/src/ui/screens/CliToolsScreen.js +0 -338
  161. package/src/ui/screens/EnvVarsScreen.js +0 -152
  162. package/src/ui/screens/GitignoreScreen.js +0 -328
  163. package/src/ui/screens/McpRegistryScreen.js +0 -238
  164. package/src/ui/screens/McpScreen.js +0 -176
  165. package/src/ui/screens/ModelSelectorScreen.js +0 -296
  166. package/src/ui/screens/ModelSelectorScreen.tsx +0 -444
  167. package/src/ui/screens/PluginsScreen.js +0 -769
  168. package/src/ui/screens/ProfilesScreen.js +0 -298
  169. package/src/ui/screens/SkillsScreen.js +0 -549
  170. package/src/ui/screens/StatusLineScreen.js +0 -206
  171. package/src/ui/screens/StatusLineScreen.tsx +0 -416
  172. package/src/ui/screens/index.js +0 -10
  173. package/src/ui/state/AnimationContext.js +0 -34
  174. package/src/ui/state/AppContext.js +0 -162
  175. package/src/ui/state/DimensionsContext.js +0 -71
  176. package/src/ui/state/reducer.js +0 -547
  177. package/src/ui/state/types.js +0 -1
  178. package/src/ui/theme.js +0 -47
  179. package/src/utils/clipboard.js +0 -56
  180. package/src/utils/command-utils.js +0 -19
  181. package/src/utils/fuzzy-search.js +0 -101
  182. package/src/utils/string-utils.js +0 -62
@@ -1,1111 +0,0 @@
1
- import { jsx as _jsx, jsxs as _jsxs, Fragment as _Fragment } from "@opentui/react/jsx-runtime";
2
- import { useEffect, useState, useCallback, useMemo, useRef } from "react";
3
- import { useApp, useModal } from "../state/AppContext.js";
4
- import { useKeyboardHandler } from "../hooks/useKeyboardHandler.js";
5
- import { ScreenLayout } from "../components/layout/index.js";
6
- import { FlagDetailEditor } from "../components/FlagDetailEditor.js";
7
- import { ALIAS_FLAGS, FLAG_GROUPS, } from "../../data/alias-flags.js";
8
- import { defaultAliasConfig, defaultValueFor, validateAliasName, derivedChannelValues, withoutDerivedChannel, CHANNELS_FLAG_ID, DEFAULT_ALIAS_NAME, } from "../../services/alias-store.js";
9
- import { loadAliasName, saveAliasName } from "../../services/alias-settings.js";
10
- import { detectShells, renderArgs, validateConfig, writeAliasToShell, parseAliasFromRc, findAdoptableAlias, } from "../../services/alias-shell-writer.js";
11
- import { readFile } from "node:fs/promises";
12
- import { existsSync } from "node:fs";
13
- function isSelectableItem(item) {
14
- return item.kind === "alias-name" || item.kind === "flag";
15
- }
16
- export function AliasScreen() {
17
- const { state } = useApp();
18
- const modal = useModal();
19
- const [config, setConfig] = useState(null);
20
- const [shells, setShells] = useState([]);
21
- const [selectedIdx, setSelectedIdx] = useState(0);
22
- const [error, setError] = useState(null);
23
- const [viewMode, setViewMode] = useState({ kind: "main" });
24
- // Snapshot of the rc file's flag values as parsed on mount / write. Used
25
- // to compute the dirty indicator: in-memory != rcSnapshot ⇒ unsaved.
26
- const [rcSnapshot, setRcSnapshot] = useState(null);
27
- // Transient write feedback shown on the header status line (not a blocking
28
- // modal). Auto-clears after a few seconds. Errors still use a modal since
29
- // they need to be read and acknowledged.
30
- const [writeStatus, setWriteStatus] = useState(null);
31
- // A hand-written `claude` alias found OUTSIDE any managed block on mount.
32
- // Set when the rc file has no managed block but a stray alias we could
33
- // adopt — drives the one-time "import it?" offer below. Cleared once the
34
- // offer has been shown (whether accepted or declined).
35
- const [adoptable, setAdoptable] = useState(null);
36
- // When the user accepts a LOSSLESS adoption, we remember the line range of
37
- // their original alias so the next write replaces it in place (no duplicate
38
- // alias). Cleared after that write absorbs it into the managed block.
39
- const [pendingAdoptRange, setPendingAdoptRange] = useState(null);
40
- // Clear the write status line a few seconds after it appears.
41
- useEffect(() => {
42
- if (!writeStatus)
43
- return;
44
- const t = setTimeout(() => setWriteStatus(null), 4000);
45
- return () => clearTimeout(t);
46
- }, [writeStatus]);
47
- // One-time "adopt a hand-written alias?" offer. Fires when the mount load
48
- // found a stray `claude` alias outside any managed block. We import only the
49
- // flags we recognized; whether we also TAKE OWNERSHIP (remove the original
50
- // line on the next write) depends on `lossless`:
51
- // - lossless: every token round-trips → safe to absorb. We stash the line
52
- // range so the next write replaces it in place (no duplicate alias).
53
- // - not lossless: we couldn't parse some tokens (e.g. an uncatalogued
54
- // flag like --model) → import the known flags for convenience but LEAVE
55
- // the original line untouched. CRITICAL: we must NOT adopt its name here.
56
- // Shell alias resolution is last-definition-wins, so a managed block
57
- // sharing the name would shadow the surviving original at `source` time —
58
- // silently killing the very tokens that made it not-lossless. Keeping the
59
- // tool's own name lets both coexist: the original keeps working, the
60
- // managed block lives under a different name.
61
- // True once we've shown the offer. A ref (not state) so it survives re-render
62
- // without being a dependency — critical because this effect mutates its own
63
- // `adoptable` dep, and tying "fire once" to state/deps would let the dep
64
- // change abort the in-flight modal mid-await (the cleanup would fire before
65
- // the user answered). The ref decouples one-shot from the dependency array.
66
- const didOfferAdoptRef = useRef(false);
67
- useEffect(() => {
68
- if (!adoptable || !config || didOfferAdoptRef.current)
69
- return;
70
- didOfferAdoptRef.current = true;
71
- (async () => {
72
- const a = adoptable;
73
- const body = a.rawLine.trim();
74
- const others = a.others.length > 0
75
- ? `\n\n(Also found ${a.others.length} other claude alias${a.others.length === 1 ? "" : "es"} — leaving those alone.)`
76
- : "";
77
- // On a not-lossless adopt the managed block must NOT share the original's
78
- // name — same name + last-wins shell resolution = the block shadows the
79
- // surviving original, killing its uncatalogued tokens. Compute a managed
80
- // name distinct from `a.name`: keep the tool's current name if it already
81
- // differs, else derive a suffixed variant that's free in the rc file.
82
- const managedName = a.lossless
83
- ? a.name
84
- : pickDistinctName(config.aliasName, a.name, a.others);
85
- const message = a.lossless
86
- ? `Found a hand-written alias:\n\n ${body}\n\nImport its flags into the editor? On the next write it'll be absorbed into a managed block (your original line is replaced — no duplicate).${others}`
87
- : `Found a hand-written alias:\n\n ${body}\n\nI can import the flags I recognize, but it uses ${a.leftovers.length} token${a.leftovers.length === 1 ? "" : "s"} I don't manage (${a.leftovers
88
- .map((t) => JSON.stringify(t))
89
- .join(", ")}). I'll import the known flags and LEAVE your original "${a.name}" line untouched so it keeps working. The managed alias will use the name "${managedName}" — distinct from "${a.name}" so it can't override it. Import the known flags?${others}`;
90
- const accepted = await modal.confirm("Adopt existing alias?", message);
91
- if (accepted) {
92
- // Lossless: adopt the name AND take ownership (replace the line on
93
- // write). Not-lossless: import flags under a distinct managed name and
94
- // never touch the original line — so it survives AND keeps resolving.
95
- setConfig((prev) => prev
96
- ? {
97
- ...prev,
98
- aliasName: managedName,
99
- flags: { ...prev.flags, ...a.flags },
100
- }
101
- : prev);
102
- if (a.lossless) {
103
- // Persist the adopted name and stash the line range so the next
104
- // write replaces the original in place (no duplicate, no shadow).
105
- void persistAliasName(a.name);
106
- setPendingAdoptRange(a.lineRange);
107
- }
108
- else {
109
- // Persist the distinct managed name so it survives a reopen.
110
- void persistAliasName(managedName);
111
- }
112
- }
113
- // Clear the candidate now that the decision is made — after the await,
114
- // never before (clearing before would abort this very async via the
115
- // dep-change cleanup, the bug this effect previously had).
116
- setAdoptable(null);
117
- })();
118
- // persistAliasName is stable (useCallback); excluded to keep this one-shot.
119
- // eslint-disable-next-line react-hooks/exhaustive-deps
120
- }, [adoptable, config, modal]);
121
- // ── Load alias name + parse rc file + detect shells on mount ─────────
122
- // The alias name is computer-wide and persisted in ~/.claude/settings.json.
123
- // Flag values are read directly from the shell rc file's managed block —
124
- // the rc file IS the source of truth so what the user sees matches what
125
- // they're actually running.
126
- useEffect(() => {
127
- let cancelled = false;
128
- (async () => {
129
- try {
130
- const [name, s] = await Promise.all([loadAliasName(), detectShells()]);
131
- if (cancelled)
132
- return;
133
- // Pick the same rc file we'd write to with `w` (default shell that
134
- // exists; else first existing). If none exists, start from defaults.
135
- const readTarget = s.find((sh) => sh.isDefault && sh.exists) ??
136
- s.find((sh) => sh.exists);
137
- const base = defaultAliasConfig();
138
- base.aliasName = name;
139
- let parsedFlags = null;
140
- let foundAdoptable = null;
141
- if (readTarget && existsSync(readTarget.path)) {
142
- try {
143
- const rcText = await readFile(readTarget.path, "utf8");
144
- const parsed = parseAliasFromRc(rcText);
145
- if (parsed) {
146
- parsedFlags = { ...base.flags, ...parsed.flags };
147
- base.flags = parsedFlags;
148
- // Honour an existing alias name from the rc if settings is at default.
149
- // But the user's stored preference wins when set explicitly.
150
- // (No-op here — `name` already loaded above.)
151
- }
152
- else {
153
- // No managed block on disk. The user may still have a hand-written
154
- // `claude` alias elsewhere — detect it so we can offer to adopt it
155
- // instead of looking broken. Non-destructive: just a candidate.
156
- foundAdoptable = findAdoptableAlias(rcText);
157
- }
158
- }
159
- catch {
160
- // rc unreadable — fall back to defaults; not a hard error.
161
- }
162
- }
163
- if (cancelled)
164
- return;
165
- // No mirror normalization: channels.values holds OWN channels only;
166
- // derived channels come from the dev-load flag at display/render time.
167
- // The parser already subtracts derived values from the parsed channels
168
- // list, so `base.flags` is correct as-is.
169
- setConfig(base);
170
- setShells(s);
171
- setRcSnapshot(parsedFlags ?? { ...base.flags });
172
- if (foundAdoptable)
173
- setAdoptable(foundAdoptable);
174
- }
175
- catch (err) {
176
- if (cancelled)
177
- return;
178
- setError(err instanceof Error ? err.message : String(err));
179
- }
180
- })();
181
- return () => {
182
- cancelled = true;
183
- };
184
- }, []);
185
- // ── Build the flat list of items ──────────────────────────────────────
186
- // Group headers and the shell legend live in the same flat array as
187
- // alias-name + flag rows so that ScrollableList can window them together.
188
- // Navigation skips non-selectable kinds.
189
- const items = useMemo(() => {
190
- if (!config)
191
- return [];
192
- const issues = validateConfig(config);
193
- const issueMap = new Map(issues.map((i) => [i.flagId, i]));
194
- const out = [
195
- {
196
- kind: "alias-name",
197
- row: { kind: "alias-name", value: config.aliasName },
198
- },
199
- ];
200
- for (const group of FLAG_GROUPS) {
201
- const groupFlags = ALIAS_FLAGS.filter((f) => f.group === group.id);
202
- if (groupFlags.length === 0)
203
- continue;
204
- out.push({ kind: "header", label: group.label });
205
- for (const flag of groupFlags) {
206
- // --channels shows enabled when the rendered alias would emit it —
207
- // i.e. own channels are on OR a dev-loaded channel is derived in. This
208
- // keeps the checkbox honest about what gets written without mutating
209
- // the own-channels enabled flag (which would silently re-emit own
210
- // values the user disabled).
211
- let effectiveEnabled;
212
- let effectiveDetail;
213
- let stateSummary;
214
- if (flag.id === CHANNELS_FLAG_ID) {
215
- const own = config.flags[flag.id];
216
- const ownValues = own && own.kind === "text-list" && own.enabled
217
- ? own.values.filter((v) => v.length > 0)
218
- : [];
219
- const derived = derivedChannelValues(config.flags);
220
- // Deduped union — matches the writer's render-time union and the
221
- // detail-pane summary, so the count is consistent everywhere.
222
- const total = new Set([...ownValues, ...derived]).size;
223
- effectiveEnabled = total > 0;
224
- // Show the union count so the row matches what's written. When the
225
- // count is purely derived, this reads e.g. `[x] --channels 1`.
226
- effectiveDetail = total > 0 ? `${total}` : "";
227
- // The detail-pane State line shows the same final channel list.
228
- stateSummary = channelsStateSummary(config.flags);
229
- }
230
- out.push({
231
- kind: "flag",
232
- row: {
233
- kind: "flag",
234
- flag,
235
- value: config.flags[flag.id] ?? defaultValueFor(flag),
236
- issue: issueMap.get(flag.id),
237
- effectiveEnabled,
238
- effectiveDetail,
239
- stateSummary,
240
- },
241
- });
242
- }
243
- }
244
- return out;
245
- }, [config]);
246
- /** Indices in `items` that the cursor may land on. */
247
- const selectableIndices = useMemo(() => items.flatMap((it, i) => (isSelectableItem(it) ? [i] : [])), [items]);
248
- // ── Flag-detail sub-screen items ──────────────────────────────────────
249
- // Computed only when viewMode is flag-detail. Built off the flag's current
250
- // The flag-detail sub-screen is now self-contained in <FlagDetailEditor>.
251
- // We just resolve the flag + value pair here so the parent can render
252
- // the editor and the right-pane preview.
253
- const detailFlag = viewMode.kind === "flag-detail"
254
- ? ALIAS_FLAGS.find((f) => f.id === viewMode.flagId) ?? null
255
- : null;
256
- const detailValue = detailFlag && config ? config.flags[detailFlag.id] ?? null : null;
257
- // ── Helper: check whether a row is gated (requires unmet) ─────────────
258
- const isGated = useCallback((flag) => {
259
- if (!flag.requires || !config)
260
- return false;
261
- return !isFlagEnabled(config.flags[flag.requires]);
262
- }, [config]);
263
- const selectedItem = items[selectedIdx];
264
- const selectedRow = selectedItem &&
265
- (selectedItem.kind === "alias-name" || selectedItem.kind === "flag")
266
- ? selectedItem.row
267
- : undefined;
268
- // Clamp selection: snap to the nearest selectable index whenever items shift.
269
- useEffect(() => {
270
- if (selectableIndices.length === 0)
271
- return;
272
- if (!isSelectableItem(items[selectedIdx])) {
273
- // Find the nearest selectable index <= selectedIdx (or the first one)
274
- const fallback = [...selectableIndices].reverse().find((i) => i <= selectedIdx) ??
275
- selectableIndices[0];
276
- setSelectedIdx(fallback);
277
- }
278
- else if (selectedIdx >= items.length) {
279
- setSelectedIdx(selectableIndices[selectableIndices.length - 1]);
280
- }
281
- }, [items, selectableIndices, selectedIdx]);
282
- // ── Mutators ──────────────────────────────────────────────────────────
283
- // Flag mutations stay in memory. Only the alias name is persisted (to
284
- // ~/.claude/settings.json) — flag values reach disk only when the user
285
- // explicitly presses `w` to write the shell rc file.
286
- const persistAliasName = useCallback(async (name) => {
287
- try {
288
- await saveAliasName(name);
289
- }
290
- catch (err) {
291
- await modal.message("Save failed", err instanceof Error ? err.message : String(err), "error");
292
- }
293
- }, [modal]);
294
- // Cascade dependencies on every mutation:
295
- // - Enabling a flag → enable its `requires` chain (no modal nagging).
296
- // - Disabling a flag → disable anything whose `requires === this flag id`,
297
- // because the renderer would silently drop them otherwise and the UI
298
- // would lie about what's going to be written.
299
- const updateFlag = useCallback((id, next) => {
300
- setConfig((prev) => {
301
- if (!prev)
302
- return prev;
303
- const flags = { ...prev.flags, [id]: next };
304
- const target = ALIAS_FLAGS.find((f) => f.id === id);
305
- if (!target)
306
- return { ...prev, flags };
307
- const becomingEnabled = isFlagEnabled(next);
308
- if (becomingEnabled) {
309
- // Walk `requires` chain and force-enable each ancestor to its
310
- // catalog-default-enabled state if it's currently off.
311
- let cursor = target.requires;
312
- const seen = new Set();
313
- while (cursor && !seen.has(cursor)) {
314
- seen.add(cursor);
315
- const dep = ALIAS_FLAGS.find((f) => f.id === cursor);
316
- if (!dep)
317
- break;
318
- if (!isFlagEnabled(flags[dep.id])) {
319
- flags[dep.id] = enableDefault(dep);
320
- }
321
- cursor = dep.requires;
322
- }
323
- }
324
- else {
325
- // Cascade-disable any flag that requires this one (one level deep is
326
- // enough today; recurse defensively in case a chain emerges).
327
- const queue = [id];
328
- const seen = new Set();
329
- while (queue.length > 0) {
330
- const cur = queue.shift();
331
- if (seen.has(cur))
332
- continue;
333
- seen.add(cur);
334
- for (const dependent of ALIAS_FLAGS) {
335
- if (dependent.requires !== cur)
336
- continue;
337
- if (!isFlagEnabled(flags[dependent.id]))
338
- continue;
339
- flags[dependent.id] = disableValue(flags[dependent.id]);
340
- queue.push(dependent.id);
341
- }
342
- }
343
- }
344
- return { ...prev, flags };
345
- });
346
- }, []);
347
- // Remove a value from the dev-load flag — invoked when the user deletes a
348
- // "Dev-loaded channels" row inside the --channels editor. The derived
349
- // section is sourced from this flag, so the deletion lands here, not in
350
- // channels.values. updateFlag keeps enabled-state and cascades consistent.
351
- const removeDevloadChannel = useCallback((val) => {
352
- setConfig((prev) => prev ? { ...prev, flags: withoutDerivedChannel(prev.flags, val) } : prev);
353
- }, []);
354
- const editAliasName = useCallback(async () => {
355
- if (!config)
356
- return;
357
- const v = await modal.input("Alias name", `Shell alias name (default: "${DEFAULT_ALIAS_NAME}"). Letters, digits, _ or - only.`, config.aliasName);
358
- if (v === null)
359
- return;
360
- const reason = validateAliasName(v);
361
- if (reason) {
362
- await modal.message("Invalid alias name", reason, "error");
363
- return;
364
- }
365
- setConfig((prev) => (prev ? { ...prev, aliasName: v } : prev));
366
- void persistAliasName(v);
367
- }, [config, modal, persistAliasName]);
368
- const editSelected = useCallback(async () => {
369
- if (!selectedRow)
370
- return;
371
- if (selectedRow.kind === "alias-name") {
372
- await editAliasName();
373
- return;
374
- }
375
- // No more "Requires another flag" modal — `updateFlag` auto-enables the
376
- // `requires` chain when the user activates a gated flag.
377
- //
378
- // Collection editors live in a dedicated sub-screen, not a modal —
379
- // each row gets its own keybindings (space toggle, a add, d delete)
380
- // so there's no "what does enter do here?" overloading.
381
- const k = selectedRow.value.kind;
382
- if (k === "text-list" || k === "multi-with-custom") {
383
- // FlagDetailEditor manages its own cursor — parent just flips mode.
384
- setViewMode({ kind: "flag-detail", flagId: selectedRow.flag.id });
385
- return;
386
- }
387
- const next = await editFlagValue(selectedRow.flag, selectedRow.value, modal);
388
- if (next)
389
- updateFlag(selectedRow.flag.id, next);
390
- }, [selectedRow, modal, updateFlag, editAliasName]);
391
- const toggleSelected = useCallback(async () => {
392
- if (!selectedRow)
393
- return;
394
- if (selectedRow.kind === "alias-name") {
395
- // No "toggle" semantic for the name — fall through to edit.
396
- await editAliasName();
397
- return;
398
- }
399
- // Only booleans and tri-states have a meaningful single-press cycle.
400
- // Everything else (select, text, list, multi-with-custom) needs a value
401
- // chooser; falling back to edit prevents the "I pressed space and got the
402
- // first option without seeing the choices" footgun.
403
- const k = selectedRow.value.kind;
404
- if (k !== "boolean" && k !== "tri-state") {
405
- await editSelected();
406
- return;
407
- }
408
- const next = quickToggle(selectedRow.flag, selectedRow.value);
409
- if (next)
410
- updateFlag(selectedRow.flag.id, next);
411
- }, [selectedRow, updateFlag, editSelected, editAliasName]);
412
- const handleWrite = useCallback(async () => {
413
- if (!config)
414
- return;
415
- // Pick the target shell automatically: default shell (matches $SHELL)
416
- // if its rc file exists; otherwise the first existing rc file. Users
417
- // who care about other shells edit them directly — the alias config
418
- // itself is stored in ~/.claude and the user can run `w` again from
419
- // a different $SHELL session if they want to mirror it.
420
- const target = shells.find((s) => s.isDefault && s.exists) ??
421
- shells.find((s) => s.exists);
422
- if (!target) {
423
- await modal.message("No shells detected", "No supported rc files found. Create ~/.zshrc, ~/.bashrc, or ~/.config/fish/config.fish first.", "info");
424
- return;
425
- }
426
- try {
427
- // If we adopted a lossless hand-written alias, pass its line range so
428
- // the FIRST write replaces that line in place (absorbing it into the
429
- // managed block) rather than appending a second alias. Once the block
430
- // exists, the writer ignores the range and splices by markers.
431
- const r = await writeAliasToShell(config, target, pendingAdoptRange ? { adoptLineRange: pendingAdoptRange } : {});
432
- // The adopted line is now gone (replaced by the block); drop the range
433
- // so subsequent writes don't try to re-target a line that moved.
434
- if (pendingAdoptRange)
435
- setPendingAdoptRange(null);
436
- // Non-blocking confirmation on the status line — no "press any key".
437
- const name = r.path.split("/").pop() || r.path;
438
- setWriteStatus(`✓ ${r.action === "created" ? "Created" : "Updated"} ${name} — source it or open a new shell`);
439
- setShells(await detectShells());
440
- // We just wrote the rc file with current in-memory flag values, so
441
- // the snapshot now matches in-memory state. Dirty indicator clears.
442
- setRcSnapshot(config.flags);
443
- }
444
- catch (err) {
445
- await modal.message("Write failed", err instanceof Error ? err.message : String(err), "error");
446
- }
447
- }, [config, shells, modal, pendingAdoptRange]);
448
- // ── Keyboard ──────────────────────────────────────────────────────────
449
- // j/k navigate the selectable subset, jumping over headers/legend lines.
450
- const moveSelection = useCallback((dir) => {
451
- if (selectableIndices.length === 0)
452
- return;
453
- const cursorPos = selectableIndices.indexOf(selectedIdx);
454
- const nextPos = cursorPos === -1
455
- ? // Currently parked on a non-selectable; move to first/last selectable.
456
- dir === 1
457
- ? 0
458
- : selectableIndices.length - 1
459
- : Math.min(selectableIndices.length - 1, Math.max(0, cursorPos + dir));
460
- setSelectedIdx(selectableIndices[nextPos]);
461
- }, [selectableIndices, selectedIdx]);
462
- // The flag-detail sub-screen handles its own cursor + key + render
463
- // (see FlagDetailEditor component). The parent only needs to know how
464
- // to leave it.
465
- const exitDetail = useCallback(() => {
466
- setViewMode({ kind: "main" });
467
- }, []);
468
- // ── Keyboard handler ──────────────────────────────────────────────────
469
- // When the sub-screen is mounted, FlagDetailEditor installs its own
470
- // keyboard handler. Both handlers fire (OpenTUI's useKeyboard delivers
471
- // to every subscriber), so this handler must SKIP the keys the child
472
- // owns to avoid double-dispatch. We bail entirely while in detail mode.
473
- useKeyboardHandler((input, key) => {
474
- if (state.modal)
475
- return;
476
- if (viewMode.kind === "flag-detail")
477
- return;
478
- // Main mode.
479
- if (input === "j" || key.downArrow) {
480
- moveSelection(1);
481
- return;
482
- }
483
- if (input === "k" || key.upArrow) {
484
- moveSelection(-1);
485
- return;
486
- }
487
- if (key.return || input === " " || key.name === "space") {
488
- void toggleSelected();
489
- return;
490
- }
491
- if (input === "e") {
492
- void editSelected();
493
- return;
494
- }
495
- if (input === "w") {
496
- void handleWrite();
497
- return;
498
- }
499
- if (input === "r") {
500
- // Reset the selected row to its default.
501
- if (!selectedRow)
502
- return;
503
- if (selectedRow.kind === "alias-name") {
504
- setConfig((prev) => prev ? { ...prev, aliasName: DEFAULT_ALIAS_NAME } : prev);
505
- void persistAliasName(DEFAULT_ALIAS_NAME);
506
- return;
507
- }
508
- // Flag reset stays in memory until `w`.
509
- updateFlag(selectedRow.flag.id, defaultValueFor(selectedRow.flag));
510
- }
511
- });
512
- // ── Render ────────────────────────────────────────────────────────────
513
- const previewSegments = config ? renderArgs(config) : [];
514
- const previewAliasName = config?.aliasName ?? "";
515
- // Native OpenTUI scrollboxes own the scroll math. We render every item
516
- // into the scrollbox's content area and ask the renderable to scroll the
517
- // selected child into view whenever the cursor moves. The previous JS-
518
- // windowed approach (ScrollableList) overstrike-rendered rows when its
519
- // height computation drifted off the actual panel size.
520
- const mainScrollRef = useRef(null);
521
- useEffect(() => {
522
- const item = items[selectedIdx];
523
- if (!item)
524
- return;
525
- mainScrollRef.current?.scrollChildIntoView(`alias-row-${getItemKey(item)}`);
526
- }, [items, selectedIdx]);
527
- const inDetail = viewMode.kind === "flag-detail" && detailFlag && detailValue;
528
- // FlagDetailEditor only handles text-list and multi-with-custom values;
529
- // narrow the type for the JSX below.
530
- const editableDetailValue = inDetail &&
531
- (detailValue.kind === "text-list" ||
532
- detailValue.kind === "multi-with-custom")
533
- ? detailValue
534
- : null;
535
- const mainListPanel = !config ? (_jsx("text", { fg: "gray", children: error ? `Error: ${error}` : "Loading..." })) : (_jsx("box", { flexDirection: "column", height: "100%", children: _jsx("scrollbox", { ref: mainScrollRef, scrollY: true, scrollX: false, flexGrow: 1, children: _jsx("box", { flexDirection: "column", children: items.map((item, idx) => (
536
- // id is content-derived (not positional `${idx}`) so OpenTUI's
537
- // reconciler stays in lockstep with React's key-based reconcile.
538
- _jsx("box", { id: `alias-row-${getItemKey(item)}`, children: renderItem(item, idx === selectedIdx, isGated) }, getItemKey(item)))) }) }) }));
539
- const listPanel = inDetail && editableDetailValue ? (_jsx(FlagDetailEditor, { flag: detailFlag, value: editableDetailValue, onChange: (next) => updateFlag(detailFlag.id, next), onBack: exitDetail, derivedValues: detailFlag.id === CHANNELS_FLAG_ID && config
540
- ? derivedChannelValues(config.flags)
541
- : undefined, derivedLabel: "From --dangerously-load:", toggleLabel: detailFlag.id === CHANNELS_FLAG_ID
542
- ? "Enable own channels"
543
- : undefined, onDerivedDelete: (v) => removeDevloadChannel(v) })) : (mainListPanel);
544
- const mainDetailPanel = renderDetail(selectedRow, isGated, previewAliasName, previewSegments);
545
- // When editing --channels and there are derived rows, the right pane carries
546
- // the contextual instruction about what deleting a derived row does — that
547
- // explanation belongs here, not crammed into the left list.
548
- const channelsHasDerived = inDetail &&
549
- detailFlag.id === CHANNELS_FLAG_ID &&
550
- config &&
551
- derivedChannelValues(config.flags).length > 0;
552
- const derivedNote = channelsHasDerived
553
- ? "Rows under “From --dangerously-load:” are derived from the --dangerously-load-development-channels flag. Deleting one here removes it from that flag."
554
- : undefined;
555
- // The right-pane `State:` line is informational — it describes what the alias
556
- // actually runs. For --channels that's the FINAL channel list: the union of
557
- // the user's own channels and the derived (dev-loaded) ones. We show the
558
- // union count so it agrees with the list row's count and the Preview, and
559
- // annotate how many are derived so the source is clear. Computed only when
560
- // editing --channels; other flags fall back to their own summary.
561
- const stateOverride = inDetail && detailFlag.id === CHANNELS_FLAG_ID && config
562
- ? channelsStateSummary(config.flags)
563
- : undefined;
564
- const detailDetailPanel = inDetail
565
- ? renderFlagDetailRightPane(detailFlag, detailValue, previewAliasName, previewSegments, derivedNote, stateOverride)
566
- : null;
567
- const detailPanel = inDetail ? detailDetailPanel : mainDetailPanel;
568
- const enabledCount = config
569
- ? Object.values(config.flags).filter(isFlagEnabled).length
570
- : 0;
571
- const subtitle = inDetail
572
- ? `editing ${detailFlag.flag}`
573
- : writeStatus
574
- ? writeStatus
575
- : config
576
- ? `${enabledCount} flag${enabledCount === 1 ? "" : "s"} enabled`
577
- : "";
578
- // Resolve the rc-file name we'd actually write to (basename of the chosen
579
- // shell's path). Falls back to "shell" if no shells were detected — UI
580
- // surface mirrors the runtime behavior of `handleWrite`.
581
- const writeTarget = shells.find((s) => s.isDefault && s.exists) ??
582
- shells.find((s) => s.exists);
583
- const writeLabel = writeTarget
584
- ? writeTarget.path.split("/").pop() || "shell"
585
- : "shell";
586
- // Dirty when current in-memory flags differ from the rc-file snapshot.
587
- // Initial mount sets rcSnapshot from the parsed rc, so this is false
588
- // until the user edits.
589
- const dirty = config
590
- ? rcSnapshot !== null && !shallowFlagsEqual(config.flags, rcSnapshot)
591
- : false;
592
- const footerHints = inDetail
593
- ? [
594
- { keys: ["↑", "↓"], label: "move" },
595
- { keys: ["space"], label: "toggle" },
596
- { keys: ["a"], label: "add" },
597
- { keys: ["d"], label: "delete" },
598
- { keys: ["h"], label: "back" },
599
- ]
600
- : [
601
- { keys: ["↑", "↓"], label: "move" },
602
- { keys: ["space"], label: "toggle" },
603
- { keys: ["e"], label: "edit" },
604
- { keys: ["r"], label: "reset" },
605
- {
606
- keys: ["w"],
607
- label: `${dirty ? "*" : ""}write to ${writeLabel}`,
608
- },
609
- ];
610
- return (_jsx(ScreenLayout, { title: "Claude Alias", subtitle: subtitle, currentScreen: "alias", footerHints: footerHints, listPanel: listPanel, detailPanel: detailPanel }));
611
- }
612
- // ─── Helpers ────────────────────────────────────────────────────────────
613
- /**
614
- * Summarize the EFFECTIVE state of `--channels` for the detail `State:` line:
615
- * the final channel list that the alias will actually run, i.e. the union of
616
- * the user's own (enabled) channels and the derived dev-loaded ones. This must
617
- * agree with the list row's union count and the Preview.
618
- *
619
- * Returns "off" when nothing is emitted, or e.g.:
620
- * - "2 channels" (all own, no derived)
621
- * - "1 channel (from --dangerously-load)" (purely derived, own off/empty)
622
- * - "2 channels (1 from --dangerously-load)" (mixed)
623
- */
624
- function channelsStateSummary(flags) {
625
- const ownValue = flags[CHANNELS_FLAG_ID];
626
- const ownValues = ownValue && ownValue.kind === "text-list" && ownValue.enabled
627
- ? ownValue.values.filter((v) => v.length > 0)
628
- : [];
629
- const derived = derivedChannelValues(flags);
630
- // Union, deduped, matching the writer's render-time union.
631
- const total = new Set([...ownValues, ...derived]).size;
632
- if (total === 0)
633
- return "off";
634
- const noun = total === 1 ? "channel" : "channels";
635
- if (derived.length === 0)
636
- return `${total} ${noun}`;
637
- // How many of the union come from the derived flag (after dedup with own).
638
- const derivedInUnion = new Set(derived).size;
639
- const derivedNote = derivedInUnion === total
640
- ? "from --dangerously-load"
641
- : `${derivedInUnion} from --dangerously-load`;
642
- return `${total} ${noun} (${derivedNote})`;
643
- }
644
- /**
645
- * Compare two flag maps for value equality. We render-then-diff via JSON
646
- * because FlagValues are small, fully serialisable, and order-insensitive
647
- * inside the maps. A property-by-property deep-equal would be more efficient
648
- * but the maps have ~14 entries — diff cost is negligible.
649
- */
650
- function shallowFlagsEqual(a, b) {
651
- const aKeys = Object.keys(a).sort();
652
- const bKeys = Object.keys(b).sort();
653
- if (aKeys.length !== bKeys.length)
654
- return false;
655
- for (let i = 0; i < aKeys.length; i++) {
656
- if (aKeys[i] !== bKeys[i])
657
- return false;
658
- }
659
- for (const k of aKeys) {
660
- if (JSON.stringify(a[k]) !== JSON.stringify(b[k]))
661
- return false;
662
- }
663
- return true;
664
- }
665
- function isFlagEnabled(value) {
666
- if (!value)
667
- return false;
668
- switch (value.kind) {
669
- case "boolean":
670
- return value.enabled;
671
- case "tri-state":
672
- return value.state !== "unset";
673
- case "select":
674
- case "text":
675
- case "optional-text":
676
- case "text-list":
677
- case "multi-with-custom":
678
- return value.enabled;
679
- }
680
- }
681
- /**
682
- * Pick a managed-alias name that can't shadow a surviving hand-written alias.
683
- *
684
- * On a not-lossless adoption we keep the user's original `<original>` line in
685
- * the rc file, so the managed block must NOT share its name (shell aliases are
686
- * last-definition-wins — a same-named block would override the original and
687
- * silently drop the very tokens that made it not-lossless).
688
- *
689
- * Strategy: prefer the tool's `current` name if it already differs from the
690
- * original. Otherwise derive `<original>m`, `<original>m2`, … until we find one
691
- * that is valid AND collides with neither the original nor the other detected
692
- * claude aliases. Falls back to a timestamp-free deterministic suffix.
693
- */
694
- function pickDistinctName(current, original, others) {
695
- // Names already taken by aliases we're leaving in place.
696
- const taken = new Set([original]);
697
- for (const line of others) {
698
- const m = /^alias\s+([A-Za-z_][A-Za-z0-9_-]*)\s*=/.exec(line.trim());
699
- if (m)
700
- taken.add(m[1]);
701
- }
702
- // If our current name is already distinct + valid, just use it.
703
- if (current !== original && !taken.has(current) && !validateAliasName(current)) {
704
- return current;
705
- }
706
- // Derive a suffixed variant from the original.
707
- const base = `${original}m`;
708
- if (!taken.has(base) && !validateAliasName(base))
709
- return base;
710
- for (let n = 2; n < 100; n++) {
711
- const cand = `${original}m${n}`;
712
- if (!taken.has(cand) && !validateAliasName(cand))
713
- return cand;
714
- }
715
- // Pathological fallback — should never be reached for sane inputs.
716
- return `${original}managed`;
717
- }
718
- /**
719
- * Produce an "enabled by default" value for a flag — what we'd give it when
720
- * the user activates a dependent that needs this one on. For booleans this
721
- * is just `enabled: true`; for kinds that carry a value (select/text/etc.)
722
- * we set `enabled: true` with the catalog default value, leaving the user
723
- * free to refine it after.
724
- */
725
- function enableDefault(flag) {
726
- switch (flag.kind) {
727
- case "boolean":
728
- return { kind: "boolean", enabled: true };
729
- case "tri-state":
730
- return { kind: "tri-state", state: "on" };
731
- case "select":
732
- return {
733
- kind: "select",
734
- enabled: true,
735
- value: flag.options?.[0]?.value ?? "",
736
- };
737
- case "text":
738
- return { kind: "text", enabled: true, value: "" };
739
- case "optional-text":
740
- return { kind: "optional-text", enabled: true, value: "" };
741
- case "text-list":
742
- return {
743
- kind: "text-list",
744
- enabled: true,
745
- values: [...(flag.defaultValues ?? [])],
746
- };
747
- case "multi-with-custom":
748
- return {
749
- kind: "multi-with-custom",
750
- enabled: true,
751
- picked: [],
752
- custom: [...(flag.defaultValues ?? [])],
753
- };
754
- }
755
- }
756
- /**
757
- * Disable a flag while preserving any values the user has already entered.
758
- * Used by the cascade-disable path: turning off `--worktree` shouldn't lose
759
- * the user's `--tmux=classic` choice — only re-enable the dependency and
760
- * the value reappears.
761
- */
762
- function disableValue(value) {
763
- switch (value.kind) {
764
- case "boolean":
765
- return { kind: "boolean", enabled: false };
766
- case "tri-state":
767
- return { kind: "tri-state", state: "unset" };
768
- case "select":
769
- case "text":
770
- case "optional-text":
771
- case "text-list":
772
- case "multi-with-custom":
773
- return { ...value, enabled: false };
774
- }
775
- }
776
- function summarizeValue(value) {
777
- switch (value.kind) {
778
- case "boolean":
779
- return value.enabled ? "on" : "off";
780
- case "tri-state":
781
- return value.state;
782
- case "select":
783
- return value.enabled ? value.value || "(bare)" : "off";
784
- case "text":
785
- case "optional-text":
786
- return value.enabled
787
- ? value.value
788
- ? truncate(value.value, 32)
789
- : "(empty)"
790
- : "off";
791
- case "text-list":
792
- return value.enabled ? `${value.values.length} item(s)` : "off";
793
- case "multi-with-custom": {
794
- if (!value.enabled)
795
- return "off";
796
- const total = new Set([...value.picked, ...value.custom]).size;
797
- return total === 0 ? "(no filter)" : `${total} token(s)`;
798
- }
799
- }
800
- }
801
- function truncate(s, n) {
802
- return s.length <= n ? s : s.slice(0, n - 1) + "…";
803
- }
804
- /**
805
- * Quick toggle (enter/space). For boolean → flip. For tri-state → cycle
806
- * unset → on → off → unset. For others, just flip the `enabled` field; the
807
- * user must press `e` to set the value.
808
- */
809
- function quickToggle(_flag, value) {
810
- switch (value.kind) {
811
- case "boolean":
812
- return { kind: "boolean", enabled: !value.enabled };
813
- case "tri-state": {
814
- const next = value.state === "unset" ? "on" : value.state === "on" ? "off" : "unset";
815
- return { kind: "tri-state", state: next };
816
- }
817
- case "select":
818
- return { ...value, enabled: !value.enabled };
819
- case "text":
820
- case "optional-text":
821
- return { ...value, enabled: !value.enabled };
822
- case "text-list":
823
- return { ...value, enabled: !value.enabled };
824
- case "multi-with-custom":
825
- return { ...value, enabled: !value.enabled };
826
- }
827
- }
828
- /**
829
- * `e` — edit the value. Modal flow varies by flag kind.
830
- */
831
- async function editFlagValue(flag, value, modal) {
832
- switch (value.kind) {
833
- case "boolean":
834
- return { kind: "boolean", enabled: !value.enabled };
835
- case "tri-state": {
836
- const choice = await modal.select(flag.label, flag.description, [
837
- { label: "Unset (no opinion)", value: "unset" },
838
- { label: `On (${flag.flag})`, value: "on" },
839
- ...(flag.triStateOff
840
- ? [{ label: `Off (${flag.triStateOff})`, value: "off" }]
841
- : []),
842
- ], ["unset", "on", "off"].indexOf(value.state));
843
- if (!choice)
844
- return null;
845
- return { kind: "tri-state", state: choice };
846
- }
847
- case "select": {
848
- const opts = flag.options ?? [];
849
- const choice = await modal.select(flag.label, flag.description, [
850
- { label: "(disable)", value: "__off__" },
851
- ...opts.map((o) => ({ label: o.label, value: `v:${o.value}` })),
852
- ], value.enabled
853
- ? Math.max(0, opts.findIndex((o) => o.value === value.value)) + 1
854
- : 0);
855
- if (choice === null)
856
- return null;
857
- if (choice === "__off__")
858
- return { ...value, enabled: false };
859
- return {
860
- kind: "select",
861
- enabled: true,
862
- value: choice.replace(/^v:/, ""),
863
- };
864
- }
865
- case "text": {
866
- // Lead with a 2-option chooser so the user can disable without going
867
- // through `r` reset. Selecting "Set value" jumps to the input modal.
868
- const action = await modal.select(flag.label, flag.description, value.enabled
869
- ? [
870
- { label: `Edit value (current: "${truncate(value.value, 32)}")`, value: "__edit__" },
871
- { label: "Disable flag", value: "__off__" },
872
- ]
873
- : [
874
- { label: "Enable with value...", value: "__edit__" },
875
- { label: "Keep disabled", value: "__off__" },
876
- ], 0);
877
- if (action === null)
878
- return null;
879
- if (action === "__off__") {
880
- return { kind: "text", enabled: false, value: value.value };
881
- }
882
- const v = await modal.input(flag.label, flag.description, value.value);
883
- if (v === null)
884
- return null;
885
- return { kind: "text", enabled: v.length > 0, value: v };
886
- }
887
- case "optional-text": {
888
- // Three-option lead: edit value, bare (no value), or disable.
889
- const action = await modal.select(flag.label, flag.description, [
890
- {
891
- label: value.enabled && value.value
892
- ? `Edit value (current: "${truncate(value.value, 32)}")`
893
- : "Set value...",
894
- value: "__edit__",
895
- },
896
- { label: "Bare flag (no value)", value: "__bare__" },
897
- { label: "Disable flag", value: "__off__" },
898
- ], value.enabled ? (value.value ? 0 : 1) : 2);
899
- if (action === null)
900
- return null;
901
- if (action === "__off__") {
902
- return { kind: "optional-text", enabled: false, value: value.value };
903
- }
904
- if (action === "__bare__") {
905
- return { kind: "optional-text", enabled: true, value: "" };
906
- }
907
- const v = await modal.input(flag.label, flag.description, value.value);
908
- if (v === null)
909
- return null;
910
- return { kind: "optional-text", enabled: true, value: v };
911
- }
912
- case "text-list":
913
- case "multi-with-custom":
914
- // These kinds are routed to the flag-detail sub-screen by
915
- // `editSelected`, never to this modal-based editor. If you see this
916
- // throw, the caller bypassed the routing in editSelected — fix that
917
- // instead of re-introducing the modal cascade.
918
- throw new Error(`${flag.kind} flags use the flag-detail sub-screen, not the modal editor`);
919
- }
920
- }
921
- // ─── Render helpers ─────────────────────────────────────────────────────
922
- /**
923
- * The alias-name row sits above all flag groups. We render it with a clear
924
- * "Alias:" label and the value styled as the editable field, plus an `[edit]`
925
- * hint, so it doesn't blend in with the flag rows below.
926
- */
927
- function renderAliasNameRow(name, selected) {
928
- if (selected) {
929
- return (_jsx("box", { flexDirection: "row", children: _jsx("text", { bg: "#7e57c2", fg: "white", children: `▶ Alias name: ${name} [enter to edit]` }) }, "alias-name-row"));
930
- }
931
- return (_jsxs("text", { children: [_jsx("span", { fg: "gray", children: " Alias name: " }), _jsx("span", { fg: "cyan", children: _jsx("strong", { children: name }) }), _jsx("span", { fg: "gray", children: " [enter to edit]" })] }, "alias-name-row"));
932
- }
933
- /** Stable key per item for the windowed list. */
934
- function getItemKey(item) {
935
- switch (item.kind) {
936
- case "alias-name":
937
- return "alias-name";
938
- case "flag":
939
- return `flag:${item.row.flag.id}`;
940
- case "header":
941
- return `header:${item.label}`;
942
- }
943
- }
944
- /** Dispatch render for one flat-list item. */
945
- function renderItem(item, isSelected, isGated) {
946
- switch (item.kind) {
947
- case "alias-name":
948
- return renderAliasNameRow(item.row.value, isSelected);
949
- case "flag":
950
- return renderRow(item.row, isSelected, isGated(item.row.flag));
951
- case "header":
952
- return _jsx("text", { fg: "#7e57c2", children: item.label });
953
- }
954
- }
955
- function renderRow(row, selected, gated) {
956
- // Prefer the precomputed effective state (e.g. --channels shows enabled when
957
- // a dev-loaded channel forces it to emit) over the flag's own enabled flag.
958
- const enabled = row.effectiveEnabled ?? isFlagEnabled(row.value);
959
- const marker = enabled ? "[x]" : "[ ]";
960
- const issueMark = row.issue ? " ⚠" : "";
961
- const fg = gated ? "gray" : enabled ? "white" : "gray";
962
- // Only show a value suffix when the flag carries non-redundant detail.
963
- // Boolean / tri-state state is fully conveyed by the checkbox. A precomputed
964
- // effectiveDetail (e.g. --channels union count) wins over the own-value one.
965
- const detail = row.effectiveDetail ?? enabledDetail(row.value);
966
- const detailSuffix = detail ? ` ${detail}` : "";
967
- const line = `${selected ? "▶ " : " "}${marker} ${row.flag.flag}${detailSuffix}${issueMark}`;
968
- if (selected) {
969
- return (_jsx("text", { bg: "#7e57c2", fg: "white", children: line }, row.flag.id));
970
- }
971
- return (_jsx("text", { fg: fg, children: line }, row.flag.id));
972
- }
973
- /**
974
- * Per-row trailing detail. Returns "" for booleans and tri-states (their state
975
- * is already in the checkbox) and for disabled flags (no need to advertise an
976
- * unset value). Non-empty for flags that carry an extra value the checkbox
977
- * doesn't capture.
978
- */
979
- function enabledDetail(value) {
980
- switch (value.kind) {
981
- case "boolean":
982
- case "tri-state":
983
- return "";
984
- case "select":
985
- if (!value.enabled)
986
- return "";
987
- return value.value === "" ? "(bare)" : value.value;
988
- case "text":
989
- case "optional-text":
990
- if (!value.enabled)
991
- return "";
992
- return value.value ? truncate(value.value, 24) : "(empty)";
993
- case "text-list":
994
- if (!value.enabled)
995
- return "";
996
- return value.values.length === 0 ? "(empty)" : `${value.values.length}`;
997
- case "multi-with-custom": {
998
- if (!value.enabled)
999
- return "";
1000
- const total = new Set([...value.picked, ...value.custom]).size;
1001
- return total === 0 ? "(no filter)" : `${total} token(s)`;
1002
- }
1003
- }
1004
- }
1005
- function renderDetail(row, isGated, aliasName, segments) {
1006
- if (!row) {
1007
- return _jsx("text", { fg: "gray", children: "No row selected." });
1008
- }
1009
- const headerAndBody = row.kind === "alias-name"
1010
- ? renderAliasNameDetail(row)
1011
- : renderFlagDetail(row, isGated);
1012
- // Preview is the only "global" element kept in the detail panel — it
1013
- // updates as the user toggles, which is the strongest visual feedback for
1014
- // "what alias am I building". We show argv one-per-line rather than the
1015
- // raw POSIX-escaped alias body (which contains `'\''` sequences that look
1016
- // alarming to readers who don't know the close-escape-reopen pattern).
1017
- return (_jsxs("box", { flexDirection: "column", children: [headerAndBody, _jsx("text", { children: " " }), _jsx("text", { fg: "gray", children: "Preview:" }), renderPreviewLines(aliasName, segments)] }));
1018
- }
1019
- function renderAliasNameDetail(row) {
1020
- return (_jsxs("box", { flexDirection: "column", children: [_jsx("text", { fg: "white", children: _jsx("strong", { children: "Alias name" }) }), _jsx("text", { fg: "gray", children: "Shell name for the wrapped claude command. Default: \"c\". Letters, digits, _ or - only." }), _jsx("text", { children: " " }), _jsxs("text", { children: [_jsx("span", { fg: "gray", children: "Current: " }), _jsx("span", { fg: "white", children: _jsx("strong", { children: row.value }) })] }), _jsx("text", { children: " " }), _jsx("text", { fg: "gray", children: "Enter to rename. r resets to \"c\"." })] }));
1021
- }
1022
- function renderFlagDetail(row, isGated) {
1023
- const gated = isGated(row.flag);
1024
- // State must agree with the checkbox and the Preview. For --channels we show
1025
- // the effective channel-list summary (union of own + derived); other flags
1026
- // use their own value summary.
1027
- const stateText = row.stateSummary ?? summarizeValue(row.value);
1028
- return (_jsxs("box", { flexDirection: "column", children: [_jsx("text", { fg: "white", children: _jsx("strong", { children: row.flag.flag }) }), _jsx("text", { fg: "gray", children: row.flag.description }), _jsx("text", { children: " " }), _jsxs("text", { children: [_jsx("span", { fg: "gray", children: "State: " }), _jsx("span", { fg: "white", children: stateText })] }), gated && (_jsx("text", { fg: "gray", children: `Depends on --${row.flag.requires}. Enabling this will turn that on too.` })), row.issue && (_jsx("text", { fg: "yellow", children: `Conflict: ${row.issue.reason}` }))] }));
1029
- }
1030
- /**
1031
- * Render the alias preview as one argv arg per line. This replaces the raw
1032
- * POSIX-escaped alias body (`alias c='claude '\''text with spaces'\'' …'`),
1033
- * which is correct but visually alarming — readers without POSIX shell
1034
- * fluency mistake `'\''` for broken quoting.
1035
- *
1036
- * We show each argv token on its own row, with values that need quoting
1037
- * wrapped in plain double quotes (display-only — these are NOT what gets
1038
- * written to the rc file). Composite segments (templated values) display
1039
- * with their `{token}` placeholders intact in cyan so users see exactly
1040
- * what will expand at shell-eval time.
1041
- *
1042
- * Example output:
1043
- * alias c='claude
1044
- * --dangerously-skip-permissions
1045
- * --append-system-prompt "you ae the smaretes model ever"
1046
- * --debug plugins
1047
- * '
1048
- */
1049
- function renderPreviewLines(aliasName, segments) {
1050
- if (segments.length === 0) {
1051
- return _jsx("text", { fg: "white", children: `alias ${aliasName || "?"}='claude'` });
1052
- }
1053
- const lines = [
1054
- _jsx("text", { fg: "white", children: `alias ${aliasName || "?"}='claude` }, "head"),
1055
- ];
1056
- segments.forEach((seg, i) => {
1057
- lines.push(_jsxs("text", { fg: "white", children: [" ", renderPreviewSegment(seg)] }, `arg-${i}`));
1058
- });
1059
- lines.push(_jsx("text", { fg: "white", children: "'" }, "tail"));
1060
- return _jsx(_Fragment, { children: lines });
1061
- }
1062
- function renderPreviewSegment(seg) {
1063
- if (seg.kind === "literal") {
1064
- return _jsx("span", { fg: "white", children: quoteForDisplay(seg.text) });
1065
- }
1066
- // Composite: literal parts as-is, raw parts as `{token}` reconstructed
1067
- // from the writer's TOKEN_TO_SUB map. We don't have direct access to the
1068
- // map here, so we reverse-lookup using the same forms.
1069
- const spans = [];
1070
- seg.parts.forEach((p, i) => {
1071
- if (p.kind === "literal") {
1072
- spans.push(_jsx("span", { fg: "white", children: p.text }, `p-${i}`));
1073
- }
1074
- else {
1075
- spans.push(_jsx("span", { fg: "cyan", children: substitutionToToken(p.posix) }, `p-${i}`));
1076
- }
1077
- });
1078
- return _jsx("span", { children: spans });
1079
- }
1080
- const PREVIEW_SAFE = /^[A-Za-z0-9_\-=,:.\/!@%+]+$/;
1081
- function quoteForDisplay(text) {
1082
- if (text === "")
1083
- return '""';
1084
- if (PREVIEW_SAFE.test(text))
1085
- return text;
1086
- // Display-only quoting. We don't have to escape anything for the shell
1087
- // since this string never reaches a parser — it's just for the user to
1088
- // read. We do escape an embedded `"` to keep visual balance.
1089
- return `"${text.replace(/"/g, '\\"')}"`;
1090
- }
1091
- /**
1092
- * Reverse-lookup the writer's POSIX substitution codes to their `{token}`
1093
- * forms. Mirror of `TOKEN_TO_SUB` in `alias-shell-writer.ts`.
1094
- */
1095
- function substitutionToToken(posixCode) {
1096
- switch (posixCode) {
1097
- case '$(basename "$PWD")':
1098
- return "{folder}";
1099
- case "$(date +%d)":
1100
- return "{day}";
1101
- case "$(date +%m)":
1102
- return "{month}";
1103
- case "$(date +%Y)":
1104
- return "{year}";
1105
- default:
1106
- return posixCode;
1107
- }
1108
- }
1109
- function renderFlagDetailRightPane(flag, value, aliasName, segments, derivedNote, stateOverride) {
1110
- return (_jsxs("box", { flexDirection: "column", children: [_jsx("text", { fg: "white", children: _jsx("strong", { children: flag.flag }) }), _jsx("text", { fg: "gray", children: flag.description }), derivedNote && (_jsxs(_Fragment, { children: [_jsx("text", { children: " " }), _jsx("text", { fg: "gray", children: derivedNote })] })), _jsx("text", { children: " " }), _jsxs("text", { children: [_jsx("span", { fg: "gray", children: "State: " }), _jsx("span", { fg: "white", children: stateOverride ?? summarizeValue(value) })] }), _jsx("text", { children: " " }), _jsx("text", { fg: "gray", children: "Preview:" }), renderPreviewLines(aliasName, segments), _jsx("text", { children: " " }), _jsx("text", { fg: "gray", children: "Keys:" }), _jsx("text", { fg: "white", children: " space/enter toggle the highlighted row" }), _jsx("text", { fg: "white", children: " a add a new value" }), _jsx("text", { fg: "white", children: " d delete the highlighted item" }), _jsx("text", { fg: "white", children: " h back to flag list" })] }));
1111
- }