-
Notifications
You must be signed in to change notification settings - Fork 20
Expand file tree
/
Copy pathui.jsx
More file actions
570 lines (516 loc) · 19 KB
/
ui.jsx
File metadata and controls
570 lines (516 loc) · 19 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
import React, { useState, useEffect, useRef, useCallback } from "react";
import { render, Box, Text, useApp, useInput } from "ink";
import { renderSprite, RARITY_STARS, RARITY_COLORS } from "./sprites.js";
import { existsSync, copyFileSync } from "fs";
const SPINNER_FRAMES = ["⠋", "⠙", "⠹", "⠸", "⠼", "⠴", "⠦", "⠧", "⠇", "⠏"];
function Spinner({ label }) {
const [frame, setFrame] = useState(0);
useEffect(() => {
const timer = setInterval(() => setFrame((f) => (f + 1) % SPINNER_FRAMES.length), 80);
return () => clearInterval(timer);
}, []);
return <Text><Text color="cyan">{SPINNER_FRAMES[frame]}</Text> {label}</Text>;
}
// ── Components ──────────────────────────────────────────────────────────
function KeyHint({ children }) {
return <Text italic dimColor>{children}</Text>;
}
function ListSelect({ label, options, defaultValue, onChange, onSubmit, onBack, isActive }) {
const [idx, setIdx] = useState(() => Math.max(0, options.findIndex((o) => o.value === defaultValue)));
useInput((input, key) => {
if (key.escape && onBack) { onBack(); return; }
if (key.upArrow || key.leftArrow) {
const next = (idx - 1 + options.length) % options.length;
setIdx(next);
if (onChange) onChange(options[next].value);
}
if (key.downArrow || key.rightArrow) {
const next = (idx + 1) % options.length;
setIdx(next);
if (onChange) onChange(options[next].value);
}
if (key.return) onSubmit(options[idx].value);
}, { isActive: isActive !== false });
return (
<Box flexDirection="column">
{label && <Text bold>{label}</Text>}
{options.map((opt, i) => (
<Text key={opt.value}>
<Text color={i === idx ? "cyan" : undefined}>
{i === idx ? "❯ " : " "}{opt.label}
</Text>
{opt.hint && <Text dimColor> ({opt.hint})</Text>}
</Text>
))}
<KeyHint>{onBack ? "↑↓ select · enter confirm · esc back" : "↑↓ select · enter confirm"}</KeyHint>
</Box>
);
}
function ConfirmSelect({ label, onConfirm, onCancel, onBack, isActive }) {
const [idx, setIdx] = useState(0);
const options = [
{ label: "Yes", value: true },
{ label: "No", value: false },
];
useInput((input, key) => {
if (key.escape && onBack) { onBack(); return; }
if (key.upArrow || key.downArrow || key.leftArrow || key.rightArrow) {
setIdx(idx === 0 ? 1 : 0);
}
if (key.return) {
if (options[idx].value) onConfirm();
else onCancel();
}
}, { isActive: isActive !== false });
return (
<Box flexDirection="column">
<Text bold>{label}</Text>
<Box gap={2}>
{options.map((opt, i) => (
<Text key={opt.label} color={i === idx ? "cyan" : undefined}>
{i === idx ? "❯ " : " "}{opt.label}
</Text>
))}
</Box>
<KeyHint>{onBack ? "←→ select · enter confirm · esc back" : "←→ select · enter confirm"}</KeyHint>
</Box>
);
}
function PreviewCard({ species, rarity, eye, hat, shiny, stats }) {
const color = RARITY_COLORS[rarity] ?? "white";
const stars = RARITY_STARS[rarity] ?? "";
const sprite = renderSprite({ species, eye, hat });
return (
<Box flexDirection="column" borderStyle="round" borderColor={color} paddingX={1}>
<Box>
<Box flexDirection="column">
{sprite.map((line, lineIdx) => (
<Text key={`sprite-${lineIdx}-${line.trim()}`} color={color}>{line}</Text>
))}
</Box>
<Box flexDirection="column" marginLeft={2}>
<Text bold>{species}</Text>
<Text color={color}>{rarity}{shiny ? " ✦shiny" : ""}</Text>
<Text dimColor>eye:{eye} hat:{hat}</Text>
<Text>{stars}</Text>
</Box>
</Box>
{stats && (
<Box flexDirection="column" marginTop={1}>
{Object.entries(stats).map(([k, v]) => {
const filled = Math.min(10, Math.max(0, Math.round(v / 10)));
return (
<Text key={k}>
<Text>{k.padEnd(10)} </Text>
<Text color={color}>{"█".repeat(filled)}</Text>
<Text dimColor>{"░".repeat(10 - filled)}</Text>
<Text> {String(v).padStart(3)}</Text>
</Text>
);
})}
</Box>
)}
</Box>
);
}
function ExitOnKey({ isActive, children }) {
const { exit } = useApp();
const exiting = useRef(false);
const doExit = useCallback(() => {
if (exiting.current) return;
exiting.current = true;
exit();
setTimeout(() => process.exit(0), 200);
}, [exit]);
useInput(() => doExit(), { isActive });
useEffect(() => {
if (!isActive) return;
const fallback = () => doExit();
process.stdin.once("data", fallback);
const timer = setTimeout(() => doExit(), 30000);
return () => {
process.stdin.removeListener("data", fallback);
clearTimeout(timer);
};
}, [isActive, doExit]);
return children;
}
function ShowCurrentStep({ isActive }) {
return (
<ExitOnKey isActive={isActive}>
<Box flexDirection="column">
<Text color="green">✓ Current companion shown above.</Text>
<KeyHint>Press any key to exit</KeyHint>
</Box>
</ExitOnKey>
);
}
function SpeciesStep({ speciesList, current, onChange, onSubmit, onBack, isActive }) {
const [idx, setIdx] = useState(Math.max(0, speciesList.indexOf(current)));
useInput((input, key) => {
if (key.escape && onBack) { onBack(); return; }
if (key.leftArrow || key.upArrow) {
const next = (idx - 1 + speciesList.length) % speciesList.length;
setIdx(next);
onChange(speciesList[next]);
}
if (key.rightArrow || key.downArrow) {
const next = (idx + 1) % speciesList.length;
setIdx(next);
onChange(speciesList[next]);
}
if (key.return) onSubmit();
}, { isActive });
return (
<Box flexDirection="column">
<Text bold>Species: <Text color="cyan">{speciesList[idx]}</Text> <Text dimColor>({idx + 1}/{speciesList.length})</Text></Text>
<KeyHint>←→ browse · enter select · esc back</KeyHint>
</Box>
);
}
function SearchStep({ userId, target, bruteForce, onFound, onFail, isActive }) {
const [progress, setProgress] = useState("");
const abortRef = useRef(null);
const hasStarted = useRef(false);
const { exit } = useApp();
useInput((input, key) => {
if (key.escape) {
if (abortRef.current) abortRef.current.abort();
exit();
setTimeout(() => process.exit(0), 200);
}
}, { isActive });
useEffect(() => {
if (hasStarted.current) return;
hasStarted.current = true;
const ac = new AbortController();
abortRef.current = ac;
(async () => {
let found;
try {
found = await bruteForce(userId, target, (attempts, elapsed, expected, workers) => {
if (!ac.signal.aborted) {
const elapsedSec = elapsed / 1000;
const rate = attempts / elapsedSec;
const rateStr = rate >= 1e6 ? `${(rate / 1e6).toFixed(1)}M/s` : `${(rate / 1e3).toFixed(1)}k/s`;
const fmtTime = (s) => s < 60 ? `${Math.round(s)}s` : `${Math.floor(s / 60)}m ${Math.round(s % 60)}s`;
if (attempts >= expected) {
setProgress(`Still searching... ${fmtTime(elapsedSec)} | ${rateStr} | taking longer than usual`);
} else {
const remaining = (expected - attempts) / rate;
setProgress(`Searching... ${fmtTime(elapsedSec)} | ${rateStr} | ~${fmtTime(remaining)} left`);
}
}
}, ac.signal);
} catch {
if (!ac.signal.aborted) onFail();
return;
}
if (ac.signal.aborted) return;
if (found) onFound(found);
else onFail();
})();
return () => ac.abort();
}, [bruteForce, userId, target, onFound, onFail]);
return (
<Box flexDirection="column">
<Spinner label={progress || "Looking for your buddy..."} />
<KeyHint>esc to cancel</KeyHint>
</Box>
);
}
function DoneStep({ messages, isActive }) {
const hasErrors = messages.some((msg) => msg.type === "error");
return (
<ExitOnKey isActive={isActive}>
<Box flexDirection="column">
{messages.map((msg) => (
<Text key={`${msg.type}-${msg.text}`} color={msg.type === "error" ? "red" : "green"}>
{msg.type === "error" ? "✗ " : "✓ "}{msg.text}
</Text>
))}
<Box marginTop={1}>
<Text bold>
{hasErrors
? "Something went wrong — check the issue above and try again."
: "All set! Your buddy will stick around even after updates. Restart Claude Code and say /buddy!"}
</Text>
</Box>
<KeyHint>Press any key to exit</KeyHint>
</Box>
</ExitOnKey>
);
}
const STEP_ORDER = ["action", "species", "rarity", "eye", "hat", "shiny", "peak", "dump", "confirm"];
function getPrevStep(current, rarity, peak) {
const idx = STEP_ORDER.indexOf(current);
if (idx <= 0) return null;
let prev = STEP_ORDER[idx - 1];
if (prev === "hat" && rarity === "common") prev = "eye";
if (prev === "dump" && !peak) prev = "peak";
return prev;
}
function App({ opts }) {
const { exit } = useApp();
const {
currentRoll, currentSalt, binaryPath, configPath, userId,
bruteForce, patchBinary, resignBinary, clearCompanion, getPatchability, isClaudeRunning,
rollFrom, matches, SPECIES, RARITIES, RARITY_LABELS, EYES, HATS, STAT_NAMES,
storeSalt, installHook,
} = opts;
const [step, setStep] = useState("action");
const [species, setSpecies] = useState(currentRoll.species);
const [rarity, setRarity] = useState(currentRoll.rarity);
const [eye, setEye] = useState(currentRoll.eye);
const [hat, setHat] = useState(currentRoll.hat);
const [shiny, setShiny] = useState(currentRoll.shiny);
const [peak, setPeak] = useState(null);
const [dump, setDump] = useState(null);
const [found, setFound] = useState(null);
const [doneMessages, setDoneMessages] = useState([]);
const showStats = step === "showCurrent" || step === "result" || step === "done";
const displayRoll = found ? found.result : { species, rarity, eye, hat, shiny, stats: currentRoll.stats };
const effectiveHat = rarity === "common" ? "none" : hat;
const buildTarget = (s = shiny) => {
const t = { species, rarity, eye, hat: effectiveHat, shiny: s };
if (peak) t.peak = peak;
if (dump) t.dump = dump;
return t;
};
const goBack = (toStep) => {
const prev = toStep || getPrevStep(step, rarity, peak);
if (prev) setStep(prev);
else exit();
};
return (
<Box flexDirection="column" padding={1}>
<Text bold dimColor>buddy-reroll</Text>
<PreviewCard
species={displayRoll.species}
rarity={displayRoll.rarity}
eye={displayRoll.eye}
hat={displayRoll.hat}
shiny={displayRoll.shiny}
stats={showStats ? displayRoll.stats : null}
/>
<Box marginTop={1}>
{step === "action" && (
<ListSelect
label="What would you like to do?"
options={[
{ label: "Reroll companion", value: "reroll" },
{ label: "Restore original", value: "restore" },
{ label: "Show current", value: "current" },
]}
isActive={step === "action"}
onSubmit={(action) => {
if (action === "current") {
setStep("showCurrent");
} else if (action === "restore") {
const patchability = getPatchability(binaryPath);
if (!patchability.ok) {
setDoneMessages([{ type: "error", text: patchability.message }]);
setStep("done");
return;
}
const { backupPath } = patchability;
if (!existsSync(backupPath)) {
setDoneMessages([{ type: "info", text: "No backup found — nothing to undo." }]);
setStep("done");
return;
}
try {
copyFileSync(backupPath, binaryPath);
resignBinary(binaryPath);
clearCompanion(configPath);
setDoneMessages([{ type: "success", text: "Restored! Restart Claude Code and say /buddy to see your original friend." }]);
} catch (err) {
setDoneMessages([{ type: "error", text: err.message }]);
}
setStep("done");
} else {
setStep("species");
}
}}
/>
)}
{step === "showCurrent" && (
<ShowCurrentStep isActive={step === "showCurrent"} />
)}
{step === "species" && (
<SpeciesStep
speciesList={SPECIES}
current={species}
onChange={setSpecies}
onSubmit={() => setStep("rarity")}
onBack={() => goBack("action")}
isActive={step === "species"}
/>
)}
{step === "rarity" && (
<ListSelect
label="Rarity"
options={RARITIES.map((r) => ({ label: RARITY_LABELS[r], value: r }))}
defaultValue={rarity}
onChange={(r) => {
setRarity(r);
if (r === "common") setHat("none");
}}
onSubmit={() => setStep("eye")}
onBack={() => goBack()}
isActive={step === "rarity"}
/>
)}
{step === "eye" && (
<ListSelect
label="Eye"
options={EYES.map((e) => ({ label: e, value: e }))}
defaultValue={eye}
onChange={setEye}
onSubmit={() => setStep(rarity === "common" ? "shiny" : "hat")}
onBack={() => goBack()}
isActive={step === "eye"}
/>
)}
{step === "hat" && (
<ListSelect
label="Hat"
options={HATS.map((h) => ({ label: h, value: h }))}
defaultValue={hat === "none" ? "crown" : hat}
onChange={setHat}
onSubmit={() => setStep("shiny")}
onBack={() => goBack()}
isActive={step === "hat"}
/>
)}
{step === "shiny" && (
<ConfirmSelect
label="Shiny?"
isActive={step === "shiny"}
onConfirm={() => {
setShiny(true);
setStep("peak");
}}
onCancel={() => {
setShiny(false);
setStep("peak");
}}
onBack={() => goBack()}
/>
)}
{step === "peak" && (
<ListSelect
label="Best at"
options={[
{ label: "Any (random)", value: "any" },
...(STAT_NAMES || []).map(s => ({ label: s, value: s })),
]}
defaultValue="any"
onSubmit={(v) => {
setPeak(v === "any" ? null : v);
if (v === "any") {
setStep("confirm");
} else {
setStep("dump");
}
}}
onBack={() => goBack()}
isActive={step === "peak"}
/>
)}
{step === "dump" && (
<ListSelect
label="Worst at"
options={[
{ label: "Any (random)", value: "any" },
...(STAT_NAMES || []).filter(s => s !== peak).map(s => ({ label: s, value: s })),
]}
defaultValue="any"
onSubmit={(v) => {
setDump(v === "any" ? null : v);
setStep("confirm");
}}
onBack={() => goBack()}
isActive={step === "dump"}
/>
)}
{step === "confirm" && (
<Box flexDirection="column">
<Text>Target: <Text bold>{species}</Text> / <Text bold>{rarity}</Text> / eye:{eye} / hat:{effectiveHat}{shiny ? " / shiny" : ""}{peak ? ` / peak:${peak}` : ""}{dump ? ` / dump:${dump}` : ""}</Text>
{isClaudeRunning() && <Text color="yellow">⚠ Claude Code appears to be running. Quit it before patching.</Text>}
<ConfirmSelect
label="Search and apply?"
isActive={step === "confirm"}
onConfirm={() => {
const patchability = getPatchability(binaryPath);
if (!patchability.ok) {
setDoneMessages([{ type: "error", text: patchability.message }]);
setStep("done");
return;
}
setStep("search");
}}
onCancel={() => exit()}
onBack={() => goBack()}
/>
</Box>
)}
{step === "search" && (
<SearchStep
userId={userId}
target={buildTarget()}
bruteForce={bruteForce}
onFound={(f) => { setFound(f); setStep("result"); }}
onFail={() => {
setDoneMessages([{ type: "error", text: "Couldn't find a match. Try being less picky!" }]);
setStep("done");
}}
isActive={step === "search"}
/>
)}
{step === "result" && (
<Box flexDirection="column">
<Text bold color="green">✓ Found your buddy! ({found.checked.toLocaleString()} tries, {(found.elapsed / 1000).toFixed(1)}s)</Text>
<ConfirmSelect
label="Apply patch?"
isActive={step === "result"}
onConfirm={() => {
const patchability = getPatchability(binaryPath);
if (!patchability.ok) {
setDoneMessages([{ type: "error", text: patchability.message }]);
setStep("done");
return;
}
const msgs = [];
const { backupPath } = patchability;
try {
if (!existsSync(backupPath)) {
copyFileSync(binaryPath, backupPath);
msgs.push({ type: "success", text: `Saved a backup just in case` });
}
const count = patchBinary(binaryPath, currentSalt, found.salt);
msgs.push({ type: "success", text: "Applied!" });
if (resignBinary(binaryPath)) msgs.push({ type: "success", text: "Re-signed for macOS" });
clearCompanion(configPath);
if (storeSalt) storeSalt(found.salt);
if (installHook) installHook();
msgs.push({ type: "success", text: "Cleaned up old buddy data" });
} catch (err) {
msgs.push({ type: "error", text: err.message });
}
setDoneMessages(msgs);
setStep("done");
}}
onCancel={() => exit()}
/>
</Box>
)}
{step === "done" && <DoneStep messages={doneMessages} isActive={step === "done"} />}
</Box>
</Box>
);
}
export async function runInteractiveUI(opts) {
const { waitUntilExit } = render(<App opts={opts} />);
await waitUntilExit();
}