@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.
@@ -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,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
+ });
@@ -0,0 +1,149 @@
1
+ import { existsSync, mkdirSync, readFileSync, readdirSync, writeFileSync } from 'node:fs';
2
+ import { homedir } from 'node:os';
3
+ import path from 'node:path';
4
+ import {
5
+ AIMessage,
6
+ HumanMessage,
7
+ SystemMessage,
8
+ ToolMessage,
9
+ type BaseMessage,
10
+ type MessageContent,
11
+ } from '@langchain/core/messages';
12
+
13
+ /** A persisted conversation (one JSON file under ~/.transcode/sessions). */
14
+ export interface SessionRecord {
15
+ id: string;
16
+ title: string;
17
+ createdAt: number;
18
+ updatedAt: number;
19
+ cwd: string;
20
+ model: string;
21
+ messages: BaseMessage[];
22
+ }
23
+
24
+ interface StoredMessage {
25
+ type: string;
26
+ content: MessageContent;
27
+ tool_calls?: AIMessage['tool_calls'];
28
+ tool_call_id?: string;
29
+ name?: string;
30
+ }
31
+
32
+ // Test isolation mirrors TRANSCODE_CONFIG_PATH.
33
+ const sessionsDir = (): string =>
34
+ process.env.TRANSCODE_SESSIONS_DIR ?? path.join(homedir(), '.transcode', 'sessions');
35
+
36
+ function serialize(messages: BaseMessage[]): StoredMessage[] {
37
+ return messages.map((message) => {
38
+ const stored: StoredMessage = { type: message.getType(), content: message.content };
39
+ const ai = message as AIMessage;
40
+ if (ai.tool_calls?.length) stored.tool_calls = ai.tool_calls;
41
+ const tool = message as ToolMessage;
42
+ if (tool.tool_call_id) {
43
+ stored.tool_call_id = tool.tool_call_id;
44
+ stored.name = tool.name;
45
+ }
46
+ return stored;
47
+ });
48
+ }
49
+
50
+ function deserialize(stored: StoredMessage[]): BaseMessage[] {
51
+ return stored.map((item) => {
52
+ const content = item.content as MessageContent;
53
+ switch (item.type) {
54
+ case 'system':
55
+ return new SystemMessage({ content: content as string });
56
+ case 'ai':
57
+ return new AIMessage({
58
+ content,
59
+ ...(item.tool_calls ? { tool_calls: item.tool_calls } : {}),
60
+ });
61
+ case 'tool':
62
+ return new ToolMessage({
63
+ content: content as string,
64
+ tool_call_id: item.tool_call_id ?? '',
65
+ name: item.name ?? 'tool',
66
+ });
67
+ default:
68
+ return new HumanMessage({ content });
69
+ }
70
+ });
71
+ }
72
+
73
+ function readRecord(file: string): SessionRecord | null {
74
+ try {
75
+ const parsed = JSON.parse(readFileSync(file, 'utf8')) as Omit<SessionRecord, 'messages'> & {
76
+ messages: StoredMessage[];
77
+ };
78
+ return { ...parsed, messages: deserialize(parsed.messages ?? []) };
79
+ } catch {
80
+ return null;
81
+ }
82
+ }
83
+
84
+ export function saveSession(record: SessionRecord): void {
85
+ const dir = sessionsDir();
86
+ mkdirSync(dir, { recursive: true });
87
+ writeFileSync(
88
+ path.join(dir, `${record.id}.json`),
89
+ JSON.stringify({ ...record, messages: serialize(record.messages) }, null, 2),
90
+ );
91
+ }
92
+
93
+ /** All conversations, newest first. */
94
+ export function listSessions(): SessionRecord[] {
95
+ const dir = sessionsDir();
96
+ if (!existsSync(dir)) return [];
97
+ return readdirSync(dir)
98
+ .filter((file) => file.endsWith('.json'))
99
+ .map((file) => readRecord(path.join(dir, file)))
100
+ .filter((record): record is SessionRecord => record !== null)
101
+ .sort((a, b) => b.updatedAt - a.updatedAt);
102
+ }
103
+
104
+ export function getSession(id: string): SessionRecord | undefined {
105
+ const record = readRecord(path.join(sessionsDir(), `${id}.json`));
106
+ return record ?? undefined;
107
+ }
108
+
109
+ /** Keyword search over titles AND message content (case-insensitive). */
110
+ export function searchSessions(keyword: string): SessionRecord[] {
111
+ const query = keyword.trim().toLowerCase();
112
+ if (!query) return listSessions();
113
+ return listSessions().filter(
114
+ (record) =>
115
+ record.title.toLowerCase().includes(query) ||
116
+ record.messages.some((message) =>
117
+ typeof message.content === 'string'
118
+ ? message.content.toLowerCase().includes(query)
119
+ : JSON.stringify(message.content).toLowerCase().includes(query),
120
+ ),
121
+ );
122
+ }
123
+
124
+ /**
125
+ * Model-generated conversation title (≤12 chars). Returns the derived
126
+ * fallback when the model call fails.
127
+ */
128
+ export async function generateTitle(
129
+ model: { invoke: (input: string) => Promise<{ content: unknown }> },
130
+ firstUserText: string,
131
+ firstAssistantText: string,
132
+ ): Promise<string> {
133
+ const fallback = firstUserText.replace(/\s+/g, ' ').trim().slice(0, 24) || '新对话';
134
+ try {
135
+ const response = await model.invoke(
136
+ '为下面这段对话生成一个不超过 12 个字的中文标题,只输出标题本身,不要标点。\n' +
137
+ `用户:${firstUserText.slice(0, 500)}\n助手:${firstAssistantText.slice(0, 500)}`,
138
+ );
139
+ const text = (typeof response.content === 'string'
140
+ ? response.content
141
+ : JSON.stringify(response.content)
142
+ )
143
+ .replace(/["“”'‘’\s]/g, '')
144
+ .slice(0, 16);
145
+ return text.length >= 2 ? text : fallback;
146
+ } catch {
147
+ return fallback;
148
+ }
149
+ }
@@ -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
+ });