@trans-ai/trans-code 0.9.0 → 0.10.1

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.
@@ -1,7 +1,7 @@
1
1
  import { Box, Text, useInput, useApp, useStdout } from 'ink';
2
2
  import { useState, useCallback, useEffect, useMemo, useRef } from 'react';
3
3
  import path from 'node:path';
4
- import { findCommand, getCommands, type CommandContext } from '../commands.js';
4
+ import { executeCommand, findCommand, getCommands, type CommandContext } from '../commands.js';
5
5
  import {
6
6
  getAvailableModels,
7
7
  createModel,
@@ -18,9 +18,16 @@ import {
18
18
  type ModelId,
19
19
  } from '../provider/provider.js';
20
20
  import { loadConfig, normalizeAutoCompact } from '../config.js';
21
+ import {
22
+ checkWebSearch,
23
+ normalizeWebSearchConfig,
24
+ saveWebSearchConfig,
25
+ webSearchConfigWarning,
26
+ type WebSearchConfig,
27
+ } from '../provider/web-search.js';
21
28
  import { runAgentLoop, type PermissionRequest } from '../agent/loop.js';
22
29
  import { createToolSession } from '../agent/tools/index.js';
23
- import { getPermissionMode } from '../agent/permission.js';
30
+ import { getPermissionMode, nextPermissionMode, setPermissionMode } from '../agent/permission.js';
24
31
  import {
25
32
  buildSessionRecord,
26
33
  generateTitle,
@@ -40,6 +47,7 @@ import {
40
47
  slashQuery,
41
48
  } from './slash-completion.js';
42
49
  import { resolveSubmitInput } from './submit.js';
50
+ import { submitSearchApiKey } from './search-setup.js';
43
51
  import { historyRule } from './history-rule.js';
44
52
  import { renderDiff } from './diff-render.js';
45
53
  import { createTurnStats, recordCall, shouldCollapse, summaryLine } from './turn-summary.js';
@@ -61,7 +69,13 @@ type PromptPhase =
61
69
  | 'model_apikey'
62
70
  | 'model_check'
63
71
  | 'permission'
64
- | 'session_select';
72
+ | 'session_select'
73
+ | 'search_provider'
74
+ | 'search_apikey'
75
+ | 'search_check';
76
+
77
+ /** Providers offered by the /search setup flow (mirrors normalizeWebSearchConfig). */
78
+ const SEARCH_PROVIDERS: WebSearchConfig['provider'][] = ['tavily', 'brave'];
65
79
 
66
80
  interface REPLProps {
67
81
  ctx: CommandContext;
@@ -100,6 +114,12 @@ export default function REPL({ ctx, updateNotice }: REPLProps) {
100
114
  setPendingModel(id);
101
115
  };
102
116
  const [modelCursor, setModelCursor] = useState(0);
117
+ // /search setup flow: cursor over SEARCH_PROVIDERS, ref carries the pick.
118
+ const [searchCursor, setSearchCursor] = useState(0);
119
+ const searchProviderRef = useRef<WebSearchConfig['provider']>('tavily');
120
+ // Generation guard: bumping invalidates an in-flight connectivity check,
121
+ // so a cancelled /search never writes config or yanks the phase back.
122
+ const searchRunIdRef = useRef(0);
103
123
  // session_select picker: cursor over the project-scoped session snapshot.
104
124
  const [sessionCursor, setSessionCursor] = useState(0);
105
125
  // Model selection flow: vendor → model → key (reused if saved) → check.
@@ -231,6 +251,16 @@ export default function REPL({ ctx, updateNotice }: REPLProps) {
231
251
  cancelled = true;
232
252
  };
233
253
  }, [updateNotice, addHistory, dragFlush]);
254
+ // Web search misconfiguration: one line on startup; a simply-absent
255
+ // section stays silent (never nags unconfigured users).
256
+ useEffect(() => {
257
+ const warning = webSearchConfigWarning(loadConfig().webSearch);
258
+ if (warning) {
259
+ addHistory({ input: '', output: warning });
260
+ dragFlush();
261
+ }
262
+ // eslint-disable-next-line react-hooks/exhaustive-deps
263
+ }, []);
234
264
  const pendingPermissionRef = useRef<{
235
265
  request: PermissionRequest;
236
266
  resolve: (allow: boolean) => void;
@@ -625,6 +655,25 @@ export default function REPL({ ctx, updateNotice }: REPLProps) {
625
655
  [applyModelSwitch, addHistory, commitInput, dragFlush],
626
656
  );
627
657
 
658
+ // /search key step: orchestration lives in search-setup.ts (tested there).
659
+ const handleSearchApiKey = useCallback(
660
+ async (value: string) => {
661
+ const runId = ++searchRunIdRef.current;
662
+ const provider = searchProviderRef.current;
663
+ setPhase('search_check');
664
+ await submitSearchApiKey(value, provider, {
665
+ savedConfig: () => normalizeWebSearchConfig(loadConfig().webSearch),
666
+ check: (cfg) => checkWebSearch(cfg),
667
+ save: saveWebSearchConfig,
668
+ notify: (output) => addHistory({ input: '••••••••', output }),
669
+ onOutcome: (phase) => setPhase(phase),
670
+ isStale: () => searchRunIdRef.current !== runId,
671
+ });
672
+ dragFlush();
673
+ },
674
+ [addHistory, dragFlush],
675
+ );
676
+
628
677
  const handleApiKey = useCallback(
629
678
  async (value: string) => {
630
679
  // Key-first vendor setup: the key unlocks the live model list before
@@ -715,6 +764,14 @@ export default function REPL({ ctx, updateNotice }: REPLProps) {
715
764
  return;
716
765
  }
717
766
 
767
+ if (phase === 'search_apikey') {
768
+ await handleSearchApiKey(trimmed);
769
+ commitInput('');
770
+ return;
771
+ }
772
+
773
+ if (phase === 'search_check') return;
774
+
718
775
  if (phase === 'custom_baseurl') {
719
776
  if (!/^https?:\/\//.test(trimmed)) {
720
777
  addHistory({ input: trimmed, output: '地址需以 http:// 或 https:// 开头。' });
@@ -754,6 +811,15 @@ export default function REPL({ ctx, updateNotice }: REPLProps) {
754
811
  return;
755
812
  }
756
813
 
814
+ if (cmdName === 'search') {
815
+ addHistory({ input: trimmed, output: 'Select a search provider (↑↓ to navigate, Enter to select):' });
816
+ setSearchCursor(0);
817
+ setPhase('search_provider');
818
+ commitInput('');
819
+ dragFlush();
820
+ return;
821
+ }
822
+
757
823
  if (cmdName === 'new') {
758
824
  conversationRef.current = null;
759
825
  conversationTitleRef.current = '';
@@ -911,7 +977,7 @@ export default function REPL({ ctx, updateNotice }: REPLProps) {
911
977
  const cmd = findCommand(cmdName);
912
978
 
913
979
  if (cmd) {
914
- const result = await cmd.execute(args, ctx);
980
+ const result = await executeCommand(cmd, args, ctx);
915
981
 
916
982
  if (result.exit) {
917
983
  exit();
@@ -966,6 +1032,9 @@ export default function REPL({ ctx, updateNotice }: REPLProps) {
966
1032
  return;
967
1033
  }
968
1034
  if (phase !== 'idle') {
1035
+ // Invalidate any in-flight /search connectivity check: its late
1036
+ // result must not write config or pull the user back into the flow.
1037
+ searchRunIdRef.current++;
969
1038
  setPhase('idle');
970
1039
  setVendor(null);
971
1040
  commitInput('');
@@ -988,6 +1057,28 @@ export default function REPL({ ctx, updateNotice }: REPLProps) {
988
1057
  return;
989
1058
  }
990
1059
 
1060
+ if (phase === 'search_provider') {
1061
+ if (key.upArrow) {
1062
+ setSearchCursor((c) => (c - 1 + SEARCH_PROVIDERS.length) % SEARCH_PROVIDERS.length);
1063
+ return;
1064
+ }
1065
+ if (key.downArrow) {
1066
+ setSearchCursor((c) => (c + 1) % SEARCH_PROVIDERS.length);
1067
+ return;
1068
+ }
1069
+ if (key.return) {
1070
+ const provider = SEARCH_PROVIDERS[searchCursor];
1071
+ searchProviderRef.current = provider;
1072
+ const saved = normalizeWebSearchConfig(loadConfig().webSearch);
1073
+ const hint = saved?.provider === provider ? '(Enter 沿用已存 key)' : '';
1074
+ addHistory({ input: '', output: `搜索商:${provider}。输入 API key ${hint}:` });
1075
+ setPhase('search_apikey');
1076
+ commitInput('');
1077
+ return;
1078
+ }
1079
+ return;
1080
+ }
1081
+
991
1082
  if (phase === 'model_select') {
992
1083
  if (key.return) {
993
1084
  const selected = models[modelCursor];
@@ -1112,6 +1203,16 @@ export default function REPL({ ctx, updateNotice }: REPLProps) {
1112
1203
  return;
1113
1204
  }
1114
1205
 
1206
+ // Shift+Tab cycles permission modes (ask → auto → readonly). Runs FIRST:
1207
+ // ink reports shift+tab as a bare {tab} key (raw input '[Z'), so every
1208
+ // later tab branch (popup completion, slash completion) would misfire.
1209
+ if (key.tab && (ch === '[Z' || key.shift) && phase === 'idle') {
1210
+ const next = nextPermissionMode(getPermissionMode());
1211
+ setPermissionMode(next);
1212
+ addHistory({ input: '', output: `权限模式 → ${next}` });
1213
+ return;
1214
+ }
1215
+
1115
1216
  // @-mention popup navigation and completion (takes precedence over
1116
1217
  // history navigation, tab completion and submission).
1117
1218
  if (phase === 'idle' && mentionActive && mentionCandidates.length > 0) {
@@ -1216,6 +1317,8 @@ export default function REPL({ ctx, updateNotice }: REPLProps) {
1216
1317
  ? keyHint ? `apikey (回车沿用 ${keyHint})> ` : 'apikey> '
1217
1318
  : phase === 'vendor_apikey'
1218
1319
  ? 'apikey> '
1320
+ : phase === 'search_apikey'
1321
+ ? 'search apikey> '
1219
1322
  : phase === 'permission'
1220
1323
  ? 'allow?> '
1221
1324
  : '> ';
@@ -1280,6 +1383,19 @@ export default function REPL({ ctx, updateNotice }: REPLProps) {
1280
1383
  </Box>
1281
1384
  )}
1282
1385
 
1386
+ {phase === 'search_provider' && (
1387
+ <Box flexDirection="column" marginLeft={2}>
1388
+ {SEARCH_PROVIDERS.map((p, i) => (
1389
+ <Box key={p}>
1390
+ <Text color={i === searchCursor ? 'cyan' : undefined}>
1391
+ {i === searchCursor ? '❯ ' : ' '}{p}
1392
+ </Text>
1393
+ </Box>
1394
+ ))}
1395
+ <Text color="gray" dimColor>↑↓ 选择搜索商 · Enter 下一步 · Esc 取消</Text>
1396
+ </Box>
1397
+ )}
1398
+
1283
1399
  {phase === 'session_select' && (
1284
1400
  <Box flexDirection="column" marginLeft={2}>
1285
1401
  <Text color="gray" dimColor>恢复对话 (↑↓ 选择 · Enter 恢复 · Esc 取消)</Text>
@@ -0,0 +1,89 @@
1
+ import { describe, expect, test } from 'bun:test';
2
+ import { submitSearchApiKey } from './search-setup.js';
3
+ import type { WebSearchCheck, WebSearchConfig } from '../provider/web-search.js';
4
+
5
+ interface Captured {
6
+ checked?: WebSearchConfig;
7
+ saved?: { provider: string; apiKey: string };
8
+ outcomes: string[];
9
+ notices: string[];
10
+ stale: boolean;
11
+ }
12
+
13
+ function makeDeps(overrides?: {
14
+ checkResult?: WebSearchCheck;
15
+ saveThrows?: boolean;
16
+ saved?: WebSearchConfig | null;
17
+ }) {
18
+ const cap: Captured = { outcomes: [], notices: [], stale: false };
19
+ return {
20
+ cap,
21
+ deps: {
22
+ savedConfig: () => overrides?.saved ?? null,
23
+ check: async (cfg: WebSearchConfig) => {
24
+ cap.checked = cfg;
25
+ return overrides?.checkResult ?? { ok: true, firstTitle: 'Alive' };
26
+ },
27
+ save: (provider: string, apiKey: string) => {
28
+ if (overrides?.saveThrows) throw new Error('EACCES: disk full');
29
+ cap.saved = { provider, apiKey };
30
+ },
31
+ notify: (output: string) => cap.notices.push(output),
32
+ onOutcome: (phase: 'idle' | 'search_apikey') => cap.outcomes.push(phase),
33
+ isStale: () => cap.stale,
34
+ },
35
+ };
36
+ }
37
+
38
+ describe('submitSearchApiKey', () => {
39
+ test('空输入 + 已存同商 key → 回车沿用 saved key 发起测试', async () => {
40
+ const { cap, deps } = makeDeps({ saved: { provider: 'tavily', apiKey: 'tvly-old' } });
41
+ await submitSearchApiKey('', 'tavily', deps);
42
+ expect(cap.checked).toEqual({ provider: 'tavily', apiKey: 'tvly-old' });
43
+ });
44
+
45
+ test('空输入 + 无已存 → 错误提示,不发起测试,phase 不动', async () => {
46
+ const { cap, deps } = makeDeps();
47
+ await submitSearchApiKey(' ', 'brave', deps);
48
+ expect(cap.checked).toBeUndefined();
49
+ expect(cap.notices[0]).toContain('不能为空');
50
+ expect(cap.outcomes).toEqual([]);
51
+ });
52
+
53
+ test('成功 → 写配置 + 成功提示 + 回 idle', async () => {
54
+ const { cap, deps } = makeDeps();
55
+ await submitSearchApiKey('tvly-new', 'tavily', deps);
56
+ expect(cap.saved).toEqual({ provider: 'tavily', apiKey: 'tvly-new' });
57
+ expect(cap.notices.join('\n')).toContain('已启用');
58
+ expect(cap.outcomes).toEqual(['idle']);
59
+ });
60
+
61
+ test('测试失败 → 不写配置 + 错误提示 + 回 search_apikey 可重输', async () => {
62
+ const { cap, deps } = makeDeps({ checkResult: { ok: false, error: 'brave HTTP 401: bad key' } });
63
+ await submitSearchApiKey('k', 'brave', deps);
64
+ expect(cap.saved).toBeUndefined();
65
+ expect(cap.notices.join('\n')).toContain('401');
66
+ expect(cap.outcomes).toEqual(['search_apikey']);
67
+ });
68
+
69
+ test('Esc 后代次失效(isStale)→ 不写配置、不动 phase、不发迟到的成功消息', async () => {
70
+ const { cap, deps } = makeDeps();
71
+ // Esc fires while the check is in flight: mark stale before completion.
72
+ deps.check = async (cfg: WebSearchConfig) => {
73
+ cap.checked = cfg;
74
+ cap.stale = true;
75
+ return { ok: true, firstTitle: 'late' };
76
+ };
77
+ await submitSearchApiKey('k', 'tavily', deps);
78
+ expect(cap.saved).toBeUndefined();
79
+ expect(cap.outcomes).toEqual([]);
80
+ expect(cap.notices.join('\n')).not.toContain('已启用');
81
+ });
82
+
83
+ test('saveConfig 抛异常 → 错误提示 + 回 search_apikey,不向上抛', async () => {
84
+ const { cap, deps } = makeDeps({ saveThrows: true });
85
+ await submitSearchApiKey('k', 'tavily', deps);
86
+ expect(cap.notices.join('\n')).toContain('EACCES');
87
+ expect(cap.outcomes).toEqual(['search_apikey']);
88
+ });
89
+ });
@@ -0,0 +1,57 @@
1
+ import type { WebSearchCheck, WebSearchConfig } from '../provider/web-search.js';
2
+
3
+ /**
4
+ * /search key-step orchestration, extracted so the flow is testable without
5
+ * the REPL: reuse a saved key on empty input, run a live check, persist only
6
+ * on success, and abandon the outcome entirely when the run went stale
7
+ * (the user pressed Esc while the check was in flight).
8
+ */
9
+
10
+ export interface SearchSetupDeps {
11
+ /** Current persisted config (for the "Enter keeps the saved key" path). */
12
+ savedConfig: () => WebSearchConfig | null;
13
+ /** Live connectivity check (never throws). */
14
+ check: (cfg: WebSearchConfig) => Promise<WebSearchCheck>;
15
+ /** Persist provider+key. */
16
+ save: (provider: WebSearchConfig['provider'], apiKey: string) => void;
17
+ /** Append a message to the chat history. */
18
+ notify: (output: string) => void;
19
+ /** Phase transition after the outcome: idle on success, key prompt on failure. */
20
+ onOutcome: (phase: 'idle' | 'search_apikey') => void;
21
+ /** True when this run was cancelled (Esc) before the check returned. */
22
+ isStale: () => boolean;
23
+ }
24
+
25
+ export async function submitSearchApiKey(
26
+ value: string,
27
+ provider: WebSearchConfig['provider'],
28
+ deps: SearchSetupDeps,
29
+ ): Promise<void> {
30
+ const saved = deps.savedConfig();
31
+ const apiKey = value.trim() || (saved?.provider === provider ? saved.apiKey : '');
32
+ if (!apiKey) {
33
+ deps.notify('API key 不能为空。(Esc 取消)');
34
+ return;
35
+ }
36
+
37
+ deps.notify(`正在测试 ${provider} key…`);
38
+ const result = await deps.check({ provider, apiKey });
39
+ // Esc during the check: write nothing, touch no phase, show no late result.
40
+ if (deps.isStale()) return;
41
+
42
+ if (result.ok) {
43
+ try {
44
+ deps.save(provider, apiKey);
45
+ } catch (error) {
46
+ deps.notify(`✗ 配置写入失败:${error instanceof Error ? error.message : String(error)}\n请重试或手改 ~/.transcode.json`);
47
+ deps.onOutcome('search_apikey');
48
+ return;
49
+ }
50
+ deps.notify(`✓ ${provider} 连通正常(首条结果:${result.firstTitle})。web_search 已启用。`);
51
+ deps.onOutcome('idle');
52
+ return;
53
+ }
54
+
55
+ deps.notify(`✗ 测试失败:${result.error}\n请重新输入 key(Esc 取消)`);
56
+ deps.onOutcome('search_apikey');
57
+ }
@@ -21,3 +21,11 @@ describe('resolveSubmitInput', () => {
21
21
  expect(resolveSubmitInput('idle', 'hello')).toBe('hello');
22
22
  });
23
23
  });
24
+
25
+ describe('search_apikey empty submit', () => {
26
+ test('empty Enter at the search_apikey prompt submits (reuses the saved key)', () => {
27
+ // The /search prompt advertises "(Enter 沿用已存 key)" — a bare Enter
28
+ // must reach the search key handler, which falls back to the saved key.
29
+ expect(resolveSubmitInput('search_apikey', '')).toBe('');
30
+ });
31
+ });
@@ -3,7 +3,7 @@
3
3
  * prompt the hint reads "apikey (回车沿用 sk-…xxxx)> " — a bare Enter means
4
4
  * "reuse the saved key", and handleApiKey falls back to it for empty input.
5
5
  */
6
- const EMPTY_SUBMIT_PHASES = new Set(['model_apikey']);
6
+ const EMPTY_SUBMIT_PHASES = new Set(['model_apikey', 'search_apikey']);
7
7
 
8
8
  /**
9
9
  * Decide whether a submitted line should be dispatched. Returns the trimmed
package/src/version.ts CHANGED
@@ -1,2 +1,2 @@
1
1
  // Auto-generated from package.json by scripts/sync-version.ts (npm version hook)
2
- export const VERSION = '0.9.0';
2
+ export const VERSION = '0.10.1';