@trans-ai/trans-code 0.6.1 → 0.7.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/docs/superpowers/plans/2026-11-21-one-step-resume.md +125 -0
- package/docs/superpowers/specs/2026-11-21-one-step-resume-design.md +30 -0
- package/package.json +1 -1
- package/src/screens/REPL.tsx +90 -29
- package/src/sessions/resume.test.ts +92 -0
- package/src/sessions/resume.ts +34 -0
- package/src/sessions/store.test.ts +60 -2
- package/src/sessions/store.ts +53 -13
- package/src/version.ts +1 -1
|
@@ -0,0 +1,125 @@
|
|
|
1
|
+
# 一步恢复会话(/resume 项目作用域选择器)Implementation Plan
|
|
2
|
+
|
|
3
|
+
> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking.
|
|
4
|
+
|
|
5
|
+
**Goal:** `/resume` 无参数弹出当前项目的会话选择器(↑↓ + Enter + Esc),一条命令完成浏览+恢复。
|
|
6
|
+
|
|
7
|
+
**Architecture:** 纯逻辑(按 cwd 过滤列表、恢复目标解析)落到新模块 `src/sessions/resume.ts` 走 TDD;REPL 克隆现有 `model_select` 的 phase 状态机接键盘与渲染。带参 `/resume` 与 `/sessions` 行为不变。
|
|
8
|
+
|
|
9
|
+
**Tech Stack:** TypeScript + Ink(React)、bun:test。
|
|
10
|
+
|
|
11
|
+
**Spec:** `docs/superpowers/specs/2026-11-21-one-step-resume-design.md`
|
|
12
|
+
|
|
13
|
+
## Global Constraints
|
|
14
|
+
|
|
15
|
+
- 选择器只列 `record.cwd === process.cwd()` 的会话(含旧平铺文件,按记录里的 `cwd` 字段命中);本项目为空时提示「当前项目暂无历史对话」,不回退全局
|
|
16
|
+
- 选择器最多 20 条,行格式沿用 `/sessions`:`N. 标题 · 时间 · 模型 · N 条`(spec 原文)
|
|
17
|
+
- `/resume <序号|id|标题片段>` 与 `/sessions`(全局列表+搜索)行为不变
|
|
18
|
+
- 键位:↑↓ 环形移动、Enter 恢复、Esc 走现有通用取消路径(同 `model_select`)
|
|
19
|
+
- 所有测试用 `TRANSCODE_SESSIONS_DIR` 指向 mkdtemp 临时目录,绝不触碰真实 `~/.transcode`
|
|
20
|
+
|
|
21
|
+
## Review Focus
|
|
22
|
+
|
|
23
|
+
- `/resume `(仅空白参数)必须等同于无参 → 弹选择器,而不是「未找到」(解析函数先 trim;Task 1 测试)
|
|
24
|
+
- 序号越界(`/resume 99`)→ 返回 undefined 走现有「未找到」提示,不崩溃(Task 1 测试)
|
|
25
|
+
- 旧平铺会话按记录内 `cwd` 字段命中本项目过滤(Task 1 测试)
|
|
26
|
+
- 精确 id 优先于片段匹配;id 与标题都能作为片段命中(Task 1 测试)
|
|
27
|
+
- 本项目零会话时 `/resume` 给提示而非空选择器(Task 2 接线,沿 Task 1 的空数组语义)
|
|
28
|
+
|
|
29
|
+
---
|
|
30
|
+
|
|
31
|
+
### Task 1: cwd 作用域列表 + 恢复目标解析(纯逻辑)
|
|
32
|
+
|
|
33
|
+
**Files:**
|
|
34
|
+
- Create: `src/sessions/resume.ts`
|
|
35
|
+
- Test: `src/sessions/resume.test.ts`
|
|
36
|
+
|
|
37
|
+
**Interfaces:**
|
|
38
|
+
- Consumes: `listSessions(): SessionRecord[]`(store.js,已按 updatedAt 倒序)、`SessionRecord`(store.js)
|
|
39
|
+
- Produces(Task 2 依赖,签名精确):
|
|
40
|
+
- `listProjectSessions(cwd: string): SessionRecord[]` — 本项目会话,新→旧
|
|
41
|
+
- `resolveResumeTarget(target: string, lastIds: string[], list: SessionRecord[]): SessionRecord | undefined`
|
|
42
|
+
|
|
43
|
+
- [ ] **Step 1: 写失败测试**(环境准备同 `store.test.ts`:`beforeEach` mkdtemp + 设 `TRANSCODE_SESSIONS_DIR`,`afterEach` 清理删除)
|
|
44
|
+
|
|
45
|
+
```ts
|
|
46
|
+
describe('listProjectSessions', () => {
|
|
47
|
+
test('only returns sessions whose cwd matches, including legacy flat files', () => {
|
|
48
|
+
saveSession({ ...sample('A', 'a'), id: 'ses_a', cwd: '/tmp/proj-a' });
|
|
49
|
+
saveSession({ ...sample('B', 'b'), id: 'ses_b', cwd: '/tmp/proj-b' });
|
|
50
|
+
// 旧平铺文件:直接 writeFileSync 到 sessions 根目录,记录内 cwd = '/tmp/proj-a'
|
|
51
|
+
writeLegacyFlat('ses_legacy', '/tmp/proj-a');
|
|
52
|
+
const ids = listProjectSessions('/tmp/proj-a').map(s => s.id).sort();
|
|
53
|
+
expect(ids).toEqual(['ses_a', 'ses_legacy']);
|
|
54
|
+
});
|
|
55
|
+
});
|
|
56
|
+
|
|
57
|
+
describe('resolveResumeTarget', () => {
|
|
58
|
+
// list 顺序即 /sessions 展示顺序;lastIds 是上次列表的 id 快照
|
|
59
|
+
test('numeric resolves through lastIds first, then falls back to list index', () => {
|
|
60
|
+
expect(resolveResumeTarget('2', ['x1', 'ses_b'], list)?.id).toBe('ses_b');
|
|
61
|
+
expect(resolveResumeTarget('1', [], list)?.id).toBe(list[0]!.id);
|
|
62
|
+
});
|
|
63
|
+
test('numeric out of range returns undefined', () => {
|
|
64
|
+
expect(resolveResumeTarget('99', [], list)).toBeUndefined();
|
|
65
|
+
});
|
|
66
|
+
test('exact id beats substring; id/title substring both match', () => {
|
|
67
|
+
expect(resolveResumeTarget('ses_a', [], list)?.id).toBe('ses_a');
|
|
68
|
+
expect(resolveResumeTarget('proj', [], list)?.id).toBeDefined(); // 标题片段
|
|
69
|
+
});
|
|
70
|
+
test('blank target returns undefined (caller opens the picker)', () => {
|
|
71
|
+
expect(resolveResumeTarget(' ', [], list)).toBeUndefined();
|
|
72
|
+
});
|
|
73
|
+
});
|
|
74
|
+
```
|
|
75
|
+
|
|
76
|
+
- [ ] **Step 2: 跑测试确认失败**
|
|
77
|
+
|
|
78
|
+
Run: `bun test src/sessions/resume.test.ts`
|
|
79
|
+
Expected: FAIL — 模块 `./resume.js` 不存在(导出未找到)
|
|
80
|
+
|
|
81
|
+
- [ ] **Step 3: 实现 `src/sessions/resume.ts`**
|
|
82
|
+
|
|
83
|
+
- `listProjectSessions(cwd)` = `listSessions().filter(s => s.cwd === cwd)`(沿用既有排序)
|
|
84
|
+
- `resolveResumeTarget(target, lastIds, list)`:`target = target.trim()`,空 → undefined;`/^\d+$/` → `n = Number(target)`,先按 `lastIds[n-1]` 在 list 里找同 id 记录,否则 `list[n-1]`,越界 → undefined;否则 `list.find(r => r.id === target)` 优先,再 `find(r => r.id.includes(target) || r.title.includes(target))`
|
|
85
|
+
- 帮助函数(sample/writeLegacyFlat)只放测试文件
|
|
86
|
+
|
|
87
|
+
- [ ] **Step 4: 跑测试确认通过**
|
|
88
|
+
|
|
89
|
+
Run: `bun test src/sessions/resume.test.ts` → PASS
|
|
90
|
+
|
|
91
|
+
- [ ] **Step 5: Commit**
|
|
92
|
+
|
|
93
|
+
```bash
|
|
94
|
+
git add src/sessions/resume.ts src/sessions/resume.test.ts
|
|
95
|
+
git commit -m "feat: cwd-scoped session list and pure resume-target resolution"
|
|
96
|
+
```
|
|
97
|
+
|
|
98
|
+
### Task 2: REPL 接线 session_select phase
|
|
99
|
+
|
|
100
|
+
**Files:**
|
|
101
|
+
- Modify: `src/screens/REPL.tsx` — phase 联合类型(~:48-60)、`modelCursor` 旁加状态(~:97)、`lastSessionsRef`(~:136)、`/resume` 分支(:628-657)、`useInput`(:717+ 的 `model_select` 分支旁)、`model_select` 渲染块后(:1029)、输入框门控(:1065)
|
|
102
|
+
|
|
103
|
+
**Interfaces:**
|
|
104
|
+
- Consumes: `listProjectSessions`、`resolveResumeTarget`(Task 1);`createToolSession`、`listSessions`、`getSession` 不变
|
|
105
|
+
- Produces: 无(终端交互)
|
|
106
|
+
|
|
107
|
+
- [ ] **Step 1: 状态与类型** — `PromptPhase` 增加 `'session_select'`;新增 `const [sessionCursor, setSessionCursor] = useState(0);` 与 `const sessionPickerRef = useRef<SessionRecord[]>([]);`;import Task 1 两个函数与 `SessionRecord` 类型
|
|
108
|
+
|
|
109
|
+
- [ ] **Step 2: 重写 `/resume` 分支** — 抽 `applyResume(record: SessionRecord)`(设 `conversationRef`/`conversationTitleRef`/`messagesRef`/`toolSessionRef` + `addHistory` 确认行,即现 :643-650 内容);无参路径:`listProjectSessions(process.cwd()).slice(0, 20)` 为空 → `addHistory`「当前项目暂无历史对话」,非空 → 写 `sessionPickerRef` + `lastSessionsRef.current = 快照 ids` + `setSessionCursor(0)` + `setPhase('session_select')` + `commitInput('')`;带参路径:内联解析替换为 `resolveResumeTarget(target, lastSessionsRef.current, listSessions())`,undefined → 现有「未找到」提示,命中 → `applyResume`
|
|
110
|
+
|
|
111
|
+
- [ ] **Step 3: `useInput` 新分支**(克隆 :761-820 的 `model_select` 分支)— `phase === 'session_select'`:`key.return` → `applyResume(sessionPickerRef.current[sessionCursor]!)` + `setPhase('idle')`;`key.upArrow`/`key.downArrow` → 环形移动 `% length`;Esc 由 :732-747 现有通用路径处理(处于 `phase !== 'idle'` 即回 idle),无需新增
|
|
112
|
+
|
|
113
|
+
- [ ] **Step 4: 渲染块**(插在 :1029 `model_select` 块后,镜像其结构)— 头行灰字「恢复对话 (↑↓ 选择 · Enter 恢复 · Esc 取消)」;每行 `❯ `/两空格 + `N. ${title} · ${new Date(updatedAt).toLocaleString()} · ${model} · ${messages.length} 条`,光标行 cyan;:1065 输入框门控改为 `phase !== 'model_select' && phase !== 'session_select'`
|
|
114
|
+
|
|
115
|
+
- [ ] **Step 5: 全量验证**
|
|
116
|
+
|
|
117
|
+
Run: `bun test`(全绿,含 Task 1 与既有 227 个)+ `npm run typecheck`(无输出)
|
|
118
|
+
另:`bun run dev` 手动冒烟 `/resume` ⏎ → 选择 → Esc(可选,交互无法自动化)
|
|
119
|
+
|
|
120
|
+
- [ ] **Step 6: Commit**
|
|
121
|
+
|
|
122
|
+
```bash
|
|
123
|
+
git add src/screens/REPL.tsx
|
|
124
|
+
git commit -m "feat: one-step /resume with cwd-scoped arrow-key session picker"
|
|
125
|
+
```
|
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
# 一步恢复会话(/resume 无参数弹选择器)— 设计
|
|
2
|
+
|
|
3
|
+
## 意图
|
|
4
|
+
|
|
5
|
+
现在恢复会话要两步:先 `/sessions` 看带序号的列表,再 `/resume 3`。目标:一条命令完成浏览+选择 —— `/resume` 不带参数直接弹出方向键选择器,Enter 恢复、Esc 取消。
|
|
6
|
+
|
|
7
|
+
## 目标
|
|
8
|
+
|
|
9
|
+
- `/resume` 无参数 → 模态选择器(复用 `model_select` 的 phase 模式)
|
|
10
|
+
- **选择器按当前 cwd 过滤**:只列本项目的历史会话(与保存时按目录分区对应,同 Claude Code `--resume` 的项目作用域);当前项目没有会话时提示「当前项目暂无历史对话」,不回退到全局
|
|
11
|
+
- ↑↓ 循环移动、Enter 恢复、Esc 取消回到输入态
|
|
12
|
+
- `/resume <序号|id|标题片段>` 和 `/sessions` 行为不变(`/sessions` 仍为全局列表 + 搜索)
|
|
13
|
+
|
|
14
|
+
## 非目标
|
|
15
|
+
|
|
16
|
+
- 选择器内滚动/翻页(最多显示 20 条)
|
|
17
|
+
- 选择器内关键词过滤、删除会话
|
|
18
|
+
- `/sessions` 改为按项目过滤(保持全局视图)
|
|
19
|
+
|
|
20
|
+
## 设计
|
|
21
|
+
|
|
22
|
+
- **触发**:`/resume` 无参数 → `listSessions().filter(s => s.cwd === process.cwd())` 取本项目会话(不做旧版平铺文件兼容,只认按目录分区的新布局),非空则快照前 20 条、`setPhase('session_select')`、清空输入;为空则提示「当前项目暂无历史对话」。
|
|
23
|
+
- **键位**(新增 `useInput` 分支,照抄 `model_select`):↑↓ 环形移动 cursor;Enter 调共享的恢复逻辑;Esc 走现有 phase 通用取消路径。
|
|
24
|
+
- **恢复逻辑**:从现 `/resume` 分支抽出 `applyResume(record)`(设 conversationRef/标题/messagesRef/toolSession + 确认历史行),带参/无参两条路径共用;恢复后把 `lastSessionsRef` 同步为选择器列表,让紧随其后的 `/resume N` 序号与所见一致。
|
|
25
|
+
- **渲染**:镜像 `model_select` 的块 —— 顶部「恢复对话 (↑↓ 选择 · Enter 恢复 · Esc 取消)」,行格式复用 `/sessions` 的 `N. 标题 · 时间 · 模型 · N 条`,光标行 cyan + `❯`。
|
|
26
|
+
- **测试**:恢复目标解析逻辑(无参→选择器、数字→lastSessions 索引、id/片段→匹配)抽成纯函数,TDD 覆盖;键盘/渲染接线与 `model_select` 同标准(不单测)。
|
|
27
|
+
|
|
28
|
+
## 备选方案(已否)
|
|
29
|
+
|
|
30
|
+
- **无参直接恢复最近会话**(claude -c 式):按键最少,但选不了目标,只能回到最新;用户已选方向键选择器。
|
package/package.json
CHANGED
package/src/screens/REPL.tsx
CHANGED
|
@@ -22,11 +22,13 @@ import { createToolSession } from '../agent/tools/index.js';
|
|
|
22
22
|
import { getPermissionMode } from '../agent/permission.js';
|
|
23
23
|
import {
|
|
24
24
|
generateTitle,
|
|
25
|
-
getSession,
|
|
26
25
|
listSessions,
|
|
26
|
+
newSessionId,
|
|
27
27
|
saveSession,
|
|
28
28
|
searchSessions,
|
|
29
|
+
type SessionRecord,
|
|
29
30
|
} from '../sessions/store.js';
|
|
31
|
+
import { listProjectSessions, resolveResumeTarget } from '../sessions/resume.js';
|
|
30
32
|
import { walkFiles } from '../agent/tools/fs-utils.js';
|
|
31
33
|
import { applyCompletion, filterFiles, mentionQuery } from './file-completion.js';
|
|
32
34
|
import {
|
|
@@ -55,7 +57,8 @@ type PromptPhase =
|
|
|
55
57
|
| 'vendor_apikey'
|
|
56
58
|
| 'model_apikey'
|
|
57
59
|
| 'model_check'
|
|
58
|
-
| 'permission'
|
|
60
|
+
| 'permission'
|
|
61
|
+
| 'session_select';
|
|
59
62
|
|
|
60
63
|
interface REPLProps {
|
|
61
64
|
ctx: CommandContext;
|
|
@@ -94,6 +97,8 @@ export default function REPL({ ctx, updateNotice }: REPLProps) {
|
|
|
94
97
|
setPendingModel(id);
|
|
95
98
|
};
|
|
96
99
|
const [modelCursor, setModelCursor] = useState(0);
|
|
100
|
+
// session_select picker: cursor over the project-scoped session snapshot.
|
|
101
|
+
const [sessionCursor, setSessionCursor] = useState(0);
|
|
97
102
|
// Model selection flow: vendor → model → key (reused if saved) → check.
|
|
98
103
|
const [pickOptions, setPickOptions] = useState<string[]>([]);
|
|
99
104
|
const [pickCursor, setPickCursor] = useState(0);
|
|
@@ -133,6 +138,22 @@ export default function REPL({ ctx, updateNotice }: REPLProps) {
|
|
|
133
138
|
const conversationRef = useRef<{ id: string; createdAt: number; titled: boolean } | null>(null);
|
|
134
139
|
const conversationTitleRef = useRef('');
|
|
135
140
|
const lastSessionsRef = useRef<string[]>([]);
|
|
141
|
+
// Snapshot for the /resume arrow-key picker (set together with the phase).
|
|
142
|
+
const sessionPickerRef = useRef<SessionRecord[]>([]);
|
|
143
|
+
/** Load a record into the live conversation; shared by /resume arg and picker paths. */
|
|
144
|
+
const applyResume = useCallback(
|
|
145
|
+
(record: SessionRecord, inputLine: string) => {
|
|
146
|
+
conversationRef.current = { id: record.id, createdAt: record.createdAt, titled: true };
|
|
147
|
+
conversationTitleRef.current = record.title;
|
|
148
|
+
messagesRef.current = record.messages;
|
|
149
|
+
toolSessionRef.current = createToolSession(process.cwd());
|
|
150
|
+
addHistory({
|
|
151
|
+
input: inputLine,
|
|
152
|
+
output: `已恢复「${record.title}」(${record.messages.length} 条消息,${record.model}),继续对话。`,
|
|
153
|
+
});
|
|
154
|
+
},
|
|
155
|
+
[addHistory],
|
|
156
|
+
);
|
|
136
157
|
|
|
137
158
|
// @-mention file completion: lazy file list, active query, dismissed flag.
|
|
138
159
|
const [fileList, setFileList] = useState<string[] | null>(null);
|
|
@@ -336,7 +357,7 @@ export default function REPL({ ctx, updateNotice }: REPLProps) {
|
|
|
336
357
|
// Persist the conversation for /sessions and /resume.
|
|
337
358
|
if (!conversationRef.current) {
|
|
338
359
|
conversationRef.current = {
|
|
339
|
-
id:
|
|
360
|
+
id: newSessionId(),
|
|
340
361
|
createdAt: Date.now(),
|
|
341
362
|
titled: false,
|
|
342
363
|
};
|
|
@@ -627,27 +648,24 @@ export default function REPL({ ctx, updateNotice }: REPLProps) {
|
|
|
627
648
|
|
|
628
649
|
if (cmdName === 'resume') {
|
|
629
650
|
const target = args.join(' ').trim();
|
|
630
|
-
|
|
631
|
-
|
|
632
|
-
|
|
633
|
-
|
|
634
|
-
|
|
635
|
-
|
|
636
|
-
|
|
637
|
-
(session) => session.id
|
|
638
|
-
|
|
639
|
-
|
|
640
|
-
|
|
641
|
-
addHistory({ input: trimmed, output: `未找到对话“${target || '(空)'}”。先 /sessions 查看列表。` });
|
|
651
|
+
if (!target) {
|
|
652
|
+
// One-step resume: arrow-key picker over this project's sessions.
|
|
653
|
+
const projectSessions = listProjectSessions(process.cwd()).slice(0, 20);
|
|
654
|
+
if (projectSessions.length === 0) {
|
|
655
|
+
addHistory({ input: trimmed, output: '当前项目暂无历史对话。' });
|
|
656
|
+
} else {
|
|
657
|
+
sessionPickerRef.current = projectSessions;
|
|
658
|
+
lastSessionsRef.current = projectSessions.map((session) => session.id);
|
|
659
|
+
setSessionCursor(0);
|
|
660
|
+
setPhase('session_select');
|
|
661
|
+
}
|
|
642
662
|
} else {
|
|
643
|
-
|
|
644
|
-
|
|
645
|
-
|
|
646
|
-
|
|
647
|
-
|
|
648
|
-
|
|
649
|
-
output: `已恢复「${record.title}」(${record.messages.length} 条消息,${record.model}),继续对话。`,
|
|
650
|
-
});
|
|
663
|
+
const record = resolveResumeTarget(target, lastSessionsRef.current, listSessions());
|
|
664
|
+
if (!record) {
|
|
665
|
+
addHistory({ input: trimmed, output: `未找到对话“${target}”。先 /sessions 查看列表。` });
|
|
666
|
+
} else {
|
|
667
|
+
applyResume(record, trimmed);
|
|
668
|
+
}
|
|
651
669
|
}
|
|
652
670
|
commitInput('');
|
|
653
671
|
setHistoryIndex(-1);
|
|
@@ -821,6 +839,30 @@ export default function REPL({ ctx, updateNotice }: REPLProps) {
|
|
|
821
839
|
return;
|
|
822
840
|
}
|
|
823
841
|
|
|
842
|
+
if (phase === 'session_select') {
|
|
843
|
+
const picker = sessionPickerRef.current;
|
|
844
|
+
if (picker.length === 0) return;
|
|
845
|
+
if (key.return) {
|
|
846
|
+
const record = picker[sessionCursor];
|
|
847
|
+
if (record) {
|
|
848
|
+
setPhase('idle');
|
|
849
|
+
applyResume(record, '/resume');
|
|
850
|
+
// Stdin-path terminal action: nudge the render flush (Bun quirk).
|
|
851
|
+
dragFlush();
|
|
852
|
+
}
|
|
853
|
+
return;
|
|
854
|
+
}
|
|
855
|
+
if (key.upArrow) {
|
|
856
|
+
setSessionCursor(prev => (prev - 1 + picker.length) % picker.length);
|
|
857
|
+
return;
|
|
858
|
+
}
|
|
859
|
+
if (key.downArrow) {
|
|
860
|
+
setSessionCursor(prev => (prev + 1) % picker.length);
|
|
861
|
+
return;
|
|
862
|
+
}
|
|
863
|
+
return;
|
|
864
|
+
}
|
|
865
|
+
|
|
824
866
|
if (phase === 'model_pick') {
|
|
825
867
|
const total = pickOptions.length + 1; // + "自定义模型名…"
|
|
826
868
|
if (key.return) {
|
|
@@ -983,7 +1025,7 @@ export default function REPL({ ctx, updateNotice }: REPLProps) {
|
|
|
983
1025
|
)}
|
|
984
1026
|
{entry.output && (
|
|
985
1027
|
<Box marginLeft={2}>
|
|
986
|
-
<Text
|
|
1028
|
+
<Text>{entry.output}</Text>
|
|
987
1029
|
</Box>
|
|
988
1030
|
)}
|
|
989
1031
|
</Box>
|
|
@@ -1027,6 +1069,21 @@ export default function REPL({ ctx, updateNotice }: REPLProps) {
|
|
|
1027
1069
|
</Box>
|
|
1028
1070
|
)}
|
|
1029
1071
|
|
|
1072
|
+
{phase === 'session_select' && (
|
|
1073
|
+
<Box flexDirection="column" marginLeft={2}>
|
|
1074
|
+
<Text color="gray" dimColor>恢复对话 (↑↓ 选择 · Enter 恢复 · Esc 取消)</Text>
|
|
1075
|
+
{sessionPickerRef.current.map((session, i) => (
|
|
1076
|
+
<Box key={session.id}>
|
|
1077
|
+
<Text color={i === sessionCursor ? 'cyan' : undefined}>
|
|
1078
|
+
{i === sessionCursor ? '❯ ' : ' '}
|
|
1079
|
+
{i + 1}. {session.title} · {new Date(session.updatedAt).toLocaleString()} ·{' '}
|
|
1080
|
+
{session.model} · {session.messages.length} 条
|
|
1081
|
+
</Text>
|
|
1082
|
+
</Box>
|
|
1083
|
+
))}
|
|
1084
|
+
</Box>
|
|
1085
|
+
)}
|
|
1086
|
+
|
|
1030
1087
|
{phase === 'model_pick' && (
|
|
1031
1088
|
<Box flexDirection="column" marginLeft={2}>
|
|
1032
1089
|
{pendingModel === null && customBaseDraft && (
|
|
@@ -1061,11 +1118,15 @@ export default function REPL({ ctx, updateNotice }: REPLProps) {
|
|
|
1061
1118
|
</Box>
|
|
1062
1119
|
)}
|
|
1063
1120
|
|
|
1064
|
-
{phase !== 'model_select' && (
|
|
1065
|
-
<Box>
|
|
1066
|
-
<Text color={
|
|
1067
|
-
<
|
|
1068
|
-
|
|
1121
|
+
{phase !== 'model_select' && phase !== 'session_select' && (
|
|
1122
|
+
<Box flexDirection="column">
|
|
1123
|
+
<Text color="gray" dimColor>{historyRule(stdout?.columns ?? 80)}</Text>
|
|
1124
|
+
<Box>
|
|
1125
|
+
<Text color={phase === 'idle' ? 'green' : 'yellow'}>{promptLabel}</Text>
|
|
1126
|
+
<Text>{phase === 'model_apikey' ? '*'.repeat(input.length) : input}</Text>
|
|
1127
|
+
<Text color="gray">▎</Text>
|
|
1128
|
+
</Box>
|
|
1129
|
+
<Text color="gray" dimColor>{historyRule(stdout?.columns ?? 80)}</Text>
|
|
1069
1130
|
</Box>
|
|
1070
1131
|
)}
|
|
1071
1132
|
|
|
@@ -0,0 +1,92 @@
|
|
|
1
|
+
import { afterEach, beforeEach, describe, expect, test } from 'bun:test';
|
|
2
|
+
import { mkdtempSync, rmSync, writeFileSync } from 'node:fs';
|
|
3
|
+
import { tmpdir } from 'node:os';
|
|
4
|
+
import path from 'node:path';
|
|
5
|
+
import { HumanMessage } from '@langchain/core/messages';
|
|
6
|
+
import { saveSession, type SessionRecord } from './store.js';
|
|
7
|
+
import { listProjectSessions, resolveResumeTarget } from './resume.js';
|
|
8
|
+
|
|
9
|
+
let dir: string;
|
|
10
|
+
beforeEach(() => {
|
|
11
|
+
dir = mkdtempSync(path.join(tmpdir(), 'transcode-resume-test-'));
|
|
12
|
+
process.env.TRANSCODE_SESSIONS_DIR = dir;
|
|
13
|
+
});
|
|
14
|
+
afterEach(() => {
|
|
15
|
+
delete process.env.TRANSCODE_SESSIONS_DIR;
|
|
16
|
+
rmSync(dir, { recursive: true, force: true });
|
|
17
|
+
});
|
|
18
|
+
|
|
19
|
+
function sample(id: string, title: string, cwd: string): SessionRecord {
|
|
20
|
+
return {
|
|
21
|
+
id,
|
|
22
|
+
title,
|
|
23
|
+
createdAt: Date.now(),
|
|
24
|
+
updatedAt: Date.now(),
|
|
25
|
+
cwd,
|
|
26
|
+
model: 'deepseek',
|
|
27
|
+
messages: [new HumanMessage('body')],
|
|
28
|
+
};
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
/** Legacy pre-partitioning layout: flat file directly in the sessions root. */
|
|
32
|
+
function writeLegacyFlat(id: string, cwd: string): void {
|
|
33
|
+
writeFileSync(
|
|
34
|
+
path.join(dir, `${id}.json`),
|
|
35
|
+
JSON.stringify({
|
|
36
|
+
id,
|
|
37
|
+
title: `旧-${id}`,
|
|
38
|
+
createdAt: 1,
|
|
39
|
+
updatedAt: 1,
|
|
40
|
+
cwd,
|
|
41
|
+
model: 'deepseek',
|
|
42
|
+
messages: [{ type: 'human', content: 'legacy' }],
|
|
43
|
+
}),
|
|
44
|
+
);
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
describe('listProjectSessions', () => {
|
|
48
|
+
test('only returns sessions whose cwd matches; root-level flat files ignored', () => {
|
|
49
|
+
saveSession(sample('ses_a', '对话A', '/tmp/proj-a'));
|
|
50
|
+
saveSession(sample('ses_b', '对话B', '/tmp/proj-b'));
|
|
51
|
+
writeLegacyFlat('ses_legacy', '/tmp/proj-a');
|
|
52
|
+
|
|
53
|
+
const ids = listProjectSessions('/tmp/proj-a').map((s) => s.id).sort();
|
|
54
|
+
expect(ids).toEqual(['ses_a']);
|
|
55
|
+
});
|
|
56
|
+
|
|
57
|
+
test('empty project returns an empty list', () => {
|
|
58
|
+
saveSession(sample('ses_b', '对话B', '/tmp/proj-b'));
|
|
59
|
+
expect(listProjectSessions('/tmp/nowhere')).toEqual([]);
|
|
60
|
+
});
|
|
61
|
+
});
|
|
62
|
+
|
|
63
|
+
describe('resolveResumeTarget', () => {
|
|
64
|
+
const list: SessionRecord[] = [
|
|
65
|
+
{ ...sample('ses_1', '部署脚本', '/tmp/a'), updatedAt: 30 },
|
|
66
|
+
{ ...sample('ses_2', 'README更新', '/tmp/a'), updatedAt: 20 },
|
|
67
|
+
{ ...sample('ses_3', '闲聊', '/tmp/a'), updatedAt: 10 },
|
|
68
|
+
];
|
|
69
|
+
|
|
70
|
+
test('numeric resolves through lastIds first, then falls back to list index', () => {
|
|
71
|
+
expect(resolveResumeTarget('2', ['x1', 'ses_3'], list)?.id).toBe('ses_3');
|
|
72
|
+
expect(resolveResumeTarget('1', [], list)?.id).toBe('ses_1');
|
|
73
|
+
});
|
|
74
|
+
|
|
75
|
+
test('numeric out of range returns undefined', () => {
|
|
76
|
+
expect(resolveResumeTarget('99', [], list)).toBeUndefined();
|
|
77
|
+
});
|
|
78
|
+
|
|
79
|
+
test('exact id beats substring; id and title substrings both match', () => {
|
|
80
|
+
expect(resolveResumeTarget('ses_1', [], list)?.id).toBe('ses_1');
|
|
81
|
+
expect(resolveResumeTarget('README', [], list)?.id).toBe('ses_2');
|
|
82
|
+
expect(resolveResumeTarget('ses_', [], list)?.id).toBe('ses_1');
|
|
83
|
+
});
|
|
84
|
+
|
|
85
|
+
test('blank target returns undefined (caller opens the picker)', () => {
|
|
86
|
+
expect(resolveResumeTarget(' ', [], list)).toBeUndefined();
|
|
87
|
+
});
|
|
88
|
+
|
|
89
|
+
test('unmatched target returns undefined', () => {
|
|
90
|
+
expect(resolveResumeTarget('不存在', [], list)).toBeUndefined();
|
|
91
|
+
});
|
|
92
|
+
});
|
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
import { listSessions, type SessionRecord } from './store.js';
|
|
2
|
+
|
|
3
|
+
/** Sessions whose recorded cwd matches, newest first (project-scoped picker source). */
|
|
4
|
+
export function listProjectSessions(cwd: string): SessionRecord[] {
|
|
5
|
+
return listSessions().filter((session) => session.cwd === cwd);
|
|
6
|
+
}
|
|
7
|
+
|
|
8
|
+
/**
|
|
9
|
+
* Resolve a /resume argument to a session record.
|
|
10
|
+
* Blank target → undefined (caller opens the picker). Numeric → the last
|
|
11
|
+
* listed session at that index (falling back to list order). Otherwise
|
|
12
|
+
* exact id first, then id/title substring match. Undefined → not found.
|
|
13
|
+
*/
|
|
14
|
+
export function resolveResumeTarget(
|
|
15
|
+
target: string,
|
|
16
|
+
lastIds: string[],
|
|
17
|
+
list: SessionRecord[],
|
|
18
|
+
): SessionRecord | undefined {
|
|
19
|
+
const query = target.trim();
|
|
20
|
+
if (!query) return undefined;
|
|
21
|
+
if (/^\d+$/.test(query)) {
|
|
22
|
+
const index = Number(query) - 1;
|
|
23
|
+
const viaLast = lastIds[index];
|
|
24
|
+
if (viaLast) {
|
|
25
|
+
const record = list.find((session) => session.id === viaLast);
|
|
26
|
+
if (record) return record;
|
|
27
|
+
}
|
|
28
|
+
return list[index];
|
|
29
|
+
}
|
|
30
|
+
return (
|
|
31
|
+
list.find((session) => session.id === query) ??
|
|
32
|
+
list.find((session) => session.id.includes(query) || session.title.includes(query))
|
|
33
|
+
);
|
|
34
|
+
}
|
|
@@ -1,11 +1,13 @@
|
|
|
1
|
-
import { afterEach, beforeEach, describe, expect, test } from 'bun:test';
|
|
2
|
-
import
|
|
1
|
+
import { afterEach, beforeEach, describe, expect, spyOn, test } from 'bun:test';
|
|
2
|
+
import fs from 'node:fs';
|
|
3
|
+
import { existsSync, mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs';
|
|
3
4
|
import { tmpdir } from 'node:os';
|
|
4
5
|
import path from 'node:path';
|
|
5
6
|
import { AIMessage, HumanMessage, SystemMessage, ToolMessage } from '@langchain/core/messages';
|
|
6
7
|
import {
|
|
7
8
|
getSession,
|
|
8
9
|
listSessions,
|
|
10
|
+
newSessionId,
|
|
9
11
|
saveSession,
|
|
10
12
|
searchSessions,
|
|
11
13
|
type SessionRecord,
|
|
@@ -43,6 +45,15 @@ function sample(title: string, body: string): SessionRecord {
|
|
|
43
45
|
}
|
|
44
46
|
|
|
45
47
|
describe('session store', () => {
|
|
48
|
+
test('newSessionId generates unique UUID v4 ids (Claude Code style)', () => {
|
|
49
|
+
const uuidV4 = /^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/;
|
|
50
|
+
const a = newSessionId();
|
|
51
|
+
const b = newSessionId();
|
|
52
|
+
expect(a).toMatch(uuidV4);
|
|
53
|
+
expect(b).toMatch(uuidV4);
|
|
54
|
+
expect(a).not.toBe(b);
|
|
55
|
+
});
|
|
56
|
+
|
|
46
57
|
test('save + list roundtrips with metadata', () => {
|
|
47
58
|
saveSession(sample('更新 README', '帮我更新这个仓库的 README'));
|
|
48
59
|
|
|
@@ -78,6 +89,53 @@ describe('session store', () => {
|
|
|
78
89
|
expect(byBody.map((s) => s.id)).toEqual(['ses_test2']);
|
|
79
90
|
});
|
|
80
91
|
|
|
92
|
+
test('saves each conversation under a per-cwd subdirectory', () => {
|
|
93
|
+
saveSession({ ...sample('分区存储', 'x'), cwd: '/tmp/proj-a' });
|
|
94
|
+
|
|
95
|
+
expect(existsSync(path.join(dir, '-tmp-proj-a', 'ses_test1.json'))).toBe(true);
|
|
96
|
+
expect(getSession('ses_test1')?.title).toBe('分区存储');
|
|
97
|
+
});
|
|
98
|
+
|
|
99
|
+
test('lists sessions from multiple project directories together', () => {
|
|
100
|
+
saveSession({ ...sample('对话 A', 'a'), id: 'ses_a', cwd: '/tmp/proj-a' });
|
|
101
|
+
saveSession({ ...sample('对话 B', 'b'), id: 'ses_b', cwd: '/tmp/proj-b' });
|
|
102
|
+
|
|
103
|
+
expect(listSessions().map((s) => s.id).sort()).toEqual(['ses_a', 'ses_b']);
|
|
104
|
+
});
|
|
105
|
+
|
|
106
|
+
test('ignores root-level flat json files (legacy layout unsupported)', () => {
|
|
107
|
+
mkdirSync(dir, { recursive: true });
|
|
108
|
+
writeFileSync(
|
|
109
|
+
path.join(dir, 'ses_legacy.json'),
|
|
110
|
+
JSON.stringify({
|
|
111
|
+
id: 'ses_legacy',
|
|
112
|
+
title: '旧格式会话',
|
|
113
|
+
createdAt: 1,
|
|
114
|
+
updatedAt: 1,
|
|
115
|
+
cwd: '/other',
|
|
116
|
+
model: 'deepseek',
|
|
117
|
+
messages: [{ type: 'human', content: 'legacy body' }],
|
|
118
|
+
}),
|
|
119
|
+
);
|
|
120
|
+
|
|
121
|
+
expect(listSessions().map((s) => s.id)).not.toContain('ses_legacy');
|
|
122
|
+
expect(getSession('ses_legacy')).toBeUndefined();
|
|
123
|
+
});
|
|
124
|
+
|
|
125
|
+
test('failed save leaves the previous session file intact', () => {
|
|
126
|
+
saveSession(sample('旧内容', 'x'));
|
|
127
|
+
const spy = spyOn(fs, 'renameSync').mockImplementation(() => {
|
|
128
|
+
throw new Error('EIO');
|
|
129
|
+
});
|
|
130
|
+
try {
|
|
131
|
+
expect(() => saveSession(sample('新内容', 'y'))).toThrow('EIO');
|
|
132
|
+
} finally {
|
|
133
|
+
spy.mockRestore();
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
expect(getSession('ses_test1')?.title).toBe('旧内容');
|
|
137
|
+
});
|
|
138
|
+
|
|
81
139
|
test('list is ordered newest first', () => {
|
|
82
140
|
const older = sample('旧对话', 'a');
|
|
83
141
|
older.createdAt = Date.now() - 10_000;
|
package/src/sessions/store.ts
CHANGED
|
@@ -1,4 +1,5 @@
|
|
|
1
|
-
import
|
|
1
|
+
import fs from 'node:fs';
|
|
2
|
+
import { randomUUID } from 'node:crypto';
|
|
2
3
|
import { homedir } from 'node:os';
|
|
3
4
|
import path from 'node:path';
|
|
4
5
|
import {
|
|
@@ -33,6 +34,14 @@ interface StoredMessage {
|
|
|
33
34
|
const sessionsDir = (): string =>
|
|
34
35
|
process.env.TRANSCODE_SESSIONS_DIR ?? path.join(homedir(), '.transcode', 'sessions');
|
|
35
36
|
|
|
37
|
+
/** Project subdirectory name (Claude Code style: "/a/b" -> "-a-b"). */
|
|
38
|
+
const projectDir = (cwd: string): string => cwd.split(path.sep).join('-');
|
|
39
|
+
|
|
40
|
+
/** Fresh conversation id: bare UUID v4, like Claude Code session files. */
|
|
41
|
+
export function newSessionId(): string {
|
|
42
|
+
return randomUUID();
|
|
43
|
+
}
|
|
44
|
+
|
|
36
45
|
function serialize(messages: BaseMessage[]): StoredMessage[] {
|
|
37
46
|
return messages.map((message) => {
|
|
38
47
|
const stored: StoredMessage = { type: message.getType(), content: message.content };
|
|
@@ -72,7 +81,10 @@ function deserialize(stored: StoredMessage[]): BaseMessage[] {
|
|
|
72
81
|
|
|
73
82
|
function readRecord(file: string): SessionRecord | null {
|
|
74
83
|
try {
|
|
75
|
-
const parsed = JSON.parse(readFileSync(file, 'utf8')) as Omit<
|
|
84
|
+
const parsed = JSON.parse(fs.readFileSync(file, 'utf8')) as Omit<
|
|
85
|
+
SessionRecord,
|
|
86
|
+
'messages'
|
|
87
|
+
> & {
|
|
76
88
|
messages: StoredMessage[];
|
|
77
89
|
};
|
|
78
90
|
return { ...parsed, messages: deserialize(parsed.messages ?? []) };
|
|
@@ -82,28 +94,56 @@ function readRecord(file: string): SessionRecord | null {
|
|
|
82
94
|
}
|
|
83
95
|
|
|
84
96
|
export function saveSession(record: SessionRecord): void {
|
|
85
|
-
const dir = sessionsDir();
|
|
86
|
-
mkdirSync(dir, { recursive: true });
|
|
87
|
-
|
|
88
|
-
|
|
97
|
+
const dir = path.join(sessionsDir(), projectDir(record.cwd));
|
|
98
|
+
fs.mkdirSync(dir, { recursive: true });
|
|
99
|
+
const target = path.join(dir, `${record.id}.json`);
|
|
100
|
+
const tmp = `${target}.tmp`;
|
|
101
|
+
fs.writeFileSync(
|
|
102
|
+
tmp,
|
|
89
103
|
JSON.stringify({ ...record, messages: serialize(record.messages) }, null, 2),
|
|
90
104
|
);
|
|
105
|
+
try {
|
|
106
|
+
// Atomic replace: a crash mid-write can never truncate the previous session.
|
|
107
|
+
fs.renameSync(tmp, target);
|
|
108
|
+
} catch (error) {
|
|
109
|
+
try {
|
|
110
|
+
fs.rmSync(tmp, { force: true });
|
|
111
|
+
} catch {
|
|
112
|
+
// Best-effort cleanup; the original error matters more.
|
|
113
|
+
}
|
|
114
|
+
throw error;
|
|
115
|
+
}
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
/** All session files, one per-project subdirectory each. */
|
|
119
|
+
function sessionFiles(): string[] {
|
|
120
|
+
const root = sessionsDir();
|
|
121
|
+
if (!fs.existsSync(root)) return [];
|
|
122
|
+
const files: string[] = [];
|
|
123
|
+
for (const entry of fs.readdirSync(root, { withFileTypes: true })) {
|
|
124
|
+
if (!entry.isDirectory()) continue;
|
|
125
|
+
for (const file of fs.readdirSync(path.join(root, entry.name))) {
|
|
126
|
+
if (file.endsWith('.json')) files.push(path.join(root, entry.name, file));
|
|
127
|
+
}
|
|
128
|
+
}
|
|
129
|
+
return files;
|
|
91
130
|
}
|
|
92
131
|
|
|
93
132
|
/** All conversations, newest first. */
|
|
94
133
|
export function listSessions(): SessionRecord[] {
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
return readdirSync(dir)
|
|
98
|
-
.filter((file) => file.endsWith('.json'))
|
|
99
|
-
.map((file) => readRecord(path.join(dir, file)))
|
|
134
|
+
return sessionFiles()
|
|
135
|
+
.map((file) => readRecord(file))
|
|
100
136
|
.filter((record): record is SessionRecord => record !== null)
|
|
101
137
|
.sort((a, b) => b.updatedAt - a.updatedAt);
|
|
102
138
|
}
|
|
103
139
|
|
|
104
140
|
export function getSession(id: string): SessionRecord | undefined {
|
|
105
|
-
const
|
|
106
|
-
|
|
141
|
+
for (const file of sessionFiles()) {
|
|
142
|
+
if (path.basename(file) !== `${id}.json`) continue;
|
|
143
|
+
const record = readRecord(file);
|
|
144
|
+
if (record) return record;
|
|
145
|
+
}
|
|
146
|
+
return undefined;
|
|
107
147
|
}
|
|
108
148
|
|
|
109
149
|
/** Keyword search over titles AND message content (case-insensitive). */
|
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.
|
|
2
|
+
export const VERSION = '0.7.0';
|