@trans-ai/trans-code 0.3.0 → 0.5.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 +13 -3
- package/docs/superpowers/plans/2026-11-21-auto-update.md +138 -0
- package/docs/superpowers/specs/2026-11-21-auto-update-design.md +61 -0
- package/package.json +1 -1
- package/src/agent/loop.test.ts +92 -1
- package/src/agent/loop.ts +74 -0
- package/src/agent/tools/bash.test.ts +42 -1
- package/src/agent/tools/bash.ts +202 -15
- package/src/agent/tools/dispatch.test.ts +42 -0
- package/src/agent/tools/dispatch.ts +11 -1
- package/src/agent/tools/index.ts +2 -0
- package/src/agent/tools/powershell.test.ts +61 -0
- package/src/agent/tools/read-only.ts +16 -0
- package/src/agent/tools/session.ts +12 -0
- package/src/agent/tools/shell-paths.test.ts +65 -0
- package/src/agent/tools/shell-paths.ts +19 -0
- package/src/agent/tools/types.ts +2 -0
- package/src/cli.ts +9 -3
- package/src/commands.ts +18 -0
- package/src/config.test.ts +49 -0
- package/src/config.ts +42 -0
- package/src/main.tsx +2 -1
- package/src/provider/model-list.test.ts +65 -0
- package/src/provider/provider.test.ts +6 -0
- package/src/provider/provider.ts +35 -1
- package/src/screens/REPL.tsx +336 -42
- package/src/screens/slash-completion.test.ts +62 -0
- package/src/screens/slash-completion.ts +41 -0
- package/src/screens/submit.test.ts +23 -0
- package/src/screens/submit.ts +17 -0
- package/src/sessions/store.test.ts +91 -0
- package/src/sessions/store.ts +149 -0
- package/src/upgrade.test.ts +242 -0
- package/src/upgrade.ts +206 -9
- package/src/version.ts +1 -1
package/src/screens/REPL.tsx
CHANGED
|
@@ -9,6 +9,7 @@ import {
|
|
|
9
9
|
registerApiKey,
|
|
10
10
|
lookupApiKey,
|
|
11
11
|
setCustomModel,
|
|
12
|
+
listEndpointModels,
|
|
12
13
|
vendorModelSpec,
|
|
13
14
|
vendorModels,
|
|
14
15
|
verifyModel,
|
|
@@ -18,8 +19,21 @@ import { loadConfig } from '../config.js';
|
|
|
18
19
|
import { runAgentLoop, type PermissionRequest } from '../agent/loop.js';
|
|
19
20
|
import { createToolSession } from '../agent/tools/index.js';
|
|
20
21
|
import { getPermissionMode } from '../agent/permission.js';
|
|
22
|
+
import {
|
|
23
|
+
generateTitle,
|
|
24
|
+
getSession,
|
|
25
|
+
listSessions,
|
|
26
|
+
saveSession,
|
|
27
|
+
searchSessions,
|
|
28
|
+
} from '../sessions/store.js';
|
|
21
29
|
import { walkFiles } from '../agent/tools/fs-utils.js';
|
|
22
30
|
import { applyCompletion, filterFiles, mentionQuery } from './file-completion.js';
|
|
31
|
+
import {
|
|
32
|
+
applySlashCompletion,
|
|
33
|
+
filterSlashCommands,
|
|
34
|
+
slashQuery,
|
|
35
|
+
} from './slash-completion.js';
|
|
36
|
+
import { resolveSubmitInput } from './submit.js';
|
|
23
37
|
import { renderDiff } from './diff-render.js';
|
|
24
38
|
import { createTurnStats, recordCall, shouldCollapse, summaryLine } from './turn-summary.js';
|
|
25
39
|
import { buildSystemPrompt, INIT_PROMPT, loadProjectContext } from '../agent/system-prompt.js';
|
|
@@ -42,9 +56,11 @@ type PromptPhase =
|
|
|
42
56
|
|
|
43
57
|
interface REPLProps {
|
|
44
58
|
ctx: CommandContext;
|
|
59
|
+
/** Background auto-update outcome; a non-null message shows as a banner. */
|
|
60
|
+
updateNotice?: Promise<string | null>;
|
|
45
61
|
}
|
|
46
62
|
|
|
47
|
-
export default function REPL({ ctx }: REPLProps) {
|
|
63
|
+
export default function REPL({ ctx, updateNotice }: REPLProps) {
|
|
48
64
|
const { exit } = useApp();
|
|
49
65
|
const [input, setInput] = useState('');
|
|
50
66
|
// Multiple keystrokes can be handled in one React batch before a
|
|
@@ -68,14 +84,23 @@ export default function REPL({ ctx }: REPLProps) {
|
|
|
68
84
|
fail: number;
|
|
69
85
|
} | null>(null);
|
|
70
86
|
const [pendingModel, setPendingModel] = useState<ModelId | null>(null);
|
|
87
|
+
const pendingModelRef = useRef<ModelId | null>(null);
|
|
88
|
+
const setVendor = (id: ModelId | null) => {
|
|
89
|
+
pendingModelRef.current = id;
|
|
90
|
+
setPendingModel(id);
|
|
91
|
+
};
|
|
71
92
|
const [modelCursor, setModelCursor] = useState(0);
|
|
72
93
|
// Model selection flow: vendor → model → key (reused if saved) → check.
|
|
73
94
|
const [pickOptions, setPickOptions] = useState<string[]>([]);
|
|
74
95
|
const [pickCursor, setPickCursor] = useState(0);
|
|
96
|
+
const [pickLive, setPickLive] = useState(false);
|
|
97
|
+
const [pickLoading, setPickLoading] = useState(false);
|
|
98
|
+
const vendorModelCache = useRef(new Map<string, string[]>());
|
|
75
99
|
const [pendingSpec, setPendingSpec] = useState<string | null>(null);
|
|
76
100
|
const [pendingDisplayName, setPendingDisplayName] = useState('');
|
|
77
101
|
const [keyHint, setKeyHint] = useState<string | null>(null);
|
|
78
102
|
const [customBaseDraft, setCustomBaseDraft] = useState('');
|
|
103
|
+
const [customKeyDraft, setCustomKeyDraft] = useState('');
|
|
79
104
|
|
|
80
105
|
const models = getAvailableModels();
|
|
81
106
|
// Bun's scheduler can drop the render flush for updates issued from the
|
|
@@ -98,6 +123,10 @@ export default function REPL({ ctx }: REPLProps) {
|
|
|
98
123
|
// One tool session per process: bash cwd and read-file state persist
|
|
99
124
|
// across prompts, like the ACP session.
|
|
100
125
|
const toolSessionRef = useRef(createToolSession(process.cwd()));
|
|
126
|
+
// Conversation persistence: lazily created record + model-generated title.
|
|
127
|
+
const conversationRef = useRef<{ id: string; createdAt: number; titled: boolean } | null>(null);
|
|
128
|
+
const conversationTitleRef = useRef('');
|
|
129
|
+
const lastSessionsRef = useRef<string[]>([]);
|
|
101
130
|
|
|
102
131
|
// @-mention file completion: lazy file list, active query, dismissed flag.
|
|
103
132
|
const [fileList, setFileList] = useState<string[] | null>(null);
|
|
@@ -134,6 +163,38 @@ export default function REPL({ ctx }: REPLProps) {
|
|
|
134
163
|
() => (mentionActive && fileList ? filterFiles(fileList, mention ?? '', 8) : []),
|
|
135
164
|
[mentionActive, fileList, mention],
|
|
136
165
|
);
|
|
166
|
+
|
|
167
|
+
// Slash-command popup (mirrors the @-mention popup): candidates for the
|
|
168
|
+
// current input, a cursor, and a dismissed flag reset when the query changes.
|
|
169
|
+
const [slashCursor, setSlashCursor] = useState(0);
|
|
170
|
+
const [slashDismissed, setSlashDismissed] = useState(false);
|
|
171
|
+
const slashPrefix = phase === 'idle' && !busy ? slashQuery(input) : null;
|
|
172
|
+
const slashCandidates = useMemo(
|
|
173
|
+
() =>
|
|
174
|
+
slashPrefix !== null && !slashDismissed
|
|
175
|
+
? filterSlashCommands(input, getCommands())
|
|
176
|
+
: [],
|
|
177
|
+
[slashPrefix, slashDismissed, input],
|
|
178
|
+
);
|
|
179
|
+
useEffect(() => {
|
|
180
|
+
setSlashCursor(0);
|
|
181
|
+
if (slashPrefix === null) setSlashDismissed(false);
|
|
182
|
+
}, [slashPrefix]);
|
|
183
|
+
|
|
184
|
+
// Background auto-update outcome: surface as a history banner once settled.
|
|
185
|
+
useEffect(() => {
|
|
186
|
+
if (!updateNotice) return;
|
|
187
|
+
let cancelled = false;
|
|
188
|
+
void updateNotice.then(message => {
|
|
189
|
+
if (!cancelled && message) {
|
|
190
|
+
addHistory({ input: '', output: message });
|
|
191
|
+
dragFlush();
|
|
192
|
+
}
|
|
193
|
+
});
|
|
194
|
+
return () => {
|
|
195
|
+
cancelled = true;
|
|
196
|
+
};
|
|
197
|
+
}, [updateNotice, addHistory, dragFlush]);
|
|
137
198
|
const pendingPermissionRef = useRef<{
|
|
138
199
|
request: PermissionRequest;
|
|
139
200
|
resolve: (allow: boolean) => void;
|
|
@@ -176,11 +237,14 @@ export default function REPL({ ctx }: REPLProps) {
|
|
|
176
237
|
);
|
|
177
238
|
|
|
178
239
|
const runChat = useCallback(
|
|
179
|
-
async (text: string, display?: string) => {
|
|
240
|
+
async (text: string, display?: string, options?: { planMode?: boolean }) => {
|
|
180
241
|
setBusyBoth(true);
|
|
181
242
|
const controller = new AbortController();
|
|
182
243
|
abortRef.current = controller;
|
|
183
244
|
addHistory({ input: display ?? text, output: '' });
|
|
245
|
+
if (options?.planMode) {
|
|
246
|
+
appendChatOutput('[plan 模式:只读探索,产出方案,PLAN READY 后可让我执行]\n');
|
|
247
|
+
}
|
|
184
248
|
|
|
185
249
|
try {
|
|
186
250
|
const provider =
|
|
@@ -201,6 +265,7 @@ export default function REPL({ ctx }: REPLProps) {
|
|
|
201
265
|
messagesRef.current.push(new HumanMessage(text));
|
|
202
266
|
|
|
203
267
|
let lastWasTool = false;
|
|
268
|
+
let turnAssistantText = '';
|
|
204
269
|
const stats = createTurnStats();
|
|
205
270
|
const titlesById = new Map<string, string>();
|
|
206
271
|
const bufferedLines: string[] = [];
|
|
@@ -209,12 +274,16 @@ export default function REPL({ ctx }: REPLProps) {
|
|
|
209
274
|
model: provider?.model,
|
|
210
275
|
cwd: process.cwd(),
|
|
211
276
|
messages: messagesRef.current,
|
|
212
|
-
systemPrompt
|
|
277
|
+
systemPrompt: options?.planMode
|
|
278
|
+
? `${systemPrompt}\n\nPLAN MODE: explore read-only, then output a numbered implementation plan with exact files and changes. End with the line PLAN READY. Do not modify anything.`
|
|
279
|
+
: systemPrompt,
|
|
280
|
+
planMode: options?.planMode === true,
|
|
213
281
|
signal: controller.signal,
|
|
214
282
|
toolSession: toolSessionRef.current,
|
|
215
283
|
onEvent: event => {
|
|
216
284
|
if (event.type === 'text') {
|
|
217
285
|
appendChatOutput(lastWasTool ? `\n${event.text}` : event.text);
|
|
286
|
+
turnAssistantText += event.text;
|
|
218
287
|
lastWasTool = false;
|
|
219
288
|
} else if (event.type === 'max_turns_reached') {
|
|
220
289
|
appendChatOutput(
|
|
@@ -257,6 +326,44 @@ export default function REPL({ ctx }: REPLProps) {
|
|
|
257
326
|
}
|
|
258
327
|
|
|
259
328
|
messagesRef.current = result.messages;
|
|
329
|
+
|
|
330
|
+
// Persist the conversation for /sessions and /resume.
|
|
331
|
+
if (!conversationRef.current) {
|
|
332
|
+
conversationRef.current = {
|
|
333
|
+
id: `ses_${Date.now().toString(36)}_${Math.random().toString(36).slice(2, 6)}`,
|
|
334
|
+
createdAt: Date.now(),
|
|
335
|
+
titled: false,
|
|
336
|
+
};
|
|
337
|
+
conversationTitleRef.current = text.replace(/\s+/g, ' ').trim().slice(0, 24) || '新对话';
|
|
338
|
+
}
|
|
339
|
+
const conversation = conversationRef.current;
|
|
340
|
+
const persist = () =>
|
|
341
|
+
saveSession({
|
|
342
|
+
id: conversation.id,
|
|
343
|
+
title: conversationTitleRef.current,
|
|
344
|
+
createdAt: conversation.createdAt,
|
|
345
|
+
updatedAt: Date.now(),
|
|
346
|
+
cwd: process.cwd(),
|
|
347
|
+
model: ctx.modelId,
|
|
348
|
+
messages: messagesRef.current,
|
|
349
|
+
});
|
|
350
|
+
persist();
|
|
351
|
+
if (!conversation.titled && provider) {
|
|
352
|
+
conversation.titled = true;
|
|
353
|
+
const firstUserText = text;
|
|
354
|
+
void (async () => {
|
|
355
|
+
try {
|
|
356
|
+
conversationTitleRef.current = await generateTitle(
|
|
357
|
+
provider.model,
|
|
358
|
+
firstUserText,
|
|
359
|
+
turnAssistantText,
|
|
360
|
+
);
|
|
361
|
+
} catch {
|
|
362
|
+
// keep the derived fallback title
|
|
363
|
+
}
|
|
364
|
+
persist();
|
|
365
|
+
})();
|
|
366
|
+
}
|
|
260
367
|
if (controller.signal.aborted) appendChatOutput('\n(cancelled)');
|
|
261
368
|
} catch (error) {
|
|
262
369
|
const message = error instanceof Error ? error.message : String(error);
|
|
@@ -309,33 +416,26 @@ export default function REPL({ ctx }: REPLProps) {
|
|
|
309
416
|
setPendingSpec(null);
|
|
310
417
|
setPendingDisplayName('');
|
|
311
418
|
setKeyHint(null);
|
|
312
|
-
|
|
419
|
+
setCustomBaseDraft('');
|
|
420
|
+
setCustomKeyDraft('');
|
|
421
|
+
setVendor(null);
|
|
313
422
|
setPhase('idle');
|
|
314
423
|
dragFlush();
|
|
315
424
|
},
|
|
316
425
|
[ctx, addHistory, dragFlush],
|
|
317
426
|
);
|
|
318
427
|
|
|
319
|
-
|
|
320
|
-
|
|
321
|
-
|
|
322
|
-
const savedKey = lookupApiKey(spec);
|
|
323
|
-
const apiKey = value.trim() || savedKey;
|
|
324
|
-
|
|
325
|
-
if (!apiKey) {
|
|
326
|
-
addHistory({ input: '••••••••', output: 'API key 不能为空。' });
|
|
327
|
-
return; // stay on the key prompt
|
|
328
|
-
}
|
|
329
|
-
|
|
428
|
+
/** Verify a selection and apply it, or surface the error and re-prompt. */
|
|
429
|
+
const finalizeSelection = useCallback(
|
|
430
|
+
async (spec: string, displayName: string, apiKey: string) => {
|
|
330
431
|
if (process.env.TRANSCODE_SKIP_MODEL_CHECK === '1') {
|
|
331
|
-
applyModelSwitch(spec,
|
|
432
|
+
applyModelSwitch(spec, displayName, apiKey, '已跳过连通性测试');
|
|
332
433
|
return;
|
|
333
434
|
}
|
|
334
|
-
|
|
335
435
|
setPhase('model_check');
|
|
336
436
|
const result = await verifyModel(spec, apiKey);
|
|
337
437
|
if (result.ok) {
|
|
338
|
-
applyModelSwitch(spec,
|
|
438
|
+
applyModelSwitch(spec, displayName, apiKey, `✓ ${result.message}`);
|
|
339
439
|
return;
|
|
340
440
|
}
|
|
341
441
|
addHistory({
|
|
@@ -346,12 +446,62 @@ export default function REPL({ ctx }: REPLProps) {
|
|
|
346
446
|
commitInput('');
|
|
347
447
|
dragFlush();
|
|
348
448
|
},
|
|
349
|
-
[
|
|
449
|
+
[applyModelSwitch, addHistory, commitInput, dragFlush],
|
|
450
|
+
);
|
|
451
|
+
|
|
452
|
+
const handleApiKey = useCallback(
|
|
453
|
+
async (value: string) => {
|
|
454
|
+
// Custom-gateway setup: collect the key, then pick the model from the
|
|
455
|
+
// gateway's live list instead of asking for a blind model name.
|
|
456
|
+
if (pendingSpec === null && pendingModel === null && customBaseDraft) {
|
|
457
|
+
const apiKey = value.trim() || lookupApiKey('custom');
|
|
458
|
+
if (!apiKey) {
|
|
459
|
+
addHistory({ input: '••••••••', output: 'API key 不能为空。' });
|
|
460
|
+
return;
|
|
461
|
+
}
|
|
462
|
+
setCustomKeyDraft(apiKey);
|
|
463
|
+
setPickOptions([]);
|
|
464
|
+
setPickCursor(0);
|
|
465
|
+
setPickLive(false);
|
|
466
|
+
setPhase('model_pick');
|
|
467
|
+
commitInput('');
|
|
468
|
+
setPickLoading(true);
|
|
469
|
+
const live = await listEndpointModels('', { baseUrl: customBaseDraft, apiKey });
|
|
470
|
+
setPickOptions(live);
|
|
471
|
+
setPickLive(live.length > 0);
|
|
472
|
+
setPickLoading(false);
|
|
473
|
+
dragFlush();
|
|
474
|
+
return;
|
|
475
|
+
}
|
|
476
|
+
|
|
477
|
+
const spec = pendingSpec!;
|
|
478
|
+
const savedKey = lookupApiKey(spec);
|
|
479
|
+
const apiKey = value.trim() || savedKey;
|
|
480
|
+
|
|
481
|
+
if (!apiKey) {
|
|
482
|
+
addHistory({ input: '••••••••', output: 'API key 不能为空。' });
|
|
483
|
+
return; // stay on the key prompt
|
|
484
|
+
}
|
|
485
|
+
|
|
486
|
+
await finalizeSelection(spec, pendingDisplayName, apiKey);
|
|
487
|
+
},
|
|
488
|
+
[
|
|
489
|
+
pendingSpec,
|
|
490
|
+
pendingModel,
|
|
491
|
+
pendingDisplayName,
|
|
492
|
+
customBaseDraft,
|
|
493
|
+
addHistory,
|
|
494
|
+
finalizeSelection,
|
|
495
|
+
commitInput,
|
|
496
|
+
dragFlush,
|
|
497
|
+
],
|
|
350
498
|
);
|
|
351
499
|
|
|
352
500
|
const handleSubmit = useCallback(async (raw: string) => {
|
|
353
|
-
|
|
354
|
-
|
|
501
|
+
// Bare Enter is a no-op except at the apikey prompt, where it means
|
|
502
|
+
// "reuse the saved key" (the prompt's 回车沿用 hint).
|
|
503
|
+
const trimmed = resolveSubmitInput(phase, raw);
|
|
504
|
+
if (trimmed === null) return;
|
|
355
505
|
|
|
356
506
|
if (phase === 'model_apikey' || phase === 'model_check') {
|
|
357
507
|
await handleApiKey(trimmed);
|
|
@@ -365,7 +515,9 @@ export default function REPL({ ctx }: REPLProps) {
|
|
|
365
515
|
return;
|
|
366
516
|
}
|
|
367
517
|
setCustomBaseDraft(trimmed);
|
|
368
|
-
|
|
518
|
+
setKeyHint(lookupApiKey('custom') ? maskKey(lookupApiKey('custom')!) : null);
|
|
519
|
+
setPendingSpec(null);
|
|
520
|
+
setPhase('model_apikey');
|
|
369
521
|
commitInput('');
|
|
370
522
|
return;
|
|
371
523
|
}
|
|
@@ -373,9 +525,9 @@ export default function REPL({ ctx }: REPLProps) {
|
|
|
373
525
|
if (phase === 'model_name') {
|
|
374
526
|
if (!trimmed) return;
|
|
375
527
|
if (pendingModel === null) {
|
|
376
|
-
// Custom gateway
|
|
528
|
+
// Custom gateway, free-text model name (live list was empty/unreachable).
|
|
377
529
|
setCustomModel({ baseUrl: customBaseDraft, model: trimmed });
|
|
378
|
-
|
|
530
|
+
await finalizeSelection('custom', `custom/${trimmed}`, customKeyDraft);
|
|
379
531
|
} else {
|
|
380
532
|
beginKeyStep(vendorModelSpec(pendingModel, trimmed), `${pendingModel}/${trimmed}`);
|
|
381
533
|
}
|
|
@@ -396,6 +548,91 @@ export default function REPL({ ctx }: REPLProps) {
|
|
|
396
548
|
return;
|
|
397
549
|
}
|
|
398
550
|
|
|
551
|
+
if (cmdName === 'new') {
|
|
552
|
+
conversationRef.current = null;
|
|
553
|
+
conversationTitleRef.current = '';
|
|
554
|
+
messagesRef.current = [];
|
|
555
|
+
toolSessionRef.current = createToolSession(process.cwd());
|
|
556
|
+
addHistory({ input: trimmed, output: '已开始新对话。' });
|
|
557
|
+
commitInput('');
|
|
558
|
+
setHistoryIndex(-1);
|
|
559
|
+
setSavedInput('');
|
|
560
|
+
dragFlush();
|
|
561
|
+
return;
|
|
562
|
+
}
|
|
563
|
+
|
|
564
|
+
if (cmdName === 'sessions') {
|
|
565
|
+
const keyword = args.join(' ');
|
|
566
|
+
const found = keyword.trim() ? searchSessions(keyword) : listSessions();
|
|
567
|
+
lastSessionsRef.current = found.map((session) => session.id);
|
|
568
|
+
const lines = found
|
|
569
|
+
.slice(0, 20)
|
|
570
|
+
.map(
|
|
571
|
+
(session, index) =>
|
|
572
|
+
`${index + 1}. ${session.title} · ${new Date(session.updatedAt).toLocaleString()} · ` +
|
|
573
|
+
`${session.model} · ${session.messages.length} 条`,
|
|
574
|
+
);
|
|
575
|
+
addHistory({
|
|
576
|
+
input: trimmed,
|
|
577
|
+
output: found.length
|
|
578
|
+
? `${keyword.trim() ? `匹配“${keyword}”` : ''}${found.length} 个对话:\n${lines.join('\n')}\n/resume <序号|id|标题片段> 恢复`
|
|
579
|
+
: keyword.trim()
|
|
580
|
+
? `没有匹配“${keyword}”的对话。`
|
|
581
|
+
: '暂无历史对话。',
|
|
582
|
+
});
|
|
583
|
+
commitInput('');
|
|
584
|
+
setHistoryIndex(-1);
|
|
585
|
+
setSavedInput('');
|
|
586
|
+
dragFlush();
|
|
587
|
+
return;
|
|
588
|
+
}
|
|
589
|
+
|
|
590
|
+
if (cmdName === 'resume') {
|
|
591
|
+
const target = args.join(' ').trim();
|
|
592
|
+
const list = listSessions();
|
|
593
|
+
let record = undefined as ReturnType<typeof getSession>;
|
|
594
|
+
if (/^\d+$/.test(target)) {
|
|
595
|
+
const indexed = lastSessionsRef.current[Number(target) - 1];
|
|
596
|
+
record = (indexed ? getSession(indexed) : undefined) ?? list[Number(target) - 1];
|
|
597
|
+
} else if (target) {
|
|
598
|
+
record = getSession(target) ?? list.find(
|
|
599
|
+
(session) => session.id.includes(target) || session.title.includes(target),
|
|
600
|
+
);
|
|
601
|
+
}
|
|
602
|
+
if (!record) {
|
|
603
|
+
addHistory({ input: trimmed, output: `未找到对话“${target || '(空)'}”。先 /sessions 查看列表。` });
|
|
604
|
+
} else {
|
|
605
|
+
conversationRef.current = { id: record.id, createdAt: record.createdAt, titled: true };
|
|
606
|
+
conversationTitleRef.current = record.title;
|
|
607
|
+
messagesRef.current = record.messages;
|
|
608
|
+
toolSessionRef.current = createToolSession(process.cwd());
|
|
609
|
+
addHistory({
|
|
610
|
+
input: trimmed,
|
|
611
|
+
output: `已恢复「${record.title}」(${record.messages.length} 条消息,${record.model}),继续对话。`,
|
|
612
|
+
});
|
|
613
|
+
}
|
|
614
|
+
commitInput('');
|
|
615
|
+
setHistoryIndex(-1);
|
|
616
|
+
setSavedInput('');
|
|
617
|
+
dragFlush();
|
|
618
|
+
return;
|
|
619
|
+
}
|
|
620
|
+
|
|
621
|
+
if (cmdName === 'plan') {
|
|
622
|
+
const task = stripped.startsWith('/plan') ? stripped.slice(5).trim() : stripped;
|
|
623
|
+
if (!task) {
|
|
624
|
+
addHistory({ input: trimmed, output: '用法:/plan <任务描述> — 只读探索并产出实施方案(PLAN READY),确认后再执行' });
|
|
625
|
+
dragFlush();
|
|
626
|
+
commitInput('');
|
|
627
|
+
return;
|
|
628
|
+
}
|
|
629
|
+
commitInput('');
|
|
630
|
+
setHistoryIndex(-1);
|
|
631
|
+
setSavedInput('');
|
|
632
|
+
await runChat(task, trimmed, { planMode: true });
|
|
633
|
+
return;
|
|
634
|
+
}
|
|
635
|
+
|
|
399
636
|
if (cmdName === 'init') {
|
|
400
637
|
commitInput('');
|
|
401
638
|
setHistoryIndex(-1);
|
|
@@ -448,6 +685,11 @@ export default function REPL({ ctx }: REPLProps) {
|
|
|
448
685
|
setMentionDismissed(true);
|
|
449
686
|
return;
|
|
450
687
|
}
|
|
688
|
+
// Slash-command popup: same — Esc dismisses instead of exiting.
|
|
689
|
+
if (key.escape && slashCandidates.length > 0) {
|
|
690
|
+
setSlashDismissed(true);
|
|
691
|
+
return;
|
|
692
|
+
}
|
|
451
693
|
if (key.escape) {
|
|
452
694
|
// While generating, Esc cancels instead of exiting.
|
|
453
695
|
if (busyRef.current && abortRef.current) {
|
|
@@ -456,7 +698,7 @@ export default function REPL({ ctx }: REPLProps) {
|
|
|
456
698
|
}
|
|
457
699
|
if (phase !== 'idle') {
|
|
458
700
|
setPhase('idle');
|
|
459
|
-
|
|
701
|
+
setVendor(null);
|
|
460
702
|
commitInput('');
|
|
461
703
|
addHistory({ input: '', output: 'Cancelled.' });
|
|
462
704
|
return;
|
|
@@ -482,7 +724,7 @@ export default function REPL({ ctx }: REPLProps) {
|
|
|
482
724
|
const selected = models[modelCursor];
|
|
483
725
|
if (selected.id === 'custom') {
|
|
484
726
|
const saved = loadConfig().custom;
|
|
485
|
-
|
|
727
|
+
setVendor(null);
|
|
486
728
|
if (saved?.baseUrl && saved.model) {
|
|
487
729
|
beginKeyStep('custom', `custom/${saved.model}`);
|
|
488
730
|
} else {
|
|
@@ -491,12 +733,35 @@ export default function REPL({ ctx }: REPLProps) {
|
|
|
491
733
|
}
|
|
492
734
|
return;
|
|
493
735
|
}
|
|
494
|
-
|
|
495
|
-
|
|
496
|
-
setPickOptions(options);
|
|
736
|
+
setVendor(selected.id);
|
|
737
|
+
setPickOptions(vendorModels(selected.id));
|
|
497
738
|
setPickCursor(0);
|
|
739
|
+
setPickLive(false);
|
|
498
740
|
setPhase('model_pick');
|
|
499
741
|
commitInput('');
|
|
742
|
+
|
|
743
|
+
// Prefer the endpoint's live model list (what it actually serves)
|
|
744
|
+
// over the curated fallback; cache per vendor for this process.
|
|
745
|
+
const vendor = selected.id;
|
|
746
|
+
const cached = vendorModelCache.current.get(vendor);
|
|
747
|
+
if (cached) {
|
|
748
|
+
if (cached.length > 0) {
|
|
749
|
+
setPickOptions(cached);
|
|
750
|
+
setPickLive(true);
|
|
751
|
+
}
|
|
752
|
+
} else {
|
|
753
|
+
setPickLoading(true);
|
|
754
|
+
void listEndpointModels(vendor)
|
|
755
|
+
.then((live) => {
|
|
756
|
+
vendorModelCache.current.set(vendor, live);
|
|
757
|
+
if (live.length > 0 && pendingModelRef.current === vendor) {
|
|
758
|
+
setPickOptions(live);
|
|
759
|
+
setPickCursor(0);
|
|
760
|
+
setPickLive(true);
|
|
761
|
+
}
|
|
762
|
+
})
|
|
763
|
+
.finally(() => setPickLoading(false));
|
|
764
|
+
}
|
|
500
765
|
return;
|
|
501
766
|
}
|
|
502
767
|
if (key.upArrow) {
|
|
@@ -519,7 +784,13 @@ export default function REPL({ ctx }: REPLProps) {
|
|
|
519
784
|
return;
|
|
520
785
|
}
|
|
521
786
|
const modelName = pickOptions[pickCursor]!;
|
|
522
|
-
|
|
787
|
+
if (pendingModel === null && customBaseDraft) {
|
|
788
|
+
// Custom gateway: model chosen from the live list.
|
|
789
|
+
setCustomModel({ baseUrl: customBaseDraft, model: modelName });
|
|
790
|
+
void finalizeSelection('custom', `custom/${modelName}`, customKeyDraft);
|
|
791
|
+
} else {
|
|
792
|
+
beginKeyStep(vendorModelSpec(pendingModel!, modelName), `${pendingModel}/${modelName}`);
|
|
793
|
+
}
|
|
523
794
|
commitInput('');
|
|
524
795
|
return;
|
|
525
796
|
}
|
|
@@ -551,6 +822,23 @@ export default function REPL({ ctx }: REPLProps) {
|
|
|
551
822
|
}
|
|
552
823
|
}
|
|
553
824
|
|
|
825
|
+
// Slash-command popup: ↑↓ navigate, Tab/Enter complete (takes precedence
|
|
826
|
+
// over history navigation and submission).
|
|
827
|
+
if (phase === 'idle' && slashCandidates.length > 0) {
|
|
828
|
+
if (key.upArrow) {
|
|
829
|
+
setSlashCursor(prev => (prev - 1 + slashCandidates.length) % slashCandidates.length);
|
|
830
|
+
return;
|
|
831
|
+
}
|
|
832
|
+
if (key.downArrow) {
|
|
833
|
+
setSlashCursor(prev => (prev + 1) % slashCandidates.length);
|
|
834
|
+
return;
|
|
835
|
+
}
|
|
836
|
+
if (key.tab || key.return) {
|
|
837
|
+
commitInput(applySlashCompletion(inputRef.current, slashCandidates[slashCursor]!.name));
|
|
838
|
+
return;
|
|
839
|
+
}
|
|
840
|
+
}
|
|
841
|
+
|
|
554
842
|
if (key.return) {
|
|
555
843
|
if (busyRef.current) return; // still generating; Esc cancels
|
|
556
844
|
handleSubmit(inputRef.current);
|
|
@@ -681,6 +969,9 @@ export default function REPL({ ctx }: REPLProps) {
|
|
|
681
969
|
|
|
682
970
|
{phase === 'model_pick' && (
|
|
683
971
|
<Box flexDirection="column" marginLeft={2}>
|
|
972
|
+
{pendingModel === null && customBaseDraft && (
|
|
973
|
+
<Text color="gray" dimColor>自定义网关 {customBaseDraft} 的模型:</Text>
|
|
974
|
+
)}
|
|
684
975
|
{pickOptions.map((name, i) => (
|
|
685
976
|
<Box key={name}>
|
|
686
977
|
<Text color={i === pickCursor ? 'cyan' : undefined}>
|
|
@@ -695,6 +986,8 @@ export default function REPL({ ctx }: REPLProps) {
|
|
|
695
986
|
自定义模型名…
|
|
696
987
|
</Text>
|
|
697
988
|
</Box>
|
|
989
|
+
{pickLoading && <Text color="gray" dimColor>… 正在从网关获取实时模型列表</Text>}
|
|
990
|
+
{!pickLoading && pickLive && <Text color="gray" dimColor>(网关实时列表)</Text>}
|
|
698
991
|
<Text color="gray" dimColor>↑↓ 选择模型 · Enter 确认</Text>
|
|
699
992
|
</Box>
|
|
700
993
|
)}
|
|
@@ -713,18 +1006,19 @@ export default function REPL({ ctx }: REPLProps) {
|
|
|
713
1006
|
</Box>
|
|
714
1007
|
)}
|
|
715
1008
|
|
|
716
|
-
{phase === 'idle' &&
|
|
717
|
-
|
|
718
|
-
|
|
719
|
-
|
|
720
|
-
|
|
721
|
-
|
|
722
|
-
|
|
723
|
-
|
|
724
|
-
|
|
725
|
-
|
|
726
|
-
|
|
727
|
-
|
|
1009
|
+
{phase === 'idle' && slashCandidates.length > 0 && (
|
|
1010
|
+
<Box flexDirection="column" marginLeft={2}>
|
|
1011
|
+
{slashCandidates.map((cmd, i) => (
|
|
1012
|
+
<Box key={cmd.name}>
|
|
1013
|
+
<Text color={i === slashCursor ? 'cyan' : 'gray'}>
|
|
1014
|
+
{i === slashCursor ? '❯ ' : ' '}
|
|
1015
|
+
/{cmd.name.padEnd(10)} {cmd.description}
|
|
1016
|
+
</Text>
|
|
1017
|
+
</Box>
|
|
1018
|
+
))}
|
|
1019
|
+
<Text color="gray" dimColor>↑↓ navigate · tab/enter complete · esc close</Text>
|
|
1020
|
+
</Box>
|
|
1021
|
+
)}
|
|
728
1022
|
|
|
729
1023
|
{phase === 'idle' && !busy && mentionActive && (
|
|
730
1024
|
<Box flexDirection="column" marginLeft={2}>
|
|
@@ -0,0 +1,62 @@
|
|
|
1
|
+
import { describe, expect, test } from 'bun:test';
|
|
2
|
+
import {
|
|
3
|
+
applySlashCompletion,
|
|
4
|
+
filterSlashCommands,
|
|
5
|
+
slashQuery,
|
|
6
|
+
} from './slash-completion.js';
|
|
7
|
+
|
|
8
|
+
const CMDS = [
|
|
9
|
+
{ name: 'help', description: 'Show help' },
|
|
10
|
+
{ name: 'models', description: 'List and switch model' },
|
|
11
|
+
{ name: 'new', description: 'Start a new conversation' },
|
|
12
|
+
];
|
|
13
|
+
|
|
14
|
+
describe('slashQuery', () => {
|
|
15
|
+
test('extracts the command prefix after the slash', () => {
|
|
16
|
+
expect(slashQuery('/')).toBe('');
|
|
17
|
+
expect(slashQuery('/mo')).toBe('mo');
|
|
18
|
+
expect(slashQuery('/models')).toBe('models');
|
|
19
|
+
});
|
|
20
|
+
|
|
21
|
+
test('returns null for non-slash input', () => {
|
|
22
|
+
expect(slashQuery('')).toBeNull();
|
|
23
|
+
expect(slashQuery('hello')).toBeNull();
|
|
24
|
+
expect(slashQuery('a /b')).toBeNull();
|
|
25
|
+
});
|
|
26
|
+
});
|
|
27
|
+
|
|
28
|
+
describe('filterSlashCommands', () => {
|
|
29
|
+
test('bare slash lists every command', () => {
|
|
30
|
+
expect(filterSlashCommands('/', CMDS)).toEqual(CMDS);
|
|
31
|
+
});
|
|
32
|
+
|
|
33
|
+
test('prefix-matches case-insensitively', () => {
|
|
34
|
+
expect(filterSlashCommands('/MO', CMDS)).toEqual([CMDS[1]]);
|
|
35
|
+
});
|
|
36
|
+
|
|
37
|
+
test('no matches (or non-slash input) yields an empty list', () => {
|
|
38
|
+
expect(filterSlashCommands('/xyz', CMDS)).toEqual([]);
|
|
39
|
+
expect(filterSlashCommands('/plan task', CMDS)).toEqual([]);
|
|
40
|
+
expect(filterSlashCommands('hello', CMDS)).toEqual([]);
|
|
41
|
+
});
|
|
42
|
+
|
|
43
|
+
test('a lone exact match suppresses the popup (Enter should submit)', () => {
|
|
44
|
+
// Typing the full command name hides the popup so Enter runs the
|
|
45
|
+
// command instead of completing it.
|
|
46
|
+
expect(filterSlashCommands('/models', CMDS)).toEqual([]);
|
|
47
|
+
// …while a shared or partial prefix keeps it visible.
|
|
48
|
+
expect(filterSlashCommands('/mo', CMDS)).toEqual([CMDS[1]]);
|
|
49
|
+
expect(filterSlashCommands('/n', CMDS)).toEqual([CMDS[2]]);
|
|
50
|
+
});
|
|
51
|
+
});
|
|
52
|
+
|
|
53
|
+
describe('applySlashCompletion', () => {
|
|
54
|
+
test('replaces the slash token with the selected command plus a space', () => {
|
|
55
|
+
expect(applySlashCompletion('/mo', 'models')).toBe('/models ');
|
|
56
|
+
expect(applySlashCompletion('/', 'plan')).toBe('/plan ');
|
|
57
|
+
});
|
|
58
|
+
|
|
59
|
+
test('leaves non-slash input untouched', () => {
|
|
60
|
+
expect(applySlashCompletion('hello', 'models')).toBe('hello');
|
|
61
|
+
});
|
|
62
|
+
});
|
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Pure helpers for the REPL slash-command popup. Rendering/keys live in
|
|
3
|
+
* REPL.tsx (mirroring the @-mention popup); these are the testable parts.
|
|
4
|
+
*/
|
|
5
|
+
|
|
6
|
+
export interface SlashCommand {
|
|
7
|
+
name: string;
|
|
8
|
+
description: string;
|
|
9
|
+
}
|
|
10
|
+
|
|
11
|
+
/** Returns the command prefix after a leading '/', or null if input has none. */
|
|
12
|
+
export function slashQuery(input: string): string | null {
|
|
13
|
+
if (!input.startsWith('/')) return null;
|
|
14
|
+
return input.slice(1);
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
/**
|
|
18
|
+
* Commands visible in the popup for the current input: prefix matches,
|
|
19
|
+
* case-insensitive. A lone exact match suppresses the popup so Enter
|
|
20
|
+
* submits the typed command instead of completing it. Non-slash input,
|
|
21
|
+
* or input with arguments (no matching prefix), yields an empty list.
|
|
22
|
+
*/
|
|
23
|
+
export function filterSlashCommands(
|
|
24
|
+
input: string,
|
|
25
|
+
commands: SlashCommand[],
|
|
26
|
+
): SlashCommand[] {
|
|
27
|
+
const query = slashQuery(input);
|
|
28
|
+
if (query === null) return [];
|
|
29
|
+
const prefix = query.toLowerCase();
|
|
30
|
+
const matches = commands.filter((cmd) => cmd.name.startsWith(prefix));
|
|
31
|
+
if (matches.length === 1 && prefix !== '' && matches[0]!.name === prefix) {
|
|
32
|
+
return [];
|
|
33
|
+
}
|
|
34
|
+
return matches;
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
/** Replaces the slash token with the selected command (plus a space for args). */
|
|
38
|
+
export function applySlashCompletion(input: string, name: string): string {
|
|
39
|
+
if (slashQuery(input) === null) return input;
|
|
40
|
+
return `/${name} `;
|
|
41
|
+
}
|