@trans-ai/trans-code 0.2.4 → 0.4.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 (39) hide show
  1. package/README.md +68 -17
  2. package/package.json +1 -1
  3. package/src/acp/session.ts +4 -1
  4. package/src/agent/loop.test.ts +337 -1
  5. package/src/agent/loop.ts +166 -2
  6. package/src/agent/system-prompt.test.ts +24 -1
  7. package/src/agent/system-prompt.ts +21 -0
  8. package/src/agent/tools/ask-model.test.ts +54 -0
  9. package/src/agent/tools/ask-model.ts +44 -0
  10. package/src/agent/tools/bash.test.ts +42 -1
  11. package/src/agent/tools/bash.ts +202 -15
  12. package/src/agent/tools/dispatch.test.ts +157 -0
  13. package/src/agent/tools/dispatch.ts +151 -0
  14. package/src/agent/tools/files.test.ts +96 -0
  15. package/src/agent/tools/files.ts +111 -29
  16. package/src/agent/tools/fs-utils.ts +40 -0
  17. package/src/agent/tools/index.ts +29 -2
  18. package/src/agent/tools/powershell.test.ts +61 -0
  19. package/src/agent/tools/read-only.ts +16 -0
  20. package/src/agent/tools/search.test.ts +55 -1
  21. package/src/agent/tools/search.ts +56 -8
  22. package/src/agent/tools/session.ts +21 -0
  23. package/src/agent/tools/shell-paths.test.ts +65 -0
  24. package/src/agent/tools/shell-paths.ts +19 -0
  25. package/src/agent/tools/todo.test.ts +54 -0
  26. package/src/agent/tools/todo.ts +47 -0
  27. package/src/agent/tools/types.ts +15 -1
  28. package/src/cli.ts +2 -0
  29. package/src/commands.ts +55 -2
  30. package/src/config.ts +21 -3
  31. package/src/main.tsx +4 -4
  32. package/src/provider/model-list.test.ts +65 -0
  33. package/src/provider/provider.test.ts +117 -0
  34. package/src/provider/provider.ts +312 -34
  35. package/src/provider/routing.test.ts +109 -0
  36. package/src/screens/REPL.tsx +432 -35
  37. package/src/sessions/store.test.ts +91 -0
  38. package/src/sessions/store.ts +149 -0
  39. package/src/version.ts +1 -1
@@ -2,10 +2,30 @@ import { Box, Text, useInput, useApp } from 'ink';
2
2
  import { useState, useCallback, useEffect, useMemo, useRef } from 'react';
3
3
  import path from 'node:path';
4
4
  import { findCommand, getCommands, type CommandContext } from '../commands.js';
5
- import { getAvailableModels, createProviderWithKey, createProvider, setPreferredModel, type ModelId } from '../provider/provider.js';
5
+ import {
6
+ getAvailableModels,
7
+ createProvider,
8
+ setPreferredModel,
9
+ registerApiKey,
10
+ lookupApiKey,
11
+ setCustomModel,
12
+ listEndpointModels,
13
+ vendorModelSpec,
14
+ vendorModels,
15
+ verifyModel,
16
+ type ModelId,
17
+ } from '../provider/provider.js';
18
+ import { loadConfig } from '../config.js';
6
19
  import { runAgentLoop, type PermissionRequest } from '../agent/loop.js';
7
20
  import { createToolSession } from '../agent/tools/index.js';
8
21
  import { getPermissionMode } from '../agent/permission.js';
22
+ import {
23
+ generateTitle,
24
+ getSession,
25
+ listSessions,
26
+ saveSession,
27
+ searchSessions,
28
+ } from '../sessions/store.js';
9
29
  import { walkFiles } from '../agent/tools/fs-utils.js';
10
30
  import { applyCompletion, filterFiles, mentionQuery } from './file-completion.js';
11
31
  import { renderDiff } from './diff-render.js';
@@ -18,7 +38,15 @@ interface HistoryEntry {
18
38
  output: string;
19
39
  }
20
40
 
