@trans-ai/trans-code 0.4.0 → 0.6.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.
@@ -13,6 +13,7 @@ import {
13
13
  vendorModelSpec,
14
14
  vendorModels,
15
15
  verifyModel,
16
+ switchNote,
16
17
  type ModelId,
17
18
  } from '../provider/provider.js';
18
19
  import { loadConfig } from '../config.js';
@@ -28,6 +29,12 @@ import {
28
29
  } from '../sessions/store.js';
29
30
  import { walkFiles } from '../agent/tools/fs-utils.js';
30
31
  import { applyCompletion, filterFiles, mentionQuery } from './file-completion.js';
32
+ import {
33
+ applySlashCompletion,
34
+ filterSlashCommands,
35
+ slashQuery,
36
+ } from './slash-completion.js';
37
+ import { resolveSubmitInput } from './submit.js';
31
38
  import { renderDiff } from './diff-render.js';
32
39
  import { createTurnStats, recordCall, shouldCollapse, summaryLine } from './turn-summary.js';
33
40
  import { buildSystemPrompt, INIT_PROMPT, loadProjectContext } from '../agent/system-prompt.js';
@@ -44,15 +51,18 @@ type PromptPhase =
44
51
  | 'model_pick'
45
52
  | 'model_name'
46
53
  | 'custom_baseurl'
54
+ | 'vendor_apikey'
47
55
  | 'model_apikey'
48
56
  | 'model_check'
49
57
  | 'permission';
50
58
 
51
59
  interface REPLProps {
52
60
  ctx: CommandContext;
61
+ /** Background auto-update outcome; a non-null message shows as a banner. */
62
+ updateNotice?: Promise<string | null>;
53
63
  }
54
64
 
