ai-agent-session-manager 0.0.0-stage → 0.1.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/LICENSE +21 -0
- package/README.md +61 -2
- package/config.json +7 -0
- package/package.json +35 -3
- package/pic//346/225/210/346/236/234.jpg +0 -0
- package/src/index.js +824 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 qinyun233
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
CHANGED
|
@@ -1,3 +1,62 @@
|
|
|
1
|
-
#
|
|
1
|
+
# ai-agent-session-manager
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
使用 Node.js 实现的终端 TUI,用于管理 AI Agent 的会话记录:列出本机已有的会话,选中后直接恢复继续。
|
|
4
|
+
|
|
5
|
+
目前只实现了 Windows 下 Claude Code 的会话管理,其他 agent(如 Codex)尚未接入。
|
|
6
|
+
|
|
7
|
+

|
|
8
|
+
|
|
9
|
+
## 环境
|
|
10
|
+
|
|
11
|
+
- Node.js 18 及以上
|
|
12
|
+
- Windows 10/11 + Windows Terminal(鼠标点击需要终端支持 SGR 鼠标协议,旧版 conhost 只能用键盘)
|
|
13
|
+
- 已安装 Claude Code CLI,`claude` 命令在 PATH 中
|
|
14
|
+
|
|
15
|
+
## 安装
|
|
16
|
+
|
|
17
|
+
```powershell
|
|
18
|
+
npm install -g ai-agent-session-manager
|
|
19
|
+
```
|
|
20
|
+
|
|
21
|
+
安装后运行 `agent-sm` 启动。
|
|
22
|
+
|
|
23
|
+
也可以从源码运行:
|
|
24
|
+
|
|
25
|
+
```powershell
|
|
26
|
+
git clone https://github.com/qinyun233/ai-agent-session-manager.git
|
|
27
|
+
cd ai-agent-session-manager
|
|
28
|
+
npm start
|
|
29
|
+
```
|
|
30
|
+
|
|
31
|
+
## 使用
|
|
32
|
+
|
|
33
|
+
启动后显示会话列表,按修改时间倒序,最新的在最前面。
|
|
34
|
+
|
|
35
|
+
- 项目名后的圆点:绿色 = 该会话的 claude 进程仍在运行,红色 = 已结束
|
|
36
|
+
- 点击表头(项目 / 工作目录 / 更新时间 / 会话):按该列排序,再点一次切换正序/倒序
|
|
37
|
+
- 单击选中,双击或 Enter 打开会话;会话结束后自动回到列表
|
|
38
|
+
- 滚轮滚动,↑↓ 移动,输入关键字按项目名、路径、会话 id 过滤,Esc 退出
|
|
39
|
+
|
|
40
|
+
## 配置
|
|
41
|
+
|
|
42
|
+
配置文件为项目根目录的 `config.json`,也可用 `--config <path>` 或环境变量 `CLAUDE_SESSION_MANAGER_CONFIG` 指定。
|
|
43
|
+
|
|
44
|
+
| 配置项 | 说明 | 默认值 |
|
|
45
|
+
| --- | --- | --- |
|
|
46
|
+
| `projectsDir` | Claude 会话记录目录,支持 `~` | `~/.claude/projects` |
|
|
47
|
+
| `sessionsDir` | 运行中会话的状态目录,支持 `~` | `~/.claude/sessions` |
|
|
48
|
+
| `command` | 恢复会话的命令模板,必须包含 `{sessionId}` | `claude --resume {sessionId}` |
|
|
49
|
+
| `sort` | 初始排序:`time` / `name` / `path` / `id` | `time` |
|
|
50
|
+
| `order` | 排序方向:`asc` / `desc` | 时间 `desc`,其余 `asc` |
|
|
51
|
+
|
|
52
|
+
命令模板另支持 `{cwd}`、`{projectDir}`、`{projectName}` 占位符,路径类会自动加引号。命令会在会话的工作目录下执行,因此换成其他 agent 只需改这一项。
|
|
53
|
+
|
|
54
|
+
## 工作流程
|
|
55
|
+
|
|
56
|
+
1. 启动时读取 `config.json`,确定会话目录、状态目录和恢复命令。
|
|
57
|
+
2. 扫描 `projectsDir`:每个 `<uuid>.jsonl` 文件就是一个会话,文件名即会话 id,同时记录文件修改时间。
|
|
58
|
+
3. 逐个打开会话文件,只读到第一个 `cwd` 字段就停止,得到会话的真实工作目录(项目文件夹名是有损编码,无法反推路径)。
|
|
59
|
+
4. 读取 `sessionsDir` 下按 PID 命名的状态文件,确认 PID 存在、且进程名是 claude,标记该会话为运行中。
|
|
60
|
+
5. 按配置排序并渲染列表,支持输入关键字实时过滤;界面每 2 秒刷新一次存活状态。
|
|
61
|
+
6. 选中会话后退出 TUI,在该会话的工作目录下执行 `command`(默认 `claude --resume <会话id>`),把终端交给 claude。
|
|
62
|
+
7. claude 退出后重新扫描目录,回到列表,可以继续选择下一个会话。
|
package/config.json
ADDED
package/package.json
CHANGED
|
@@ -1,6 +1,38 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "ai-agent-session-manager",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
3
|
+
"version": "0.1.0",
|
|
4
|
+
"description": "Node.js TUI for managing AI agent sessions (Claude Code on Windows)",
|
|
5
|
+
"type": "module",
|
|
6
|
+
"bin": {
|
|
7
|
+
"agent-sm": "src/index.js"
|
|
8
|
+
},
|
|
9
|
+
"files": [
|
|
10
|
+
"src",
|
|
11
|
+
"config.json",
|
|
12
|
+
"pic"
|
|
13
|
+
],
|
|
14
|
+
"engines": {
|
|
15
|
+
"node": ">=18"
|
|
16
|
+
},
|
|
17
|
+
"scripts": {
|
|
18
|
+
"start": "node src/index.js",
|
|
19
|
+
"list": "node src/index.js --list"
|
|
20
|
+
},
|
|
21
|
+
"keywords": [
|
|
22
|
+
"claude-code",
|
|
23
|
+
"tui",
|
|
24
|
+
"session",
|
|
25
|
+
"agent",
|
|
26
|
+
"cli"
|
|
27
|
+
],
|
|
28
|
+
"author": "qinyun233 <1565604772@qq.com>",
|
|
29
|
+
"license": "MIT",
|
|
30
|
+
"repository": {
|
|
31
|
+
"type": "git",
|
|
32
|
+
"url": "git+https://github.com/qinyun233/ai-agent-session-manager.git"
|
|
33
|
+
},
|
|
34
|
+
"homepage": "https://github.com/qinyun233/ai-agent-session-manager#readme",
|
|
35
|
+
"bugs": {
|
|
36
|
+
"url": "https://github.com/qinyun233/ai-agent-session-manager/issues"
|
|
37
|
+
}
|
|
6
38
|
}
|
|
Binary file
|
package/src/index.js
ADDED
|
@@ -0,0 +1,824 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
import fs from 'node:fs';
|
|
3
|
+
import fsp from 'node:fs/promises';
|
|
4
|
+
import os from 'node:os';
|
|
5
|
+
import path from 'node:path';
|
|
6
|
+
import { spawn, execFile } from 'node:child_process';
|
|
7
|
+
import { StringDecoder } from 'node:string_decoder';
|
|
8
|
+
import { fileURLToPath } from 'node:url';
|
|
9
|
+
import { promisify } from 'node:util';
|
|
10
|
+
|
|
11
|
+
const execFileAsync = promisify(execFile);
|
|
12
|
+
|
|
13
|
+
const ROOT = path.dirname(path.dirname(fileURLToPath(import.meta.url)));
|
|
14
|
+
|
|
15
|
+
const DEFAULT_CONFIG = {
|
|
16
|
+
projectsDir: '~/.claude/projects',
|
|
17
|
+
sessionsDir: '~/.claude/sessions',
|
|
18
|
+
command: 'claude --resume {sessionId}',
|
|
19
|
+
sort: 'time',
|
|
20
|
+
order: null,
|
|
21
|
+
};
|
|
22
|
+
|
|
23
|
+
const SORT_MODES = ['time', 'name', 'path', 'id'];
|
|
24
|
+
const COLUMNS = [
|
|
25
|
+
{ key: 'name', label: '项目', width: 20 },
|
|
26
|
+
{ key: 'path', label: '工作目录', flex: true },
|
|
27
|
+
{ key: 'time', label: '更新时间', width: 10 },
|
|
28
|
+
{ key: 'id', label: '会话', width: 8 },
|
|
29
|
+
];
|
|
30
|
+
const LEFT = 1;
|
|
31
|
+
const GAP = 2;
|
|
32
|
+
const LIST_START = 4;
|
|
33
|
+
|
|
34
|
+
function parseArgs(argv) {
|
|
35
|
+
const args = { list: false, json: false, help: false, config: null, open: null, sort: null, order: null };
|
|
36
|
+
for (let i = 0; i < argv.length; i++) {
|
|
37
|
+
const a = argv[i];
|
|
38
|
+
if (a === '--list') args.list = true;
|
|
39
|
+
else if (a === '--json') args.json = true;
|
|
40
|
+
else if (a === '--help' || a === '-h') args.help = true;
|
|
41
|
+
else if (a === '--sort') args.sort = argv[++i] ?? null;
|
|
42
|
+
else if (a.startsWith('--sort=')) args.sort = a.slice('--sort='.length);
|
|
43
|
+
else if (a === '--order') args.order = argv[++i] ?? null;
|
|
44
|
+
else if (a.startsWith('--order=')) args.order = a.slice('--order='.length);
|
|
45
|
+
else if (a === '--open') args.open = argv[++i] ?? null;
|
|
46
|
+
else if (a.startsWith('--open=')) args.open = a.slice('--open='.length);
|
|
47
|
+
else if (a === '--config') args.config = argv[++i] ?? null;
|
|
48
|
+
else if (a.startsWith('--config=')) args.config = a.slice('--config='.length);
|
|
49
|
+
else console.warn(`忽略未知参数: ${a}`);
|
|
50
|
+
}
|
|
51
|
+
return args;
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
function expandHome(p) {
|
|
55
|
+
if (p === '~') return os.homedir();
|
|
56
|
+
if (p.startsWith('~/') || p.startsWith('~\\')) return path.join(os.homedir(), p.slice(2));
|
|
57
|
+
return p;
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
async function loadConfig(configPath) {
|
|
61
|
+
const file = configPath
|
|
62
|
+
?? process.env.CLAUDE_SESSION_MANAGER_CONFIG
|
|
63
|
+
?? path.join(ROOT, 'config.json');
|
|
64
|
+
let user = {};
|
|
65
|
+
try {
|
|
66
|
+
user = JSON.parse(await fsp.readFile(file, 'utf8'));
|
|
67
|
+
} catch (err) {
|
|
68
|
+
if (err.code !== 'ENOENT') throw new Error(`读取配置文件失败 ${file}: ${err.message}`);
|
|
69
|
+
console.warn(`未找到配置文件 ${file},使用默认配置`);
|
|
70
|
+
}
|
|
71
|
+
const cfg = { ...DEFAULT_CONFIG, ...user };
|
|
72
|
+
const base = path.dirname(path.resolve(file));
|
|
73
|
+
cfg.projectsDir = path.resolve(base, expandHome(String(cfg.projectsDir)));
|
|
74
|
+
cfg.sessionsDir = path.resolve(base, expandHome(String(cfg.sessionsDir ?? DEFAULT_CONFIG.sessionsDir)));
|
|
75
|
+
if (!String(cfg.command).includes('{sessionId}')) {
|
|
76
|
+
throw new Error('config.command 缺少 {sessionId} 占位符,无法继续会话');
|
|
77
|
+
}
|
|
78
|
+
const sort = normalizeSort(cfg.sort, cfg.order);
|
|
79
|
+
cfg.sort = sort.mode;
|
|
80
|
+
cfg.order = sort.order;
|
|
81
|
+
return cfg;
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
function normalizeSort(mode, order) {
|
|
85
|
+
const m = String(mode ?? 'time').toLowerCase();
|
|
86
|
+
if (!SORT_MODES.includes(m)) throw new Error(`排序方式只能是 ${SORT_MODES.join('/')},收到 "${mode}"`);
|
|
87
|
+
const o = order == null ? null : String(order).toLowerCase();
|
|
88
|
+
if (o != null && o !== 'asc' && o !== 'desc') throw new Error(`排序方向只能是 asc/desc,收到 "${order}"`);
|
|
89
|
+
return { mode: m, order: o ?? (m === 'time' ? 'desc' : 'asc') };
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
function sortLabel({ mode, order }) {
|
|
93
|
+
const name = { time: '按日期', name: '按名称', path: '按路径', id: '按会话' }[mode];
|
|
94
|
+
return `${name}${order === 'asc' ? '↑' : '↓'}`;
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
const collator = new Intl.Collator(undefined, { numeric: true, sensitivity: 'base' });
|
|
98
|
+
|
|
99
|
+
function sortSessions(sessions, { mode, order }) {
|
|
100
|
+
const sign = order === 'asc' ? 1 : -1;
|
|
101
|
+
const key = {
|
|
102
|
+
time: (s) => s.mtimeMs,
|
|
103
|
+
name: (s) => s.projectName,
|
|
104
|
+
path: (s) => s.cwd ?? '',
|
|
105
|
+
id: (s) => s.id,
|
|
106
|
+
}[mode];
|
|
107
|
+
return [...sessions].sort((a, b) => {
|
|
108
|
+
const ka = key(a);
|
|
109
|
+
const kb = key(b);
|
|
110
|
+
let r;
|
|
111
|
+
if (typeof ka === 'number') r = ka - kb;
|
|
112
|
+
else if (mode === 'id') r = ka.localeCompare(kb);
|
|
113
|
+
else r = collator.compare(ka, kb);
|
|
114
|
+
return r * sign || a.id.localeCompare(b.id);
|
|
115
|
+
});
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
function safeParse(line) {
|
|
119
|
+
try {
|
|
120
|
+
return JSON.parse(line);
|
|
121
|
+
} catch {
|
|
122
|
+
return null;
|
|
123
|
+
}
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
// 只取第一个 cwd 字段,找到即停止,不读会话其余内容
|
|
127
|
+
async function readSessionCwd(file) {
|
|
128
|
+
let handle;
|
|
129
|
+
const decoder = new StringDecoder('utf8');
|
|
130
|
+
try {
|
|
131
|
+
handle = await fsp.open(file, 'r');
|
|
132
|
+
const chunkSize = 16 * 1024;
|
|
133
|
+
const buf = Buffer.alloc(chunkSize);
|
|
134
|
+
let offset = 0;
|
|
135
|
+
let leftover = '';
|
|
136
|
+
while (offset < 1024 * 1024) {
|
|
137
|
+
const { bytesRead } = await handle.read(buf, 0, chunkSize, offset);
|
|
138
|
+
if (!bytesRead) break;
|
|
139
|
+
offset += bytesRead;
|
|
140
|
+
const lines = (leftover + decoder.write(buf.subarray(0, bytesRead))).split('\n');
|
|
141
|
+
leftover = lines.pop() ?? '';
|
|
142
|
+
for (const line of lines) {
|
|
143
|
+
const rec = safeParse(line);
|
|
144
|
+
if (rec && typeof rec.cwd === 'string' && rec.cwd) return rec.cwd;
|
|
145
|
+
}
|
|
146
|
+
}
|
|
147
|
+
return null;
|
|
148
|
+
} finally {
|
|
149
|
+
await handle?.close();
|
|
150
|
+
}
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
// sessions 目录下是 <pid>.json 状态文件,进程还在就视为存活
|
|
154
|
+
function isPidAlive(pid) {
|
|
155
|
+
try {
|
|
156
|
+
process.kill(pid, 0);
|
|
157
|
+
return true;
|
|
158
|
+
} catch (err) {
|
|
159
|
+
return err.code === 'EPERM';
|
|
160
|
+
}
|
|
161
|
+
}
|
|
162
|
+
|
|
163
|
+
function isClaudeProcess(name) {
|
|
164
|
+
return typeof name === 'string' && name.toLowerCase().includes('claude');
|
|
165
|
+
}
|
|
166
|
+
|
|
167
|
+
// tasklist 一次拿到所有进程名,用于确认 PID 确实是 claude 进程(防 PID 复用)
|
|
168
|
+
async function getProcessNames() {
|
|
169
|
+
if (process.platform !== 'win32') return null;
|
|
170
|
+
try {
|
|
171
|
+
const { stdout } = await execFileAsync('tasklist', ['/FO', 'CSV', '/NH'], {
|
|
172
|
+
windowsHide: true,
|
|
173
|
+
maxBuffer: 8 * 1024 * 1024,
|
|
174
|
+
encoding: 'utf8',
|
|
175
|
+
});
|
|
176
|
+
const map = new Map();
|
|
177
|
+
for (const line of stdout.split(/\r?\n/)) {
|
|
178
|
+
const m = line.match(/^"([^"]*)","(\d+)"/);
|
|
179
|
+
if (m) map.set(Number(m[2]), m[1].toLowerCase());
|
|
180
|
+
}
|
|
181
|
+
return map;
|
|
182
|
+
} catch {
|
|
183
|
+
return null;
|
|
184
|
+
}
|
|
185
|
+
}
|
|
186
|
+
|
|
187
|
+
async function readAliveSessionIds(sessionsDir) {
|
|
188
|
+
const ids = new Set();
|
|
189
|
+
let files;
|
|
190
|
+
try {
|
|
191
|
+
files = (await fsp.readdir(sessionsDir)).filter((n) => n.endsWith('.json'));
|
|
192
|
+
} catch {
|
|
193
|
+
return ids;
|
|
194
|
+
}
|
|
195
|
+
if (!files.length) return ids;
|
|
196
|
+
|
|
197
|
+
const [states, procNames] = await Promise.all([
|
|
198
|
+
Promise.all(files.map(async (n) => {
|
|
199
|
+
try {
|
|
200
|
+
return JSON.parse(await fsp.readFile(path.join(sessionsDir, n), 'utf8'));
|
|
201
|
+
} catch {
|
|
202
|
+
return null; // 单个状态文件损坏就跳过
|
|
203
|
+
}
|
|
204
|
+
})),
|
|
205
|
+
getProcessNames(),
|
|
206
|
+
]);
|
|
207
|
+
|
|
208
|
+
for (const data of states) {
|
|
209
|
+
if (!data || typeof data.pid !== 'number' || !data.sessionId) continue;
|
|
210
|
+
if (!isPidAlive(data.pid)) continue;
|
|
211
|
+
if (procNames && !isClaudeProcess(procNames.get(data.pid))) continue;
|
|
212
|
+
ids.add(String(data.sessionId).toLowerCase());
|
|
213
|
+
}
|
|
214
|
+
return ids;
|
|
215
|
+
}
|
|
216
|
+
|
|
217
|
+
async function applyAliveStatus(sessions, sessionsDir) {
|
|
218
|
+
const ids = await readAliveSessionIds(sessionsDir);
|
|
219
|
+
let changed = false;
|
|
220
|
+
for (const s of sessions) {
|
|
221
|
+
const alive = ids.has(s.id.toLowerCase());
|
|
222
|
+
if (s.alive !== alive) changed = true;
|
|
223
|
+
s.alive = alive;
|
|
224
|
+
}
|
|
225
|
+
return changed;
|
|
226
|
+
}
|
|
227
|
+
|
|
228
|
+
async function mapLimit(items, limit, fn) {
|
|
229
|
+
const out = new Array(items.length);
|
|
230
|
+
let next = 0;
|
|
231
|
+
const workers = Array.from({ length: Math.min(limit, items.length) }, async () => {
|
|
232
|
+
while (true) {
|
|
233
|
+
const i = next++;
|
|
234
|
+
if (i >= items.length) return;
|
|
235
|
+
out[i] = await fn(items[i]);
|
|
236
|
+
}
|
|
237
|
+
});
|
|
238
|
+
await Promise.all(workers);
|
|
239
|
+
return out;
|
|
240
|
+
}
|
|
241
|
+
|
|
242
|
+
async function scanSessions(projectsDir) {
|
|
243
|
+
let projectDirs;
|
|
244
|
+
try {
|
|
245
|
+
projectDirs = (await fsp.readdir(projectsDir, { withFileTypes: true })).filter((e) => e.isDirectory());
|
|
246
|
+
} catch (err) {
|
|
247
|
+
throw new Error(`无法读取 projects 目录 ${projectsDir}: ${err.message}`);
|
|
248
|
+
}
|
|
249
|
+
|
|
250
|
+
const sessions = [];
|
|
251
|
+
for (const pd of projectDirs) {
|
|
252
|
+
const dir = path.join(projectsDir, pd.name);
|
|
253
|
+
let names;
|
|
254
|
+
try {
|
|
255
|
+
names = await fsp.readdir(dir);
|
|
256
|
+
} catch {
|
|
257
|
+
continue;
|
|
258
|
+
}
|
|
259
|
+
for (const name of names) {
|
|
260
|
+
if (!name.endsWith('.jsonl')) continue;
|
|
261
|
+
const file = path.join(dir, name);
|
|
262
|
+
try {
|
|
263
|
+
const st = await fsp.stat(file);
|
|
264
|
+
if (!st.isFile()) continue;
|
|
265
|
+
sessions.push({
|
|
266
|
+
id: name.slice(0, -'.jsonl'.length),
|
|
267
|
+
file,
|
|
268
|
+
projectDirName: pd.name,
|
|
269
|
+
mtimeMs: st.mtimeMs,
|
|
270
|
+
cwd: null,
|
|
271
|
+
});
|
|
272
|
+
} catch {
|
|
273
|
+
// 单个会话读不到就跳过
|
|
274
|
+
}
|
|
275
|
+
}
|
|
276
|
+
}
|
|
277
|
+
|
|
278
|
+
await mapLimit(sessions, 16, async (s) => {
|
|
279
|
+
s.cwd = await readSessionCwd(s.file);
|
|
280
|
+
s.projectName = s.cwd ? path.basename(s.cwd) : s.projectDirName;
|
|
281
|
+
});
|
|
282
|
+
|
|
283
|
+
return sessions;
|
|
284
|
+
}
|
|
285
|
+
|
|
286
|
+
function isWide(cp) {
|
|
287
|
+
return (
|
|
288
|
+
(cp >= 0x1100 && cp <= 0x115f) ||
|
|
289
|
+
(cp >= 0x2e80 && cp <= 0xa4cf) ||
|
|
290
|
+
(cp >= 0xac00 && cp <= 0xd7a3) ||
|
|
291
|
+
(cp >= 0xf900 && cp <= 0xfaff) ||
|
|
292
|
+
(cp >= 0xfe30 && cp <= 0xfe6f) ||
|
|
293
|
+
(cp >= 0xff00 && cp <= 0xff60) ||
|
|
294
|
+
(cp >= 0xffe0 && cp <= 0xffe6) ||
|
|
295
|
+
(cp >= 0x1f300 && cp <= 0x1f64f)
|
|
296
|
+
);
|
|
297
|
+
}
|
|
298
|
+
|
|
299
|
+
function strWidth(s) {
|
|
300
|
+
let w = 0;
|
|
301
|
+
for (const ch of s) w += isWide(ch.codePointAt(0)) ? 2 : 1;
|
|
302
|
+
return w;
|
|
303
|
+
}
|
|
304
|
+
|
|
305
|
+
function truncate(s, width) {
|
|
306
|
+
let w = 0;
|
|
307
|
+
let out = '';
|
|
308
|
+
for (const ch of s) {
|
|
309
|
+
const cw = isWide(ch.codePointAt(0)) ? 2 : 1;
|
|
310
|
+
if (w + cw > width) return w + 1 <= width ? out + '…' : out;
|
|
311
|
+
w += cw;
|
|
312
|
+
out += ch;
|
|
313
|
+
}
|
|
314
|
+
return out;
|
|
315
|
+
}
|
|
316
|
+
|
|
317
|
+
function padEndW(s, width) {
|
|
318
|
+
return s + ' '.repeat(Math.max(0, width - strWidth(s)));
|
|
319
|
+
}
|
|
320
|
+
|
|
321
|
+
function dim(s) {
|
|
322
|
+
return `\x1b[2m${s}\x1b[0m`;
|
|
323
|
+
}
|
|
324
|
+
|
|
325
|
+
function relTime(ms) {
|
|
326
|
+
const d = Date.now() - ms;
|
|
327
|
+
if (d < 60_000) return '刚刚';
|
|
328
|
+
if (d < 3_600_000) return `${Math.floor(d / 60_000)}分钟前`;
|
|
329
|
+
if (d < 86_400_000) return `${Math.floor(d / 3_600_000)}小时前`;
|
|
330
|
+
if (d < 30 * 86_400_000) return `${Math.floor(d / 86_400_000)}天前`;
|
|
331
|
+
return new Date(ms).toISOString().slice(5, 10).replace('-', '/');
|
|
332
|
+
}
|
|
333
|
+
|
|
334
|
+
function filterSessions(sessions, term) {
|
|
335
|
+
const q = String(term ?? '').trim().toLowerCase();
|
|
336
|
+
if (!q) return sessions;
|
|
337
|
+
const parts = q.split(/\s+/);
|
|
338
|
+
return sessions.filter((s) => {
|
|
339
|
+
const hay = `${s.projectName ?? ''} ${s.cwd ?? ''} ${s.id}`.toLowerCase();
|
|
340
|
+
return parts.every((p) => hay.includes(p));
|
|
341
|
+
});
|
|
342
|
+
}
|
|
343
|
+
|
|
344
|
+
function buildCommand(cfg, session, cwd) {
|
|
345
|
+
const values = {
|
|
346
|
+
sessionId: session.id,
|
|
347
|
+
cwd,
|
|
348
|
+
projectDir: path.dirname(session.file),
|
|
349
|
+
projectName: session.projectName ?? '',
|
|
350
|
+
};
|
|
351
|
+
return String(cfg.command).replace(/\{(\w+)\}/g, (m, key) => {
|
|
352
|
+
if (!(key in values)) return m;
|
|
353
|
+
const v = String(values[key]);
|
|
354
|
+
return key === 'sessionId' || key === 'projectName' ? v : `"${v}"`;
|
|
355
|
+
});
|
|
356
|
+
}
|
|
357
|
+
|
|
358
|
+
function launch(cfg, session) {
|
|
359
|
+
const cwd = session.cwd && fs.existsSync(session.cwd) ? session.cwd : null;
|
|
360
|
+
if (!cwd) {
|
|
361
|
+
console.warn(`警告: 会话工作目录不存在或未知 (${session.cwd ?? '未记录'}),将在 ${process.cwd()} 启动`);
|
|
362
|
+
}
|
|
363
|
+
const workDir = cwd ?? process.cwd();
|
|
364
|
+
const cmd = buildCommand(cfg, session, workDir);
|
|
365
|
+
console.log(dim(`> ${cmd} (cwd: ${workDir})`));
|
|
366
|
+
return new Promise((resolve) => {
|
|
367
|
+
const child = spawn(cmd, { cwd: workDir, stdio: 'inherit', shell: true, env: process.env });
|
|
368
|
+
child.on('error', (err) => {
|
|
369
|
+
console.error(`启动失败: ${err.message}`);
|
|
370
|
+
resolve(1);
|
|
371
|
+
});
|
|
372
|
+
child.on('exit', (code, signal) => {
|
|
373
|
+
if (signal) console.log(dim(`进程被信号 ${signal} 结束`));
|
|
374
|
+
resolve(code ?? 1);
|
|
375
|
+
});
|
|
376
|
+
});
|
|
377
|
+
}
|
|
378
|
+
|
|
379
|
+
function printPlain(sessions) {
|
|
380
|
+
console.log(['项目', '状态', '工作目录', '更新时间', '会话ID'].join('\t'));
|
|
381
|
+
for (const s of sessions) {
|
|
382
|
+
console.log([s.projectName, s.alive ? '存活' : '未运行', s.cwd ?? '(未知)', new Date(s.mtimeMs).toLocaleString(), s.id].join('\t'));
|
|
383
|
+
}
|
|
384
|
+
}
|
|
385
|
+
|
|
386
|
+
function printHelp() {
|
|
387
|
+
console.log(`用法: node src/index.js [选项]
|
|
388
|
+
|
|
389
|
+
选项:
|
|
390
|
+
--list 列出所有会话(纯文本,不进入交互界面)
|
|
391
|
+
--json 以 JSON 输出会话列表
|
|
392
|
+
--open <id前缀> 直接进入指定会话,不显示列表
|
|
393
|
+
--sort <mode> 排序方式: time | name | path | id(默认 time)
|
|
394
|
+
--order <dir> 排序方向: asc | desc(time 默认 desc,其余 asc)
|
|
395
|
+
--config <path> 指定配置文件(默认 ./config.json)
|
|
396
|
+
-h, --help 显示帮助
|
|
397
|
+
|
|
398
|
+
配置项 (config.json):
|
|
399
|
+
projectsDir Claude projects 目录,支持 ~,默认 ~/.claude/projects
|
|
400
|
+
sessionsDir 运行中会话的状态目录,支持 ~,默认 ~/.claude/sessions
|
|
401
|
+
command 继续会话的命令模板,占位符: {sessionId} {cwd} {projectDir} {projectName}
|
|
402
|
+
sort 排序方式: time | name | path | id
|
|
403
|
+
order 排序方向: asc | desc
|
|
404
|
+
|
|
405
|
+
交互界面:
|
|
406
|
+
点击表头 按该列排序,再次点击切换正序/倒序
|
|
407
|
+
↑↓ / 滚轮 移动 / 滚动
|
|
408
|
+
Enter / 双击 打开所选会话
|
|
409
|
+
Esc 退出
|
|
410
|
+
|
|
411
|
+
环境变量:
|
|
412
|
+
CLAUDE_SESSION_MANAGER_CONFIG 配置文件的替代路径`);
|
|
413
|
+
}
|
|
414
|
+
|
|
415
|
+
// ---------- 交互界面 ----------
|
|
416
|
+
|
|
417
|
+
function computeLayout(width) {
|
|
418
|
+
const fixed = COLUMNS.filter((c) => !c.flex).reduce((n, c) => n + c.width, 0);
|
|
419
|
+
const flexWidth = Math.max(10, width - LEFT - fixed - GAP * (COLUMNS.length - 1));
|
|
420
|
+
let x = LEFT;
|
|
421
|
+
const cells = COLUMNS.map((c) => {
|
|
422
|
+
const w = c.flex ? flexWidth : c.width;
|
|
423
|
+
const cell = { key: c.key, label: c.label, width: w, x };
|
|
424
|
+
x += w + GAP;
|
|
425
|
+
return cell;
|
|
426
|
+
});
|
|
427
|
+
return { cells };
|
|
428
|
+
}
|
|
429
|
+
|
|
430
|
+
function sessionCell(s, key) {
|
|
431
|
+
switch (key) {
|
|
432
|
+
case 'name': return s.projectName ?? '';
|
|
433
|
+
case 'path': return s.cwd ?? '(未知)';
|
|
434
|
+
case 'time': return relTime(s.mtimeMs);
|
|
435
|
+
case 'id': return s.id.slice(0, 8);
|
|
436
|
+
default: return '';
|
|
437
|
+
}
|
|
438
|
+
}
|
|
439
|
+
|
|
440
|
+
const RESET_FG = '\x1b[22;39m';
|
|
441
|
+
const SELECTED_BG = '\x1b[48;5;240m';
|
|
442
|
+
|
|
443
|
+
// 只复位前景色/亮度,保留选中行背景色
|
|
444
|
+
function fg(code, text) {
|
|
445
|
+
return `\x1b[${code}m${text}${RESET_FG}`;
|
|
446
|
+
}
|
|
447
|
+
|
|
448
|
+
function timeColor(ms) {
|
|
449
|
+
const age = Date.now() - ms;
|
|
450
|
+
if (age < 3_600_000) return 32;
|
|
451
|
+
if (age < 86_400_000) return 33;
|
|
452
|
+
return 2;
|
|
453
|
+
}
|
|
454
|
+
|
|
455
|
+
function renderHeader(cells, sort) {
|
|
456
|
+
const parts = cells.map((c) => {
|
|
457
|
+
const active = sort.mode === c.key;
|
|
458
|
+
const marker = active ? (sort.order === 'asc' ? ' ↑' : ' ↓') : '';
|
|
459
|
+
const text = padEndW(truncate(c.label + marker, c.width), c.width);
|
|
460
|
+
return active ? `\x1b[1m\x1b[36m${text}\x1b[0m` : `\x1b[1m${text}\x1b[0m`;
|
|
461
|
+
});
|
|
462
|
+
return ' '.repeat(LEFT) + parts.join(' '.repeat(GAP));
|
|
463
|
+
}
|
|
464
|
+
|
|
465
|
+
function renderRow(cells, s, selected, width) {
|
|
466
|
+
const parts = cells.map((c) => {
|
|
467
|
+
const raw = sessionCell(s, c.key);
|
|
468
|
+
if (c.key === 'name') {
|
|
469
|
+
const label = truncate(raw, Math.max(1, c.width - 2));
|
|
470
|
+
const pad = ' '.repeat(Math.max(0, c.width - strWidth(label) - 2));
|
|
471
|
+
return fg(36, label) + ' ' + fg(s.alive ? 32 : 31, '●') + pad;
|
|
472
|
+
}
|
|
473
|
+
const shown = truncate(raw, c.width);
|
|
474
|
+
const pad = ' '.repeat(Math.max(0, c.width - strWidth(shown)));
|
|
475
|
+
if (c.key === 'time') return fg(timeColor(s.mtimeMs), shown) + pad;
|
|
476
|
+
return fg(2, shown) + pad;
|
|
477
|
+
});
|
|
478
|
+
const used = LEFT + cells.reduce((n, c) => n + c.width, 0) + GAP * (cells.length - 1);
|
|
479
|
+
const line = ' '.repeat(LEFT) + parts.join(' '.repeat(GAP)) + ' '.repeat(Math.max(0, width - used));
|
|
480
|
+
return selected ? SELECTED_BG + line + '\x1b[0m' : line;
|
|
481
|
+
}
|
|
482
|
+
|
|
483
|
+
function runTui(cfg, initialSessions, initialSort) {
|
|
484
|
+
return new Promise((resolve) => {
|
|
485
|
+
let sessions = initialSessions;
|
|
486
|
+
let sort = initialSort;
|
|
487
|
+
let sorted = sortSessions(sessions, sort);
|
|
488
|
+
let query = '';
|
|
489
|
+
let filtered = sorted;
|
|
490
|
+
let cursor = 0;
|
|
491
|
+
let top = 0;
|
|
492
|
+
let viewH = 1;
|
|
493
|
+
let layout = computeLayout(100);
|
|
494
|
+
let busy = false;
|
|
495
|
+
let ended = false;
|
|
496
|
+
let attached = false;
|
|
497
|
+
let aliveRefreshing = false;
|
|
498
|
+
let aliveTimer = null;
|
|
499
|
+
let lastClick = { index: -1, at: 0 };
|
|
500
|
+
const decoder = new StringDecoder('utf8');
|
|
501
|
+
let pending = '';
|
|
502
|
+
let escTimer = null;
|
|
503
|
+
|
|
504
|
+
const enableScreen = () => process.stdout.write('\x1b[?1049h\x1b[?25l\x1b[?1000h\x1b[?1006h');
|
|
505
|
+
const disableScreen = () => process.stdout.write('\x1b[?1000l\x1b[?1006l\x1b[?25h\x1b[?1049l');
|
|
506
|
+
|
|
507
|
+
function attach() {
|
|
508
|
+
attached = true;
|
|
509
|
+
enableScreen();
|
|
510
|
+
process.stdout.on('resize', onResize);
|
|
511
|
+
process.stdin.setRawMode(true);
|
|
512
|
+
process.stdin.resume();
|
|
513
|
+
process.stdin.on('data', onData);
|
|
514
|
+
render();
|
|
515
|
+
}
|
|
516
|
+
|
|
517
|
+
function detach() {
|
|
518
|
+
attached = false;
|
|
519
|
+
process.stdin.removeListener('data', onData);
|
|
520
|
+
process.stdout.removeListener('resize', onResize);
|
|
521
|
+
try {
|
|
522
|
+
process.stdin.setRawMode(false);
|
|
523
|
+
} catch {
|
|
524
|
+
// 流已关闭时忽略
|
|
525
|
+
}
|
|
526
|
+
process.stdin.pause();
|
|
527
|
+
disableScreen();
|
|
528
|
+
}
|
|
529
|
+
|
|
530
|
+
function quit() {
|
|
531
|
+
if (ended) return;
|
|
532
|
+
ended = true;
|
|
533
|
+
if (escTimer) clearTimeout(escTimer);
|
|
534
|
+
clearInterval(aliveTimer);
|
|
535
|
+
detach();
|
|
536
|
+
resolve();
|
|
537
|
+
}
|
|
538
|
+
|
|
539
|
+
async function refreshAlive() {
|
|
540
|
+
if (ended || aliveRefreshing) return;
|
|
541
|
+
aliveRefreshing = true;
|
|
542
|
+
try {
|
|
543
|
+
const changed = await applyAliveStatus(sessions, cfg.sessionsDir);
|
|
544
|
+
if (changed && attached && !ended) render();
|
|
545
|
+
} finally {
|
|
546
|
+
aliveRefreshing = false;
|
|
547
|
+
}
|
|
548
|
+
}
|
|
549
|
+
|
|
550
|
+
function onResize() {
|
|
551
|
+
render();
|
|
552
|
+
}
|
|
553
|
+
|
|
554
|
+
function onData(chunk) {
|
|
555
|
+
pending += decoder.write(chunk);
|
|
556
|
+
pump();
|
|
557
|
+
}
|
|
558
|
+
|
|
559
|
+
function pump() {
|
|
560
|
+
while (pending.length) {
|
|
561
|
+
const ch = pending[0];
|
|
562
|
+
if (ch === '\x1b') {
|
|
563
|
+
const mouse = pending.match(/^\x1b\[<(\d+);(\d+);(\d+)([Mm])/);
|
|
564
|
+
if (mouse) {
|
|
565
|
+
pending = pending.slice(mouse[0].length);
|
|
566
|
+
onMouse(Number(mouse[1]), Number(mouse[2]) - 1, Number(mouse[3]) - 1, mouse[4] === 'M');
|
|
567
|
+
continue;
|
|
568
|
+
}
|
|
569
|
+
const arrow = pending.match(/^\x1b\[(A|B|C|D|H|F)/);
|
|
570
|
+
if (arrow) {
|
|
571
|
+
pending = pending.slice(arrow[0].length);
|
|
572
|
+
handleKey({ A: 'up', B: 'down', C: 'right', D: 'left', H: 'home', F: 'end' }[arrow[1]]);
|
|
573
|
+
continue;
|
|
574
|
+
}
|
|
575
|
+
const tilde = pending.match(/^\x1b\[(\d+)~/);
|
|
576
|
+
if (tilde) {
|
|
577
|
+
pending = pending.slice(tilde[0].length);
|
|
578
|
+
handleKey({ 5: 'pageup', 6: 'pagedown' }[tilde[1]] ?? 'other');
|
|
579
|
+
continue;
|
|
580
|
+
}
|
|
581
|
+
const csi = pending.match(/^\x1b\[[0-9;?]*[A-Za-z]/);
|
|
582
|
+
if (csi) {
|
|
583
|
+
pending = pending.slice(csi[0].length);
|
|
584
|
+
continue;
|
|
585
|
+
}
|
|
586
|
+
if (pending.length === 1) {
|
|
587
|
+
if (!escTimer) {
|
|
588
|
+
escTimer = setTimeout(() => {
|
|
589
|
+
escTimer = null;
|
|
590
|
+
if (pending === '\x1b') {
|
|
591
|
+
pending = '';
|
|
592
|
+
handleKey('escape');
|
|
593
|
+
} else {
|
|
594
|
+
pump();
|
|
595
|
+
}
|
|
596
|
+
}, 40);
|
|
597
|
+
}
|
|
598
|
+
return;
|
|
599
|
+
}
|
|
600
|
+
pending = pending.slice(1);
|
|
601
|
+
continue;
|
|
602
|
+
}
|
|
603
|
+
if (ch === '\r' || ch === '\n') {
|
|
604
|
+
pending = pending.slice(1);
|
|
605
|
+
handleKey('enter');
|
|
606
|
+
continue;
|
|
607
|
+
}
|
|
608
|
+
if (ch === '\x7f' || ch === '\b') {
|
|
609
|
+
pending = pending.slice(1);
|
|
610
|
+
handleKey('backspace');
|
|
611
|
+
continue;
|
|
612
|
+
}
|
|
613
|
+
if (ch === '\x03') {
|
|
614
|
+
pending = pending.slice(1);
|
|
615
|
+
handleKey('escape');
|
|
616
|
+
continue;
|
|
617
|
+
}
|
|
618
|
+
if (ch === '\x15') {
|
|
619
|
+
pending = pending.slice(1);
|
|
620
|
+
handleKey('clear');
|
|
621
|
+
continue;
|
|
622
|
+
}
|
|
623
|
+
const cp = String.fromCodePoint(pending.codePointAt(0));
|
|
624
|
+
pending = pending.slice(cp.length);
|
|
625
|
+
handleKey(cp);
|
|
626
|
+
}
|
|
627
|
+
}
|
|
628
|
+
|
|
629
|
+
function onMouse(code, x, y, press) {
|
|
630
|
+
if (!press) return;
|
|
631
|
+
if (code === 64) return move(-3);
|
|
632
|
+
if (code === 65) return move(3);
|
|
633
|
+
if ((code & 3) !== 0 || code >= 32) return;
|
|
634
|
+
if (y === 2) {
|
|
635
|
+
for (const c of layout.cells) {
|
|
636
|
+
if (x >= c.x && x < c.x + c.width) {
|
|
637
|
+
clickHeader(c.key);
|
|
638
|
+
return;
|
|
639
|
+
}
|
|
640
|
+
}
|
|
641
|
+
return;
|
|
642
|
+
}
|
|
643
|
+
if (y >= LIST_START && y < LIST_START + viewH) {
|
|
644
|
+
const idx = top + (y - LIST_START);
|
|
645
|
+
if (idx >= filtered.length) return;
|
|
646
|
+
const now = Date.now();
|
|
647
|
+
if (lastClick.index === idx && now - lastClick.at < 450) {
|
|
648
|
+
lastClick = { index: -1, at: 0 };
|
|
649
|
+
open(filtered[idx]);
|
|
650
|
+
return;
|
|
651
|
+
}
|
|
652
|
+
lastClick = { index: idx, at: now };
|
|
653
|
+
cursor = idx;
|
|
654
|
+
render();
|
|
655
|
+
}
|
|
656
|
+
}
|
|
657
|
+
|
|
658
|
+
function clickHeader(key) {
|
|
659
|
+
sort = sort.mode === key
|
|
660
|
+
? { mode: key, order: sort.order === 'asc' ? 'desc' : 'asc' }
|
|
661
|
+
: normalizeSort(key);
|
|
662
|
+
sorted = sortSessions(sessions, sort);
|
|
663
|
+
filtered = filterSessions(sorted, query);
|
|
664
|
+
cursor = 0;
|
|
665
|
+
top = 0;
|
|
666
|
+
lastClick = { index: -1, at: 0 };
|
|
667
|
+
render();
|
|
668
|
+
}
|
|
669
|
+
|
|
670
|
+
function move(delta) {
|
|
671
|
+
if (!filtered.length) return;
|
|
672
|
+
cursor = Math.max(0, Math.min(filtered.length - 1, cursor + delta));
|
|
673
|
+
render();
|
|
674
|
+
}
|
|
675
|
+
|
|
676
|
+
function handleKey(key) {
|
|
677
|
+
if (ended || busy) return;
|
|
678
|
+
switch (key) {
|
|
679
|
+
case 'up': move(-1); break;
|
|
680
|
+
case 'down': move(1); break;
|
|
681
|
+
case 'pageup': move(-viewH); break;
|
|
682
|
+
case 'pagedown': move(viewH); break;
|
|
683
|
+
case 'home': cursor = 0; render(); break;
|
|
684
|
+
case 'end': cursor = Math.max(0, filtered.length - 1); render(); break;
|
|
685
|
+
case 'enter': open(filtered[cursor]); break;
|
|
686
|
+
case 'escape': quit(); break;
|
|
687
|
+
case 'clear':
|
|
688
|
+
if (query) {
|
|
689
|
+
query = '';
|
|
690
|
+
refresh();
|
|
691
|
+
}
|
|
692
|
+
break;
|
|
693
|
+
case 'backspace':
|
|
694
|
+
if (query) {
|
|
695
|
+
query = [...query].slice(0, -1).join('');
|
|
696
|
+
refresh();
|
|
697
|
+
}
|
|
698
|
+
break;
|
|
699
|
+
case 'left': case 'right': case 'other': break;
|
|
700
|
+
default:
|
|
701
|
+
if (key.length === 1 && key.codePointAt(0) >= 32) {
|
|
702
|
+
query += key;
|
|
703
|
+
refresh();
|
|
704
|
+
}
|
|
705
|
+
}
|
|
706
|
+
}
|
|
707
|
+
|
|
708
|
+
function refresh() {
|
|
709
|
+
filtered = filterSessions(sorted, query);
|
|
710
|
+
cursor = 0;
|
|
711
|
+
top = 0;
|
|
712
|
+
lastClick = { index: -1, at: 0 };
|
|
713
|
+
render();
|
|
714
|
+
}
|
|
715
|
+
|
|
716
|
+
function render() {
|
|
717
|
+
if (ended) return;
|
|
718
|
+
const width = Math.max(70, process.stdout.columns || 100);
|
|
719
|
+
const height = Math.max(8, process.stdout.rows || 30);
|
|
720
|
+
layout = computeLayout(width);
|
|
721
|
+
viewH = Math.max(1, height - 5);
|
|
722
|
+
|
|
723
|
+
if (cursor < top) top = cursor;
|
|
724
|
+
if (cursor >= top + viewH) top = cursor - viewH + 1;
|
|
725
|
+
top = Math.max(0, Math.min(top, Math.max(0, filtered.length - viewH)));
|
|
726
|
+
|
|
727
|
+
const qMax = Math.max(4, width - 20);
|
|
728
|
+
const qShown = strWidth(query) > qMax ? '…' + [...query].slice(-(qMax - 1)).join('') : query;
|
|
729
|
+
|
|
730
|
+
const title = truncate(`Claude 会话 (${sessions.length})`, width);
|
|
731
|
+
const meta = ` 排序: ${sortLabel(sort)} ${cfg.projectsDir}`;
|
|
732
|
+
const metaRoom = width - strWidth(title);
|
|
733
|
+
const titleLine = `\x1b[1m\x1b[36m${title}\x1b[0m` + (metaRoom > 6 ? dim(truncate(meta, metaRoom)) : '');
|
|
734
|
+
|
|
735
|
+
const searchLine = dim(' 筛选: ') + `\x1b[1m${truncate(qShown, Math.max(1, width - 14))}\x1b[0m`
|
|
736
|
+
+ '\x1b[7m \x1b[0m' + dim(` (${filtered.length} 条)`);
|
|
737
|
+
|
|
738
|
+
const lines = [];
|
|
739
|
+
lines.push(titleLine);
|
|
740
|
+
lines.push(searchLine);
|
|
741
|
+
lines.push(renderHeader(layout.cells, sort));
|
|
742
|
+
lines.push(dim(' ' + '─'.repeat(Math.max(0, width - 1))));
|
|
743
|
+
for (let i = 0; i < viewH; i++) {
|
|
744
|
+
const idx = top + i;
|
|
745
|
+
lines.push(idx < filtered.length ? renderRow(layout.cells, filtered[idx], idx === cursor, width) : '');
|
|
746
|
+
}
|
|
747
|
+
lines.push(dim(truncate(' ↑↓ 移动 Enter/双击 打开 表头排序 Esc 退出 ', Math.max(0, width - 20)))
|
|
748
|
+
+ `\x1b[32m●\x1b[0m` + dim(' 运行中 ') + `\x1b[31m●\x1b[0m` + dim(' 已结束'));
|
|
749
|
+
|
|
750
|
+
process.stdout.write('\x1b[H' + lines.map((l) => l + '\x1b[K').join('\r\n') + '\x1b[J');
|
|
751
|
+
}
|
|
752
|
+
|
|
753
|
+
async function open(session) {
|
|
754
|
+
if (busy || !session) return;
|
|
755
|
+
busy = true;
|
|
756
|
+
detach();
|
|
757
|
+
await launch(cfg, session);
|
|
758
|
+
console.log(dim('正在刷新会话列表…'));
|
|
759
|
+
try {
|
|
760
|
+
sessions = await scanSessions(cfg.projectsDir);
|
|
761
|
+
await applyAliveStatus(sessions, cfg.sessionsDir);
|
|
762
|
+
sorted = sortSessions(sessions, sort);
|
|
763
|
+
} catch (err) {
|
|
764
|
+
console.error(err.message ?? err);
|
|
765
|
+
}
|
|
766
|
+
filtered = filterSessions(sorted, query);
|
|
767
|
+
cursor = Math.min(cursor, Math.max(0, filtered.length - 1));
|
|
768
|
+
busy = false;
|
|
769
|
+
attach();
|
|
770
|
+
}
|
|
771
|
+
|
|
772
|
+
aliveTimer = setInterval(refreshAlive, 2000);
|
|
773
|
+
aliveTimer.unref?.();
|
|
774
|
+
attach();
|
|
775
|
+
});
|
|
776
|
+
}
|
|
777
|
+
|
|
778
|
+
async function main() {
|
|
779
|
+
const args = parseArgs(process.argv.slice(2));
|
|
780
|
+
if (args.help) {
|
|
781
|
+
printHelp();
|
|
782
|
+
return;
|
|
783
|
+
}
|
|
784
|
+
const cfg = await loadConfig(args.config);
|
|
785
|
+
const initialSort = normalizeSort(
|
|
786
|
+
args.sort ?? cfg.sort,
|
|
787
|
+
args.order ?? (args.sort ? undefined : cfg.order),
|
|
788
|
+
);
|
|
789
|
+
const sessions = sortSessions(await scanSessions(cfg.projectsDir), initialSort);
|
|
790
|
+
if (!fs.existsSync(cfg.sessionsDir)) {
|
|
791
|
+
console.warn(`未找到 sessions 目录 ${cfg.sessionsDir},存活状态将全部显示为已结束`);
|
|
792
|
+
}
|
|
793
|
+
await applyAliveStatus(sessions, cfg.sessionsDir);
|
|
794
|
+
if (!sessions.length) {
|
|
795
|
+
console.log(`未在 ${cfg.projectsDir} 找到任何会话`);
|
|
796
|
+
return;
|
|
797
|
+
}
|
|
798
|
+
if (args.list) {
|
|
799
|
+
printPlain(sessions);
|
|
800
|
+
return;
|
|
801
|
+
}
|
|
802
|
+
if (args.json) {
|
|
803
|
+
console.log(JSON.stringify(sessions.map(({ id, cwd, projectName, mtimeMs, file, alive }) => ({ id, alive: Boolean(alive), cwd, projectName, mtimeMs, file })), null, 2));
|
|
804
|
+
return;
|
|
805
|
+
}
|
|
806
|
+
if (args.open) {
|
|
807
|
+
const q = args.open.toLowerCase();
|
|
808
|
+
const hits = sessions.filter((s) => s.id.toLowerCase().startsWith(q));
|
|
809
|
+
if (!hits.length) throw new Error(`没有以 "${args.open}" 开头的会话`);
|
|
810
|
+
if (hits.length > 1) throw new Error(`前缀 "${args.open}" 匹配到多个会话:\n${hits.map((s) => ` ${s.id} ${s.projectName} ${s.cwd ?? ''}`).join('\n')}`);
|
|
811
|
+
process.exitCode = await launch(cfg, hits[0]);
|
|
812
|
+
return;
|
|
813
|
+
}
|
|
814
|
+
if (!process.stdin.isTTY || !process.stdout.isTTY) {
|
|
815
|
+
throw new Error('交互界面需要真实终端;非交互环境请用 --list 或 --json');
|
|
816
|
+
}
|
|
817
|
+
await runTui(cfg, sessions, initialSort);
|
|
818
|
+
}
|
|
819
|
+
|
|
820
|
+
main().catch((err) => {
|
|
821
|
+
process.stdout.write('\x1b[?1000l\x1b[?1006l\x1b[?25h\x1b[?1049l');
|
|
822
|
+
console.error(err.message ?? err);
|
|
823
|
+
process.exit(1);
|
|
824
|
+
});
|