21
- type PromptPhase = 'idle' | 'model_select' | 'model_apikey' | 'permission';
41
+ type PromptPhase =
42
+ | 'idle'
43
+ | 'model_select'
44
+ | 'model_pick'
45
+ | 'model_name'
46
+ | 'custom_baseurl'
47
+ | 'model_apikey'
48
+ | 'model_check'
49
+ | 'permission';
22
50
 
23
51
  interface REPLProps {
24
52
  ctx: CommandContext;
@@ -48,7 +76,23 @@ export default function REPL({ ctx }: REPLProps) {
48
76
  fail: number;
49
77
  } | null>(null);
50
78
  const [pendingModel, setPendingModel] = useState<ModelId | null>(null);
79
+ const pendingModelRef = useRef<ModelId | null>(null);
80
+ const setVendor = (id: ModelId | null) => {
81
+ pendingModelRef.current = id;
82
+ setPendingModel(id);
83
+ };
51
84
  const [modelCursor, setModelCursor] = useState(0);
85
+ // Model selection flow: vendor → model → key (reused if saved) → check.
86
+ const [pickOptions, setPickOptions] = useState<string[]>([]);
87
+ const [pickCursor, setPickCursor] = useState(0);
88
+ const [pickLive, setPickLive] = useState(false);
89
+ const [pickLoading, setPickLoading] = useState(false);
90
+ const vendorModelCache = useRef(new Map<string, string[]>());
91
+ const [pendingSpec, setPendingSpec] = useState<string | null>(null);
92
+ const [pendingDisplayName, setPendingDisplayName] = useState('');
93
+ const [keyHint, setKeyHint] = useState<string | null>(null);
94
+ const [customBaseDraft, setCustomBaseDraft] = useState('');
95
+ const [customKeyDraft, setCustomKeyDraft] = useState('');
52
96
 
53
97
  const models = getAvailableModels();
54
98
  // Bun's scheduler can drop the render flush for updates issued from the
@@ -71,6 +115,10 @@ export default function REPL({ ctx }: REPLProps) {
71
115
  // One tool session per process: bash cwd and read-file state persist
72
116
  // across prompts, like the ACP session.
73
117
  const toolSessionRef = useRef(createToolSession(process.cwd()));
118
+ // Conversation persistence: lazily created record + model-generated title.
119
+ const conversationRef = useRef<{ id: string; createdAt: number; titled: boolean } | null>(null);
120
+ const conversationTitleRef = useRef('');
121
+ const lastSessionsRef = useRef<string[]>([]);
74
122
 
75
123
  // @-mention file completion: lazy file list, active query, dismissed flag.
76
124
  const [fileList, setFileList] = useState<string[] | null>(null);
@@ -149,11 +197,14 @@ export default function REPL({ ctx }: REPLProps) {
149
197
  );
150
198
 
151
199
  const runChat = useCallback(
152
- async (text: string, display?: string) => {
200
+ async (text: string, display?: string, options?: { planMode?: boolean }) => {
153
201
  setBusyBoth(true);
154
202
  const controller = new AbortController();
155
203
  abortRef.current = controller;
156
204
  addHistory({ input: display ?? text, output: '' });
205
+ if (options?.planMode) {
206
+ appendChatOutput('[plan 模式:只读探索,产出方案,PLAN READY 后可让我执行]\n');
207
+ }
157
208
 
158
209
  try {
159
210
  const provider =
@@ -174,6 +225,7 @@ export default function REPL({ ctx }: REPLProps) {
174
225
  messagesRef.current.push(new HumanMessage(text));
175
226
 
176
227
  let lastWasTool = false;
228
+ let turnAssistantText = '';
177
229
  const stats = createTurnStats();
178
230
  const titlesById = new Map<string, string>();
179
231
  const bufferedLines: string[] = [];
@@ -182,12 +234,16 @@ export default function REPL({ ctx }: REPLProps) {
182
234
  model: provider?.model,
183
235
  cwd: process.cwd(),
184
236
  messages: messagesRef.current,
185
- systemPrompt,
237
+ systemPrompt: options?.planMode
238
+ ? `${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.`
239
+ : systemPrompt,
240
+ planMode: options?.planMode === true,
186
241
  signal: controller.signal,
187
242
  toolSession: toolSessionRef.current,
188
243
  onEvent: event => {
189
244
  if (event.type === 'text') {
190
245
  appendChatOutput(lastWasTool ? `\n${event.text}` : event.text);
246
+ turnAssistantText += event.text;
191
247
  lastWasTool = false;
192
248
  } else if (event.type === 'max_turns_reached') {
193
249
  appendChatOutput(
@@ -209,6 +265,9 @@ export default function REPL({ ctx }: REPLProps) {
209
265
  if (event.diff) {
210
266
  // Edits and writes stay visible immediately — rare and important.
211
267
  appendChatOutput(`\n⚙ ${title} ${marker}\n${renderDiff(event.diff)}`);
268
+ } else if (event.name === 'todo_write' || event.name === 'dispatch_agent') {
269
+ // Progress state and sub-agent reports: show immediately.
270
+ appendChatOutput(`\n${event.output}`);
212
271
  } else {
213
272
  bufferedLines.push(`\n⚙ ${title} ${marker}`);
214
273
  }
@@ -227,6 +286,44 @@ export default function REPL({ ctx }: REPLProps) {
227
286
  }
228
287
 
229
288
  messagesRef.current = result.messages;
289
+
290
+ // Persist the conversation for /sessions and /resume.
291
+ if (!conversationRef.current) {
292
+ conversationRef.current = {
293
+ id: `ses_${Date.now().toString(36)}_${Math.random().toString(36).slice(2, 6)}`,
294
+ createdAt: Date.now(),
295
+ titled: false,
296
+ };
297
+ conversationTitleRef.current = text.replace(/\s+/g, ' ').trim().slice(0, 24) || '新对话';
298
+ }
299
+ const conversation = conversationRef.current;
300
+ const persist = () =>
301
+ saveSession({
302
+ id: conversation.id,
303
+ title: conversationTitleRef.current,
304
+ createdAt: conversation.createdAt,
305
+ updatedAt: Date.now(),
306
+ cwd: process.cwd(),
307
+ model: ctx.modelId,
308
+ messages: messagesRef.current,
309
+ });
310
+ persist();
311
+ if (!conversation.titled && provider) {
312
+ conversation.titled = true;
313
+ const firstUserText = text;
314
+ void (async () => {
315
+ try {
316
+ conversationTitleRef.current = await generateTitle(
317
+ provider.model,
318
+ firstUserText,
319
+ turnAssistantText,
320
+ );
321
+ } catch {
322
+ // keep the derived fallback title
323
+ }
324
+ persist();
325
+ })();
326
+ }
230
327
  if (controller.signal.aborted) appendChatOutput('\n(cancelled)');
231
328
  } catch (error) {
232
329
  const message = error instanceof Error ? error.message : String(error);
@@ -252,36 +349,146 @@ export default function REPL({ ctx }: REPLProps) {
252
349
  setPhase('model_select');
253
350
  }, [ctx.modelId, models]);
254
351
 
255
- const handleApiKey = useCallback((value: string) => {
256
- const apiKey = value.trim();
257
- const modelId = pendingModel!;
352
+ const maskKey = (key: string): string =>
353
+ key.length <= 8 ? '…****' : `${key.slice(0, 3)}…${key.slice(-4)}`;
258
354
 
259
- if (!apiKey) {
260
- addHistory({ input: '••••••••', output: 'API key cannot be empty.' });
261
- enterModelSelect();
262
- return;
263
- }
355
+ const beginKeyStep = useCallback(
356
+ (spec: string, displayName: string) => {
357
+ const saved = lookupApiKey(spec);
358
+ setPendingSpec(spec);
359
+ setPendingDisplayName(displayName);
360
+ setKeyHint(saved ? maskKey(saved) : null);
361
+ setPhase('model_apikey');
362
+ commitInput('');
363
+ },
364
+ [commitInput],
365
+ );
264
366
 
265
- try {
266
- createProviderWithKey(modelId, apiKey);
267
- ctx.setModelId(modelId);
268
- setPreferredModel(modelId);
269
- const found = models.find(m => m.id === modelId);
270
- addHistory({ input: '••••••••', output: `Switched to ${found?.name ?? modelId}` });
271
- } catch {
272
- addHistory({ input: '••••••••', output: 'Failed to switch model. Invalid API key.' });
273
- }
367
+ const applyModelSwitch = useCallback(
368
+ (spec: string, displayName: string, apiKey: string, checkMessage: string) => {
369
+ registerApiKey(spec.split(':')[0]!, apiKey);
370
+ ctx.setModelId(spec);
371
+ setPreferredModel(spec);
372
+ addHistory({
373
+ input: '••••••••',
374
+ output: `${checkMessage} — 已切换到 ${displayName}`,
375
+ });
376
+ setPendingSpec(null);
377
+ setPendingDisplayName('');
378
+ setKeyHint(null);
379
+ setCustomBaseDraft('');
380
+ setCustomKeyDraft('');
381
+ setVendor(null);
382
+ setPhase('idle');
383
+ dragFlush();
384
+ },
385
+ [ctx, addHistory, dragFlush],
386
+ );
387
+
388
+ /** Verify a selection and apply it, or surface the error and re-prompt. */
389
+ const finalizeSelection = useCallback(
390
+ async (spec: string, displayName: string, apiKey: string) => {
391
+ if (process.env.TRANSCODE_SKIP_MODEL_CHECK === '1') {
392
+ applyModelSwitch(spec, displayName, apiKey, '已跳过连通性测试');
393
+ return;
394
+ }
395
+ setPhase('model_check');
396
+ const result = await verifyModel(spec, apiKey);
397
+ if (result.ok) {
398
+ applyModelSwitch(spec, displayName, apiKey, `✓ ${result.message}`);
399
+ return;
400
+ }
401
+ addHistory({
402
+ input: '••••••••',
403
+ output: `✗ 连通失败:${result.message}\n请重新输入 key(Esc 返回模型列表)`,
404
+ });
405
+ setPhase('model_apikey');
406
+ commitInput('');
407
+ dragFlush();
408
+ },
409
+ [applyModelSwitch, addHistory, commitInput, dragFlush],
410
+ );
411
+
412
+ const handleApiKey = useCallback(
413
+ async (value: string) => {
414
+ // Custom-gateway setup: collect the key, then pick the model from the
415
+ // gateway's live list instead of asking for a blind model name.
416
+ if (pendingSpec === null && pendingModel === null && customBaseDraft) {
417
+ const apiKey = value.trim() || lookupApiKey('custom');
418
+ if (!apiKey) {
419
+ addHistory({ input: '••••••••', output: 'API key 不能为空。' });
420
+ return;
421
+ }
422
+ setCustomKeyDraft(apiKey);
423
+ setPickOptions([]);
424
+ setPickCursor(0);
425
+ setPickLive(false);
426
+ setPhase('model_pick');
427
+ commitInput('');
428
+ setPickLoading(true);
429
+ const live = await listEndpointModels('', { baseUrl: customBaseDraft, apiKey });
430
+ setPickOptions(live);
431
+ setPickLive(live.length > 0);
432
+ setPickLoading(false);
433
+ dragFlush();
434
+ return;
435
+ }
436
+
437
+ const spec = pendingSpec!;
438
+ const savedKey = lookupApiKey(spec);
439
+ const apiKey = value.trim() || savedKey;
440
+
441
+ if (!apiKey) {
442
+ addHistory({ input: '••••••••', output: 'API key 不能为空。' });
443
+ return; // stay on the key prompt
444
+ }
274
445
 
275
- setPendingModel(null);
276
- setPhase('idle');
277
- }, [pendingModel, ctx, addHistory, enterModelSelect, models]);
446
+ await finalizeSelection(spec, pendingDisplayName, apiKey);
447
+ },
448
+ [
449
+ pendingSpec,
450
+ pendingModel,
451
+ pendingDisplayName,
452
+ customBaseDraft,
453
+ addHistory,
454
+ finalizeSelection,
455
+ commitInput,
456
+ dragFlush,
457
+ ],
458
+ );
278
459
 
279
460
  const handleSubmit = useCallback(async (raw: string) => {
280
461
  const trimmed = raw.trim();
281
462
  if (!trimmed) return;
282
463
 
283
- if (phase === 'model_apikey') {
284
- handleApiKey(trimmed);
464
+ if (phase === 'model_apikey' || phase === 'model_check') {
465
+ await handleApiKey(trimmed);
466
+ commitInput('');
467
+ return;
468
+ }
469
+
470
+ if (phase === 'custom_baseurl') {
471
+ if (!/^https?:\/\//.test(trimmed)) {
472
+ addHistory({ input: trimmed, output: '地址需以 http:// 或 https:// 开头。' });
473
+ return;
474
+ }
475
+ setCustomBaseDraft(trimmed);
476
+ setKeyHint(lookupApiKey('custom') ? maskKey(lookupApiKey('custom')!) : null);
477
+ setPendingSpec(null);
478
+ setPhase('model_apikey');
479
+ commitInput('');
480
+ return;
481
+ }
482
+
483
+ if (phase === 'model_name') {
484
+ if (!trimmed) return;
485
+ if (pendingModel === null) {
486
+ // Custom gateway, free-text model name (live list was empty/unreachable).
487
+ setCustomModel({ baseUrl: customBaseDraft, model: trimmed });
488
+ await finalizeSelection('custom', `custom/${trimmed}`, customKeyDraft);
489
+ } else {
490
+ beginKeyStep(vendorModelSpec(pendingModel, trimmed), `${pendingModel}/${trimmed}`);
491
+ }
285
492
  commitInput('');
286
493
  return;
287
494
  }
@@ -299,6 +506,91 @@ export default function REPL({ ctx }: REPLProps) {
299
506
  return;
300
507
  }
301
508
 
509
+ if (cmdName === 'new') {
510
+ conversationRef.current = null;
511
+ conversationTitleRef.current = '';
512
+ messagesRef.current = [];
513
+ toolSessionRef.current = createToolSession(process.cwd());
514
+ addHistory({ input: trimmed, output: '已开始新对话。' });
515
+ commitInput('');
516
+ setHistoryIndex(-1);
517
+ setSavedInput('');
518
+ dragFlush();
519
+ return;
520
+ }
521
+
522
+ if (cmdName === 'sessions') {
523
+ const keyword = args.join(' ');
524
+ const found = keyword.trim() ? searchSessions(keyword) : listSessions();
525
+ lastSessionsRef.current = found.map((session) => session.id);
526
+ const lines = found
527
+ .slice(0, 20)
528
+ .map(
529
+ (session, index) =>
530
+ `${index + 1}. ${session.title} · ${new Date(session.updatedAt).toLocaleString()} · ` +
531
+ `${session.model} · ${session.messages.length} 条`,
532
+ );
533
+ addHistory({
534
+ input: trimmed,
535
+ output: found.length
536
+ ? `${keyword.trim() ? `匹配“${keyword}”` : ''}${found.length} 个对话:\n${lines.join('\n')}\n/resume <序号|id|标题片段> 恢复`
537
+ : keyword.trim()
538
+ ? `没有匹配“${keyword}”的对话。`
539
+ : '暂无历史对话。',
540
+ });
541
+ commitInput('');
542
+ setHistoryIndex(-1);
543
+ setSavedInput('');
544
+ dragFlush();
545
+ return;
546
+ }
547
+
548
+ if (cmdName === 'resume') {
549
+ const target = args.join(' ').trim();
550
+ const list = listSessions();
551
+ let record = undefined as ReturnType<typeof getSession>;
552
+ if (/^\d+$/.test(target)) {
553
+ const indexed = lastSessionsRef.current[Number(target) - 1];
554
+ record = (indexed ? getSession(indexed) : undefined) ?? list[Number(target) - 1];
555
+ } else if (target) {
556
+ record = getSession(target) ?? list.find(
557
+ (session) => session.id.includes(target) || session.title.includes(target),
558
+ );
559
+ }
560
+ if (!record) {
561
+ addHistory({ input: trimmed, output: `未找到对话“${target || '(空)'}”。先 /sessions 查看列表。` });
562
+ } else {
563
+ conversationRef.current = { id: record.id, createdAt: record.createdAt, titled: true };
564
+ conversationTitleRef.current = record.title;
565
+ messagesRef.current = record.messages;
566
+ toolSessionRef.current = createToolSession(process.cwd());
567
+ addHistory({
568
+ input: trimmed,
569
+ output: `已恢复「${record.title}」(${record.messages.length} 条消息,${record.model}),继续对话。`,
570
+ });
571
+ }
572
+ commitInput('');
573
+ setHistoryIndex(-1);
574
+ setSavedInput('');
575
+ dragFlush();
576
+ return;
577
+ }
578
+
579
+ if (cmdName === 'plan') {
580
+ const task = stripped.startsWith('/plan') ? stripped.slice(5).trim() : stripped;
581
+ if (!task) {
582
+ addHistory({ input: trimmed, output: '用法:/plan <任务描述> — 只读探索并产出实施方案(PLAN READY),确认后再执行' });
583
+ dragFlush();
584
+ commitInput('');
585
+ return;
586
+ }
587
+ commitInput('');
588
+ setHistoryIndex(-1);
589
+ setSavedInput('');
590
+ await runChat(task, trimmed, { planMode: true });
591
+ return;
592
+ }
593
+
302
594
  if (cmdName === 'init') {
303
595
  commitInput('');
304
596
  setHistoryIndex(-1);
@@ -359,7 +651,7 @@ export default function REPL({ ctx }: REPLProps) {
359
651
  }
360
652
  if (phase !== 'idle') {
361
653
  setPhase('idle');
362
- setPendingModel(null);
654
+ setVendor(null);
363
655
  commitInput('');
364
656
  addHistory({ input: '', output: 'Cancelled.' });
365
657
  return;
@@ -383,9 +675,46 @@ export default function REPL({ ctx }: REPLProps) {
383
675
  if (phase === 'model_select') {
384
676
  if (key.return) {
385
677
  const selected = models[modelCursor];
386
- setPendingModel(selected.id);
387
- setPhase('model_apikey');
678
+ if (selected.id === 'custom') {
679
+ const saved = loadConfig().custom;
680
+ setVendor(null);
681
+ if (saved?.baseUrl && saved.model) {
682
+ beginKeyStep('custom', `custom/${saved.model}`);
683
+ } else {
684
+ setPhase('custom_baseurl');
685
+ commitInput('');
686
+ }
687
+ return;
688
+ }
689
+ setVendor(selected.id);
690
+ setPickOptions(vendorModels(selected.id));
691
+ setPickCursor(0);
692
+ setPickLive(false);
693
+ setPhase('model_pick');
388
694
  commitInput('');
695
+
696
+ // Prefer the endpoint's live model list (what it actually serves)
697
+ // over the curated fallback; cache per vendor for this process.
698
+ const vendor = selected.id;
699
+ const cached = vendorModelCache.current.get(vendor);
700
+ if (cached) {
701
+ if (cached.length > 0) {
702
+ setPickOptions(cached);
703
+ setPickLive(true);
704
+ }
705
+ } else {
706
+ setPickLoading(true);
707
+ void listEndpointModels(vendor)
708
+ .then((live) => {
709
+ vendorModelCache.current.set(vendor, live);
710
+ if (live.length > 0 && pendingModelRef.current === vendor) {
711
+ setPickOptions(live);
712
+ setPickCursor(0);
713
+ setPickLive(true);
714
+ }
715
+ })
716
+ .finally(() => setPickLoading(false));
717
+ }
389
718
  return;
390
719
  }
391
720
  if (key.upArrow) {
@@ -399,6 +728,36 @@ export default function REPL({ ctx }: REPLProps) {
399
728
  return;
400
729
  }
401
730
 
731
+ if (phase === 'model_pick') {
732
+ const total = pickOptions.length + 1; // + "自定义模型名…"
733
+ if (key.return) {
734
+ if (pickCursor >= pickOptions.length) {
735
+ setPhase('model_name');
736
+ commitInput('');
737
+ return;
738
+ }
739
+ const modelName = pickOptions[pickCursor]!;
740
+ if (pendingModel === null && customBaseDraft) {
741
+ // Custom gateway: model chosen from the live list.
742
+ setCustomModel({ baseUrl: customBaseDraft, model: modelName });
743
+ void finalizeSelection('custom', `custom/${modelName}`, customKeyDraft);
744
+ } else {
745
+ beginKeyStep(vendorModelSpec(pendingModel!, modelName), `${pendingModel}/${modelName}`);
746
+ }
747
+ commitInput('');
748
+ return;
749
+ }
750
+ if (key.upArrow) {
751
+ setPickCursor(prev => (prev - 1 + total) % total);
752
+ return;
753
+ }
754
+ if (key.downArrow) {
755
+ setPickCursor(prev => (prev + 1) % total);
756
+ return;
757
+ }
758
+ return;
759
+ }
760
+
402
761
  // @-mention popup navigation and completion (takes precedence over
403
762
  // history navigation, tab completion and submission).
404
763
  if (phase === 'idle' && mentionActive && mentionCandidates.length > 0) {
@@ -475,12 +834,18 @@ export default function REPL({ ctx }: REPLProps) {
475
834
  });
476
835
 
477
836
  const promptLabel = phase === 'model_select'
478
- ? 'model> '
479
- : phase === 'model_apikey'
480
- ? 'apikey> '
481
- : phase === 'permission'
482
- ? 'allow?> '
483
- : '> ';
837
+ ? 'vendor> '
838
+ : phase === 'model_pick'
839
+ ? 'model> '
840
+ : phase === 'model_name'
841
+ ? pendingModel === null ? '自定义模型名> ' : '自定义模型名> '
842
+ : phase === 'custom_baseurl'
843
+ ? 'baseurl> '
844
+ : phase === 'model_apikey'
845
+ ? keyHint ? `apikey (回车沿用 ${keyHint})> ` : 'apikey> '
846
+ : phase === 'permission'
847
+ ? 'allow?> '
848
+ : '> ';
484
849
 
485
850
  return (
486
851
  <Box flexDirection="column" paddingX={1}>
@@ -534,6 +899,38 @@ export default function REPL({ ctx }: REPLProps) {
534
899
  )}
535
900
  </Box>
536
901
  ))}
902
+ <Text color="gray" dimColor>↑↓ 选择厂商 · Enter 进入模型列表</Text>
903
+ </Box>
904
+ )}
905
+
906
+ {phase === 'model_pick' && (
907
+ <Box flexDirection="column" marginLeft={2}>
908
+ {pendingModel === null && customBaseDraft && (
909
+ <Text color="gray" dimColor>自定义网关 {customBaseDraft} 的模型:</Text>
910
+ )}
911
+ {pickOptions.map((name, i) => (
912
+ <Box key={name}>
913
+ <Text color={i === pickCursor ? 'cyan' : undefined}>
914
+ {i === pickCursor ? '❯ ' : ' '}
915
+ {name}
916
+ </Text>
917
+ </Box>
918
+ ))}
919
+ <Box>
920
+ <Text color={pickCursor === pickOptions.length ? 'cyan' : 'gray'}>
921
+ {pickCursor === pickOptions.length ? '❯ ' : ' '}
922
+ 自定义模型名…
923
+ </Text>
924
+ </Box>
925
+ {pickLoading && <Text color="gray" dimColor>… 正在从网关获取实时模型列表</Text>}
926
+ {!pickLoading && pickLive && <Text color="gray" dimColor>(网关实时列表)</Text>}
927
+ <Text color="gray" dimColor>↑↓ 选择模型 · Enter 确认</Text>
928
+ </Box>
929
+ )}
930
+
931
+ {phase === 'model_check' && (
932
+ <Box marginLeft={2}>
933
+ <Text dimColor>… 测试连通性({pendingDisplayName})</Text>
537
934
  </Box>
538
935
  )}
539
936
 
@@ -0,0 +1,91 @@
1
+ import { afterEach, beforeEach, describe, expect, test } from 'bun:test';
2
+ import { mkdtempSync, rmSync } from 'node:fs';
3
+ import { tmpdir } from 'node:os';
4
+ import path from 'node:path';
5
+ import { AIMessage, HumanMessage, SystemMessage, ToolMessage } from '@langchain/core/messages';
6
+ import {
7
+ getSession,
8
+ listSessions,
9
+ saveSession,
10
+ searchSessions,
11
+ type SessionRecord,
12
+ } from './store.js';
13
+
14
+ let dir: string;
15
+ beforeEach(() => {
16
+ dir = mkdtempSync(path.join(tmpdir(), 'transcode-sessions-test-'));
17
+ process.env.TRANSCODE_SESSIONS_DIR = dir;
18
+ });
19
+ afterEach(() => {
20
+ delete process.env.TRANSCODE_SESSIONS_DIR;
21
+ rmSync(dir, { recursive: true, force: true });
22
+ });
23
+
24
+ function sample(title: string, body: string): SessionRecord {
25
+ return {
26
+ id: 'ses_test1',
27
+ title,
28
+ createdAt: Date.now(),
29
+ updatedAt: Date.now(),
30
+ cwd: '/tmp',
31
+ model: 'deepseek',
32
+ messages: [
33
+ new SystemMessage('system prompt'),
34
+ new HumanMessage(body),
35
+ new AIMessage({
36
+ content: '好的',
37
+ tool_calls: [{ id: 'call_1', name: 'bash', args: { command: 'ls' } }],
38
+ }),
39
+ new ToolMessage({ content: 'file-a file-b', tool_call_id: 'call_1', name: 'bash' }),
40
+ new AIMessage('完成'),
41
+ ],
42
+ };
43
+ }
44
+
45
+ describe('session store', () => {
46
+ test('save + list roundtrips with metadata', () => {
47
+ saveSession(sample('更新 README', '帮我更新这个仓库的 README'));
48
+
49
+ const listed = listSessions();
50
+ expect(listed.length).toBe(1);
51
+ expect(listed[0]!.title).toBe('更新 README');
52
+ expect(listed[0]!.model).toBe('deepseek');
53
+ });
54
+
55
+ test('messages survive serialization with tool calls intact', () => {
56
+ saveSession(sample('更新 README', '帮我更新 README'));
57
+
58
+ const loaded = getSession('ses_test1');
59
+ expect(loaded).toBeDefined();
60
+ const messages = loaded!.messages;
61
+ expect(messages[0]!.getType()).toBe('system');
62
+ expect(messages[1]!.content).toBe('帮我更新 README');
63
+ const ai = messages[2] as AIMessage;
64
+ expect(ai.tool_calls?.[0]?.name).toBe('bash');
65
+ const tool = messages[3] as ToolMessage;
66
+ expect(tool.tool_call_id).toBe('call_1');
67
+ expect(tool.content).toBe('file-a file-b');
68
+ });
69
+
70
+ test('search matches titles and message content, case-insensitive', () => {
71
+ saveSession(sample('部署脚本调整', '帮我看看部署'));
72
+ saveSession({ ...sample('无关对话', '今天天气如何'), id: 'ses_test2' });
73
+
74
+ const byTitle = searchSessions('部署');
75
+ expect(byTitle.map((s) => s.id)).toEqual(['ses_test1']);
76
+
77
+ const byBody = searchSessions('天气');
78
+ expect(byBody.map((s) => s.id)).toEqual(['ses_test2']);
79
+ });
80
+
81
+ test('list is ordered newest first', () => {
82
+ const older = sample('旧对话', 'a');
83
+ older.createdAt = Date.now() - 10_000;
84
+ older.updatedAt = Date.now() - 10_000;
85
+ older.id = 'ses_old';
86
+ saveSession(older);
87
+ saveSession(sample('新对话', 'b'));
88
+
89
+ expect(listSessions()[0]!.id).toBe('ses_test1');
90
+ });
91
+ });