55
- export default function REPL({ ctx }: REPLProps) {
65
+ export default function REPL({ ctx, updateNotice }: REPLProps) {
56
66
  const { exit } = useApp();
57
67
  const [input, setInput] = useState('');
58
68
  // Multiple keystrokes can be handled in one React batch before a
@@ -93,6 +103,8 @@ export default function REPL({ ctx }: REPLProps) {
93
103
  const [keyHint, setKeyHint] = useState<string | null>(null);
94
104
  const [customBaseDraft, setCustomBaseDraft] = useState('');
95
105
  const [customKeyDraft, setCustomKeyDraft] = useState('');
106
+ // Key typed at the vendor step (first-time setup) before any model pick.
107
+ const [vendorKeyDraft, setVendorKeyDraft] = useState('');
96
108
 
97
109
  const models = getAvailableModels();
98
110
  // Bun's scheduler can drop the render flush for updates issued from the
@@ -155,6 +167,38 @@ export default function REPL({ ctx }: REPLProps) {
155
167
  () => (mentionActive && fileList ? filterFiles(fileList, mention ?? '', 8) : []),
156
168
  [mentionActive, fileList, mention],
157
169
  );
170
+
171
+ // Slash-command popup (mirrors the @-mention popup): candidates for the
172
+ // current input, a cursor, and a dismissed flag reset when the query changes.
173
+ const [slashCursor, setSlashCursor] = useState(0);
174
+ const [slashDismissed, setSlashDismissed] = useState(false);
175
+ const slashPrefix = phase === 'idle' && !busy ? slashQuery(input) : null;
176
+ const slashCandidates = useMemo(
177
+ () =>
178
+ slashPrefix !== null && !slashDismissed
179
+ ? filterSlashCommands(input, getCommands())
180
+ : [],
181
+ [slashPrefix, slashDismissed, input],
182
+ );
183
+ useEffect(() => {
184
+ setSlashCursor(0);
185
+ if (slashPrefix === null) setSlashDismissed(false);
186
+ }, [slashPrefix]);
187
+
188
+ // Background auto-update outcome: surface as a history banner once settled.
189
+ useEffect(() => {
190
+ if (!updateNotice) return;
191
+ let cancelled = false;
192
+ void updateNotice.then(message => {
193
+ if (!cancelled && message) {
194
+ addHistory({ input: '', output: message });
195
+ dragFlush();
196
+ }
197
+ });
198
+ return () => {
199
+ cancelled = true;
200
+ };
201
+ }, [updateNotice, addHistory, dragFlush]);
158
202
  const pendingPermissionRef = useRef<{
159
203
  request: PermissionRequest;
160
204
  resolve: (allow: boolean) => void;
@@ -365,19 +409,21 @@ export default function REPL({ ctx }: REPLProps) {
365
409
  );
366
410
 
367
411
  const applyModelSwitch = useCallback(
368
- (spec: string, displayName: string, apiKey: string, checkMessage: string) => {
412
+ (spec: string, displayName: string, apiKey: string, checkMessage: string, served?: string) => {
369
413
  registerApiKey(spec.split(':')[0]!, apiKey);
370
414
  ctx.setModelId(spec);
371
415
  setPreferredModel(spec);
416
+ const pickedModel = spec.split(':').pop() ?? displayName;
372
417
  addHistory({
373
418
  input: '••••••••',
374
- output: `${checkMessage} — 已切换到 ${displayName}`,
419
+ output: `${checkMessage} — ${switchNote(displayName, pickedModel, served)}`,
375
420
  });
376
421
  setPendingSpec(null);
377
422
  setPendingDisplayName('');
378
423
  setKeyHint(null);
379
424
  setCustomBaseDraft('');
380
425
  setCustomKeyDraft('');
426
+ setVendorKeyDraft('');
381
427
  setVendor(null);
382
428
  setPhase('idle');
383
429
  dragFlush();
@@ -395,7 +441,7 @@ export default function REPL({ ctx }: REPLProps) {
395
441
  setPhase('model_check');
396
442
  const result = await verifyModel(spec, apiKey);
397
443
  if (result.ok) {
398
- applyModelSwitch(spec, displayName, apiKey, `✓ ${result.message}`);
444
+ applyModelSwitch(spec, displayName, apiKey, `✓ ${result.message}`, result.served);
399
445
  return;
400
446
  }
401
447
  addHistory({
@@ -411,6 +457,35 @@ export default function REPL({ ctx }: REPLProps) {
411
457
 
412
458
  const handleApiKey = useCallback(
413
459
  async (value: string) => {
460
+ // Key-first vendor setup: the key unlocks the live model list before
461
+ // any model is picked (first-time use — no saved key yet).
462
+ if (phase === 'vendor_apikey') {
463
+ const apiKey = value.trim();
464
+ if (!apiKey) {
465
+ addHistory({ input: '••••••••', output: 'API key 不能为空。' });
466
+ return;
467
+ }
468
+ const vendor = pendingModel!;
469
+ setVendorKeyDraft(apiKey);
470
+ setPhase('model_pick');
471
+ setPickOptions(vendorModels(vendor));
472
+ setPickCursor(0);
473
+ setPickLive(false);
474
+ setPickLoading(true);
475
+ commitInput('');
476
+ const live = await listEndpointModels(vendor, { apiKey });
477
+ if (pendingModelRef.current === vendor) {
478
+ if (live.length > 0) {
479
+ setPickOptions(live);
480
+ setPickCursor(0);
481
+ setPickLive(true);
482
+ }
483
+ setPickLoading(false);
484
+ }
485
+ dragFlush();
486
+ return;
487
+ }
488
+
414
489
  // Custom-gateway setup: collect the key, then pick the model from the
415
490
  // gateway's live list instead of asking for a blind model name.
416
491
  if (pendingSpec === null && pendingModel === null && customBaseDraft) {
@@ -446,22 +521,25 @@ export default function REPL({ ctx }: REPLProps) {
446
521
  await finalizeSelection(spec, pendingDisplayName, apiKey);
447
522
  },
448
523
  [
524
+ phase,
449
525
  pendingSpec,
450
526
  pendingModel,
451
527
  pendingDisplayName,
452
528
  customBaseDraft,
453
529
  addHistory,
454
530
  finalizeSelection,
455
- commitInput,
531
+ commitInput,
456
532
  dragFlush,
457
533
  ],
458
534
  );
459
535
 
460
536
  const handleSubmit = useCallback(async (raw: string) => {
461
- const trimmed = raw.trim();
462
- if (!trimmed) return;
537
+ // Bare Enter is a no-op except at the apikey prompt, where it means
538
+ // "reuse the saved key" (the prompt's 回车沿用 hint).
539
+ const trimmed = resolveSubmitInput(phase, raw);
540
+ if (trimmed === null) return;
463
541
 
464
- if (phase === 'model_apikey' || phase === 'model_check') {
542
+ if (phase === 'vendor_apikey' || phase === 'model_apikey' || phase === 'model_check') {
465
543
  await handleApiKey(trimmed);
466
544
  commitInput('');
467
545
  return;
@@ -643,6 +721,11 @@ export default function REPL({ ctx }: REPLProps) {
643
721
  setMentionDismissed(true);
644
722
  return;
645
723
  }
724
+ // Slash-command popup: same — Esc dismisses instead of exiting.
725
+ if (key.escape && slashCandidates.length > 0) {
726
+ setSlashDismissed(true);
727
+ return;
728
+ }
646
729
  if (key.escape) {
647
730
  // While generating, Esc cancels instead of exiting.
648
731
  if (busyRef.current && abortRef.current) {
@@ -690,6 +773,14 @@ export default function REPL({ ctx }: REPLProps) {
690
773
  setPickOptions(vendorModels(selected.id));
691
774
  setPickCursor(0);
692
775
  setPickLive(false);
776
+ setVendorKeyDraft('');
777
+ // Key-first: without a saved key the live /models call would 401,
778
+ // so ask for the key up front and fetch the real list with it.
779
+ if (!lookupApiKey(selected.id)) {
780
+ setPhase('vendor_apikey');
781
+ commitInput('');
782
+ return;
783
+ }
693
784
  setPhase('model_pick');
694
785
  commitInput('');
695
786
 
@@ -741,6 +832,14 @@ export default function REPL({ ctx }: REPLProps) {
741
832
  // Custom gateway: model chosen from the live list.
742
833
  setCustomModel({ baseUrl: customBaseDraft, model: modelName });
743
834
  void finalizeSelection('custom', `custom/${modelName}`, customKeyDraft);
835
+ } else if (vendorKeyDraft) {
836
+ // Key-first flow: the key was just typed — verify without
837
+ // re-asking for it (applyModelSwitch persists it on success).
838
+ void finalizeSelection(
839
+ vendorModelSpec(pendingModel!, modelName),
840
+ `${pendingModel}/${modelName}`,
841
+ vendorKeyDraft,
842
+ );
744
843
  } else {
745
844
  beginKeyStep(vendorModelSpec(pendingModel!, modelName), `${pendingModel}/${modelName}`);
746
845
  }
@@ -775,6 +874,23 @@ export default function REPL({ ctx }: REPLProps) {
775
874
  }
776
875
  }
777
876
 
877
+ // Slash-command popup: ↑↓ navigate, Tab/Enter complete (takes precedence
878
+ // over history navigation and submission).
879
+ if (phase === 'idle' && slashCandidates.length > 0) {
880
+ if (key.upArrow) {
881
+ setSlashCursor(prev => (prev - 1 + slashCandidates.length) % slashCandidates.length);
882
+ return;
883
+ }
884
+ if (key.downArrow) {
885
+ setSlashCursor(prev => (prev + 1) % slashCandidates.length);
886
+ return;
887
+ }
888
+ if (key.tab || key.return) {
889
+ commitInput(applySlashCompletion(inputRef.current, slashCandidates[slashCursor]!.name));
890
+ return;
891
+ }
892
+ }
893
+
778
894
  if (key.return) {
779
895
  if (busyRef.current) return; // still generating; Esc cancels
780
896
  handleSubmit(inputRef.current);
@@ -843,6 +959,8 @@ export default function REPL({ ctx }: REPLProps) {
843
959
  ? 'baseurl> '
844
960
  : phase === 'model_apikey'
845
961
  ? keyHint ? `apikey (回车沿用 ${keyHint})> ` : 'apikey> '
962
+ : phase === 'vendor_apikey'
963
+ ? 'apikey> '
846
964
  : phase === 'permission'
847
965
  ? 'allow?> '
848
966
  : '> ';
@@ -924,6 +1042,9 @@ export default function REPL({ ctx }: REPLProps) {
924
1042
  </Box>
925
1043
  {pickLoading && <Text color="gray" dimColor>… 正在从网关获取实时模型列表</Text>}
926
1044
  {!pickLoading && pickLive && <Text color="gray" dimColor>(网关实时列表)</Text>}
1045
+ {!pickLoading && !pickLive && (
1046
+ <Text color="gray" dimColor>(本地列表 · 保存 key 后显示线上实时列表)</Text>
1047
+ )}
927
1048
  <Text color="gray" dimColor>↑↓ 选择模型 · Enter 确认</Text>
928
1049
  </Box>
929
1050
  )}
@@ -942,18 +1063,19 @@ export default function REPL({ ctx }: REPLProps) {
942
1063
  </Box>
943
1064
  )}
944
1065
 
945
- {phase === 'idle' && input.startsWith('/') && (() => {
946
- const prefix = input.slice(1).toLowerCase();
947
- const matches = getCommands()
948
- .filter(c => !prefix || c.name.startsWith(prefix))
949
- .map(c => ` /${c.name.padEnd(10)} ${c.description}`);
950
- if (matches.length === 0 || (prefix && matches.length === 1 && matches[0].slice(2, 2 + prefix.length).toLowerCase() === prefix)) return null;
951
- return (
952
- <Box marginLeft={2}>
953
- <Text color="blue" dimColor>{matches.join('\n')}</Text>
954
- </Box>
955
- );
956
- })()}
1066
+ {phase === 'idle' && slashCandidates.length > 0 && (
1067
+ <Box flexDirection="column" marginLeft={2}>
1068
+ {slashCandidates.map((cmd, i) => (
1069
+ <Box key={cmd.name}>
1070
+ <Text color={i === slashCursor ? 'cyan' : 'gray'}>
1071
+ {i === slashCursor ? '❯ ' : ' '}
1072
+ /{cmd.name.padEnd(10)} {cmd.description}
1073
+ </Text>
1074
+ </Box>
1075
+ ))}
1076
+ <Text color="gray" dimColor>↑↓ navigate · tab/enter complete · esc close</Text>
1077
+ </Box>
1078
+ )}
957
1079
 
958
1080
  {phase === 'idle' && !busy && mentionActive && (
959
1081
  <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
+ }
@@ -0,0 +1,23 @@
1
+ import { describe, expect, test } from 'bun:test';
2
+ import { resolveSubmitInput } from './submit.js';
3
+
4
+ describe('resolveSubmitInput', () => {
5
+ test('empty Enter at the apikey prompt submits (reuses the saved key)', () => {
6
+ // The prompt advertises "apikey (回车沿用 sk-…xxxx)> " — a bare Enter
7
+ // must reach handleApiKey, which falls back to the saved key.
8
+ expect(resolveSubmitInput('model_apikey', '')).toBe('');
9
+ });
10
+
11
+ test('empty Enter in every other phase is a no-op', () => {
12
+ expect(resolveSubmitInput('idle', '')).toBeNull();
13
+ expect(resolveSubmitInput('model_name', '')).toBeNull();
14
+ expect(resolveSubmitInput('custom_baseurl', '')).toBeNull();
15
+ expect(resolveSubmitInput('model_select', '')).toBeNull();
16
+ expect(resolveSubmitInput('model_pick', '')).toBeNull();
17
+ });
18
+
19
+ test('non-empty input is trimmed and passed through', () => {
20
+ expect(resolveSubmitInput('model_apikey', ' sk-abc ')).toBe('sk-abc');
21
+ expect(resolveSubmitInput('idle', 'hello')).toBe('hello');
22
+ });
23
+ });
@@ -0,0 +1,17 @@
1
+ /**
2
+ * Prompt phases where submitting an empty line is meaningful. At the apikey
3
+ * prompt the hint reads "apikey (回车沿用 sk-…xxxx)> " — a bare Enter means
4
+ * "reuse the saved key", and handleApiKey falls back to it for empty input.
5
+ */
6
+ const EMPTY_SUBMIT_PHASES = new Set(['model_apikey']);
7
+
8
+ /**
9
+ * Decide whether a submitted line should be dispatched. Returns the trimmed
10
+ * value, or null when the line is empty and the phase gives it no meaning —
11
+ * so a bare Enter is a no-op everywhere except the apikey prompt.
12
+ */
13
+ export function resolveSubmitInput(phase: string, raw: string): string | null {
14
+ const trimmed = raw.trim();
15
+ if (!trimmed && !EMPTY_SUBMIT_PHASES.has(phase)) return null;
16
+ return trimmed;
17
+ }
@@ -0,0 +1,242 @@
1
+ import { afterEach, describe, expect, test } from 'bun:test';
2
+ import { mkdtempSync, mkdirSync, rmSync, writeFileSync } from 'node:fs';
3
+ import { tmpdir } from 'node:os';
4
+ import path from 'node:path';
5
+ import {
6
+ autoUpdateNotice,
7
+ isDevInstall,
8
+ planAutoUpdate,
9
+ startAutoUpdate,
10
+ } from './upgrade.js';
11
+
12
+ let configDir: string | undefined;
13
+
14
+ function useTempConfig(raw: unknown): void {
15
+ configDir = mkdtempSync(path.join(tmpdir(), 'transcode-autoupdate-test-'));
16
+ process.env.TRANSCODE_CONFIG_PATH = path.join(configDir, 'config.json');
17
+ writeFileSync(process.env.TRANSCODE_CONFIG_PATH, JSON.stringify({ autoUpdate: raw }));
18
+ }
19
+
20
+ afterEach(() => {
21
+ delete process.env.TRANSCODE_CONFIG_PATH;
22
+ if (configDir) {
23
+ rmSync(configDir, { recursive: true, force: true });
24
+ configDir = undefined;
25
+ }
26
+ });
27
+
28
+ describe('isDevInstall', () => {
29
+ test('an entry under the npm root is a global install', () => {
30
+ const root = mkdtempSync(path.join(tmpdir(), 'transcode-root-test-'));
31
+ try {
32
+ mkdirSync(path.join(root, '@trans-ai'));
33
+ const entry = path.join(root, '@trans-ai', 'trans-code.ts');
34
+ writeFileSync(entry, '');
35
+ expect(isDevInstall(entry, root)).toBe(false);
36
+ } finally {
37
+ rmSync(root, { recursive: true, force: true });
38
+ }
39
+ });
40
+
41
+ test('an entry outside the npm root (repo checkout / bun link) is a dev install', () => {
42
+ const root = mkdtempSync(path.join(tmpdir(), 'transcode-root-test-'));
43
+ const outside = mkdtempSync(path.join(tmpdir(), 'transcode-dev-test-'));
44
+ try {
45
+ const entry = path.join(outside, 'trans-code.ts');
46
+ writeFileSync(entry, '');
47
+ expect(isDevInstall(entry, root)).toBe(true);
48
+ } finally {
49
+ rmSync(root, { recursive: true, force: true });
50
+ rmSync(outside, { recursive: true, force: true });
51
+ }
52
+ });
53
+ });
54
+
55
+ describe('autoUpdateNotice / startAutoUpdate', () => {
56
+ test('autoUpdateNotice resolves null before startAutoUpdate runs', async () => {
57
+ expect(await autoUpdateNotice()).toBeNull();
58
+ });
59
+
60
+ test('a disabled config settles the notice to null without touching npm', async () => {
61
+ useTempConfig(false);
62
+ startAutoUpdate();
63
+ expect(await autoUpdateNotice()).toBeNull();
64
+ // lastCheck must not be written for a disabled updater.
65
+ const saved = JSON.parse(
66
+ await Bun.file(process.env.TRANSCODE_CONFIG_PATH!).text(),
67
+ );
68
+ expect(saved.autoUpdate).toBe(false);
69
+ });
70
+ });
71
+
72
+ const HOUR = 3_600_000;
73
+ const NOW = 1_700_000_000_000;
74
+
75
+ function defaults(overrides: Partial<Parameters<typeof planAutoUpdate>[0]> = {}) {
76
+ return {
77
+ current: '0.4.0',
78
+ latest: '0.5.0',
79
+ target: 'latest',
80
+ enabled: true,
81
+ lastCheck: 0,
82
+ now: NOW,
83
+ ...overrides,
84
+ };
85
+ }
86
+
87
+ describe('planAutoUpdate', () => {
88
+ test('envSkip wins over everything, including disabled', () => {
89
+ const plan = planAutoUpdate(defaults({ envSkip: true, enabled: false, lastCheck: NOW }));
90
+ expect(plan).toEqual({ action: 'skip', reason: 'env-skip' });
91
+ });
92
+
93
+ test('disabled skips regardless of throttle state', () => {
94
+ expect(planAutoUpdate(defaults({ enabled: false }))).toEqual({
95
+ action: 'skip',
96
+ reason: 'disabled',
97
+ });
98
+ });
99
+
100
+ test('throttled while the interval has not fully elapsed (even by 1ms)', () => {
101
+ expect(
102
+ planAutoUpdate(defaults({ lastCheck: NOW - 24 * HOUR + 1 })),
103
+ ).toEqual({ action: 'skip', reason: 'throttled' });
104
+ });
105
+
106
+ test('the boundary elapses exactly at now - lastCheck === interval', () => {
107
+ const plan = planAutoUpdate(defaults({ lastCheck: NOW - 24 * HOUR }));
108
+ expect(plan).toEqual({ action: 'install', spec: '@trans-ai/trans-code@latest', from: '0.4.0', to: '0.5.0' });
109
+ });
110
+
111
+ test('intervalHours overrides the default 24h window', () => {
112
+ expect(
113
+ planAutoUpdate(defaults({ lastCheck: NOW - 2 * HOUR, intervalHours: 1 })),
114
+ ).toEqual({ action: 'install', spec: '@trans-ai/trans-code@latest', from: '0.4.0', to: '0.5.0' });
115
+ });
116
+
117
+ test('latest mode: unreachable registry skips silently (unknown-latest)', () => {
118
+ expect(planAutoUpdate(defaults({ latest: null }))).toEqual({
119
+ action: 'skip',
120
+ reason: 'unknown-latest',
121
+ });
122
+ });
123
+
124
+ test('latest mode: already current skips (up-to-date)', () => {
125
+ expect(planAutoUpdate(defaults({ latest: '0.4.0' }))).toEqual({
126
+ action: 'skip',
127
+ reason: 'up-to-date',
128
+ });
129
+ });
130
+
131
+ test('latest mode: newer version installs the full package spec', () => {
132
+ expect(planAutoUpdate(defaults({ latest: '0.5.0' }))).toEqual({
133
+ action: 'install',
134
+ spec: '@trans-ai/trans-code@latest',
135
+ from: '0.4.0',
136
+ to: '0.5.0',
137
+ });
138
+ });
139
+
140
+ test('pinned mode: same version skips even when the registry moved on', () => {
141
+ expect(planAutoUpdate(defaults({ target: '0.4.0', latest: '0.9.0' }))).toEqual({
142
+ action: 'skip',
143
+ reason: 'up-to-date',
144
+ });
145
+ });
146
+
147
+ test('pinned mode: a different version installs the pin, downgrades included', () => {
148
+ expect(planAutoUpdate(defaults({ target: '0.3.0', latest: '0.9.0' }))).toEqual({
149
+ action: 'install',
150
+ spec: '@trans-ai/trans-code@0.3.0',
151
+ from: '0.4.0',
152
+ to: '0.3.0',
153
+ });
154
+ });
155
+ });
156
+
157
+ describe('background update silence (spawned-runner E2E)', () => {
158
+ /**
159
+ * Spawns a runner that calls startAutoUpdate() against a fake npm whose
160
+ * non-`root` calls fail on stderr after a 5s sleep (degraded network).
161
+ * `holdMs` keeps the runner alive that long, simulating a REPL session.
162
+ * Returns the child's exit status and captured stderr.
163
+ */
164
+ async function runAgainstSlowFailingNpm(holdMs: number) {
165
+ const dir = mkdtempSync(path.join(tmpdir(), 'transcode-silence-test-'));
166
+ try {
167
+ const bin = path.join(dir, 'bin');
168
+ mkdirSync(bin);
169
+ writeFileSync(
170
+ path.join(bin, 'npm'),
171
+ [
172
+ '#!/bin/sh',
173
+ // A root that contains every path lets the dev-install guard pass.
174
+ 'if [ "$1" = "root" ]; then echo "/"; exit 0; fi',
175
+ 'sleep 5',
176
+ 'echo "npm error fake-network-boom" >&2',
177
+ 'exit 1',
178
+ ].join('\n'),
179
+ );
180
+ const { chmodSync } = await import('node:fs');
181
+ chmodSync(path.join(bin, 'npm'), 0o755);
182
+
183
+ const configPath = path.join(dir, 'config.json');
184
+ writeFileSync(configPath, JSON.stringify({ autoUpdate: { lastCheck: 0 } }));
185
+
186
+ const runner = path.join(dir, 'runner.ts');
187
+ writeFileSync(
188
+ runner,
189
+ `import { startAutoUpdate } from ${JSON.stringify(path.join(import.meta.dir, 'upgrade.ts'))};\n` +
190
+ 'startAutoUpdate();\n' +
191
+ `setTimeout(() => {}, ${holdMs});\n`,
192
+ );
193
+
194
+ const { spawnSync } = await import('node:child_process');
195
+ // Strip bun-test-injected vars: a child `bun <file>` with BUN_TEST_*
196
+ // set misbehaves. Keep the ambient PATH/HOME only.
197
+ const cleanEnv: Record<string, string> = {};
198
+ for (const [key, value] of Object.entries(process.env)) {
199
+ if (value !== undefined && !key.startsWith('BUN_')) cleanEnv[key] = value;
200
+ }
201
+ const result = spawnSync(process.execPath, [runner], {
202
+ timeout: 9000,
203
+ encoding: 'utf8',
204
+ env: {
205
+ ...cleanEnv,
206
+ PATH: `${bin}:${process.env.PATH}`,
207
+ TRANSCODE_CONFIG_PATH: configPath,
208
+ },
209
+ });
210
+ return {
211
+ status: result.status,
212
+ signal: result.signal,
213
+ stderr: result.stderr ?? '',
214
+ };
215
+ } finally {
216
+ rmSync(dir, { recursive: true, force: true });
217
+ }
218
+ }
219
+
220
+ test(
221
+ 'quitting right after startup must not hang on a slow npm',
222
+ async () => {
223
+ const { status, signal, stderr } = await runAgainstSlowFailingNpm(0);
224
+ expect(
225
+ `status=${status} signal=${signal}\n${stderr.slice(0, 300)}`,
226
+ ).toBe('status=0 signal=null\n');
227
+ },
228
+ 15_000,
229
+ );
230
+
231
+ test(
232
+ 'npm failure text must never reach the terminal (silent failure)',
233
+ async () => {
234
+ // Stay alive past the fake npm's 5s sleep so the failure would land
235
+ // if stderr were inherited.
236
+ const { status, stderr } = await runAgainstSlowFailingNpm(6500);
237
+ expect(status).toBe(0);
238
+ expect(stderr).not.toContain('fake-network-boom');
239
+ },
240
+ 15_000,
241
+ );
242
+ });