chatccc 0.2.6 → 0.2.7
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/README.md +50 -11
- package/package.json +1 -1
- package/src/__tests__/adapter-interface.test.ts +151 -151
- package/src/__tests__/cards.test.ts +417 -413
- package/src/__tests__/claude-adapter.test.ts +528 -528
- package/src/__tests__/config.test.ts +123 -0
- package/src/__tests__/cursor-adapter.test.ts +662 -249
- package/src/__tests__/cursor-session-meta-store.test.ts +212 -0
- package/src/__tests__/fixtures/cursor_partial_only.jsonl +5 -0
- package/src/__tests__/fixtures/cursor_partial_with_final.jsonl +13 -0
- package/src/__tests__/fixtures/cursor_with_tool_call.jsonl +12 -0
- package/src/__tests__/git-command.test.ts +288 -0
- package/src/__tests__/session.test.ts +475 -296
- package/src/adapters/adapter-interface.ts +151 -126
- package/src/adapters/claude-adapter.ts +257 -257
- package/src/adapters/cursor-adapter.ts +401 -228
- package/src/adapters/cursor-session-meta-store.ts +154 -0
- package/src/cards.ts +33 -21
- package/src/config.ts +92 -2
- package/src/feishu-api.ts +1 -1
- package/src/git-command.ts +202 -0
- package/src/index.ts +58 -4
- package/src/session.ts +620 -513
|
@@ -0,0 +1,212 @@
|
|
|
1
|
+
// =============================================================================
|
|
2
|
+
// cursor-session-meta-store.test.ts — sessionId→{cwd,model} 持久化的护栏单测
|
|
3
|
+
// =============================================================================
|
|
4
|
+
// 行为契约(与 cursor-adapter.getSessionInfo 配合,决定 /git、/status、/sessions
|
|
5
|
+
// 在 Cursor 会话上是否显示正确):
|
|
6
|
+
// - 文件不存在 / 损坏 / 非法 schema 时 get 返回 undefined,不抛异常
|
|
7
|
+
// - set 部分合并:只覆盖非空字段,已有字段保持不变
|
|
8
|
+
// - 同实例 set→get 立即可读(内存缓存)
|
|
9
|
+
// - 跨实例(同 filePath)get 仍能读到(落盘验证)
|
|
10
|
+
// - cwd 缺失的记录视为不完整(get 返回 undefined)
|
|
11
|
+
// - 历史 schema(值为字符串)兼容读取,被视作 { cwd: <string> }
|
|
12
|
+
// - 多 sessionId 互不影响
|
|
13
|
+
// =============================================================================
|
|
14
|
+
|
|
15
|
+
import { describe, it, expect, beforeEach, afterEach } from "vitest";
|
|
16
|
+
import { mkdtemp, rm, writeFile, readFile } from "node:fs/promises";
|
|
17
|
+
import { tmpdir } from "node:os";
|
|
18
|
+
import { join } from "node:path";
|
|
19
|
+
|
|
20
|
+
import { createCursorSessionMetaStore } from "../adapters/cursor-session-meta-store.ts";
|
|
21
|
+
|
|
22
|
+
let tmpDir: string;
|
|
23
|
+
let storePath: string;
|
|
24
|
+
|
|
25
|
+
beforeEach(async () => {
|
|
26
|
+
tmpDir = await mkdtemp(join(tmpdir(), "chatccc-metastore-"));
|
|
27
|
+
storePath = join(tmpDir, "cursor-session-meta.json");
|
|
28
|
+
});
|
|
29
|
+
|
|
30
|
+
afterEach(async () => {
|
|
31
|
+
await rm(tmpDir, { recursive: true, force: true });
|
|
32
|
+
});
|
|
33
|
+
|
|
34
|
+
describe("createCursorSessionMetaStore — 文件不存在 / 损坏的鲁棒性", () => {
|
|
35
|
+
it("文件不存在时 get 返回 undefined(不抛)", async () => {
|
|
36
|
+
const store = createCursorSessionMetaStore(storePath);
|
|
37
|
+
await expect(store.get("any-sid")).resolves.toBeUndefined();
|
|
38
|
+
});
|
|
39
|
+
|
|
40
|
+
it("JSON 损坏时 get 返回 undefined,且后续 set 仍可正常写入", async () => {
|
|
41
|
+
await writeFile(storePath, "{not valid json", "utf-8");
|
|
42
|
+
const store = createCursorSessionMetaStore(storePath);
|
|
43
|
+
|
|
44
|
+
await expect(store.get("sid-1")).resolves.toBeUndefined();
|
|
45
|
+
await store.set("sid-1", { cwd: "/tmp/recovered" });
|
|
46
|
+
await expect(store.get("sid-1")).resolves.toEqual({ cwd: "/tmp/recovered" });
|
|
47
|
+
});
|
|
48
|
+
|
|
49
|
+
it("文件根是数组而非对象时视作空映射(防御非法 schema)", async () => {
|
|
50
|
+
await writeFile(storePath, JSON.stringify(["sid-1", "/tmp"]), "utf-8");
|
|
51
|
+
const store = createCursorSessionMetaStore(storePath);
|
|
52
|
+
await expect(store.get("sid-1")).resolves.toBeUndefined();
|
|
53
|
+
});
|
|
54
|
+
|
|
55
|
+
it("条目为非对象/非字符串时被忽略(防御非法 schema)", async () => {
|
|
56
|
+
await writeFile(
|
|
57
|
+
storePath,
|
|
58
|
+
JSON.stringify({
|
|
59
|
+
"sid-ok": { cwd: "/tmp/ok" },
|
|
60
|
+
"sid-num": 123,
|
|
61
|
+
"sid-null": null,
|
|
62
|
+
"sid-arr": ["x"],
|
|
63
|
+
}),
|
|
64
|
+
"utf-8",
|
|
65
|
+
);
|
|
66
|
+
const store = createCursorSessionMetaStore(storePath);
|
|
67
|
+
await expect(store.get("sid-ok")).resolves.toEqual({ cwd: "/tmp/ok" });
|
|
68
|
+
await expect(store.get("sid-num")).resolves.toBeUndefined();
|
|
69
|
+
await expect(store.get("sid-null")).resolves.toBeUndefined();
|
|
70
|
+
await expect(store.get("sid-arr")).resolves.toBeUndefined();
|
|
71
|
+
});
|
|
72
|
+
|
|
73
|
+
it("条目对象内 cwd 缺失或非字符串 → get 返回 undefined(视为不完整)", async () => {
|
|
74
|
+
await writeFile(
|
|
75
|
+
storePath,
|
|
76
|
+
JSON.stringify({
|
|
77
|
+
"sid-no-cwd": { model: "Composer 2 Fast" },
|
|
78
|
+
"sid-cwd-num": { cwd: 123, model: "X" },
|
|
79
|
+
"sid-good": { cwd: "/tmp", model: "Composer 2 Fast" },
|
|
80
|
+
}),
|
|
81
|
+
"utf-8",
|
|
82
|
+
);
|
|
83
|
+
const store = createCursorSessionMetaStore(storePath);
|
|
84
|
+
await expect(store.get("sid-no-cwd")).resolves.toBeUndefined();
|
|
85
|
+
await expect(store.get("sid-cwd-num")).resolves.toBeUndefined();
|
|
86
|
+
await expect(store.get("sid-good")).resolves.toEqual({
|
|
87
|
+
cwd: "/tmp",
|
|
88
|
+
model: "Composer 2 Fast",
|
|
89
|
+
});
|
|
90
|
+
});
|
|
91
|
+
});
|
|
92
|
+
|
|
93
|
+
describe("createCursorSessionMetaStore — 历史 schema 兼容(值为字符串)", () => {
|
|
94
|
+
it("v1 schema:value 为字符串视作 { cwd: <string> }", async () => {
|
|
95
|
+
await writeFile(
|
|
96
|
+
storePath,
|
|
97
|
+
JSON.stringify({ "sid-v1": "/legacy/path" }),
|
|
98
|
+
"utf-8",
|
|
99
|
+
);
|
|
100
|
+
const store = createCursorSessionMetaStore(storePath);
|
|
101
|
+
await expect(store.get("sid-v1")).resolves.toEqual({ cwd: "/legacy/path" });
|
|
102
|
+
});
|
|
103
|
+
|
|
104
|
+
it("空字符串值不被视为合法 v1 记录", async () => {
|
|
105
|
+
await writeFile(storePath, JSON.stringify({ "sid-empty": "" }), "utf-8");
|
|
106
|
+
const store = createCursorSessionMetaStore(storePath);
|
|
107
|
+
await expect(store.get("sid-empty")).resolves.toBeUndefined();
|
|
108
|
+
});
|
|
109
|
+
});
|
|
110
|
+
|
|
111
|
+
describe("createCursorSessionMetaStore — 读写循环", () => {
|
|
112
|
+
it("set { cwd } 后 get 返回相同 cwd(无 model 字段)", async () => {
|
|
113
|
+
const store = createCursorSessionMetaStore(storePath);
|
|
114
|
+
await store.set("sid-1", { cwd: "F:/proj" });
|
|
115
|
+
await expect(store.get("sid-1")).resolves.toEqual({ cwd: "F:/proj" });
|
|
116
|
+
});
|
|
117
|
+
|
|
118
|
+
it("set { cwd, model } 后 get 返回完整 meta", async () => {
|
|
119
|
+
const store = createCursorSessionMetaStore(storePath);
|
|
120
|
+
await store.set("sid-1", { cwd: "F:/proj", model: "Composer 2 Fast" });
|
|
121
|
+
await expect(store.get("sid-1")).resolves.toEqual({
|
|
122
|
+
cwd: "F:/proj",
|
|
123
|
+
model: "Composer 2 Fast",
|
|
124
|
+
});
|
|
125
|
+
});
|
|
126
|
+
|
|
127
|
+
it("set 后跨实例(同 filePath)get 仍能读到(落盘验证)", async () => {
|
|
128
|
+
const writer = createCursorSessionMetaStore(storePath);
|
|
129
|
+
await writer.set("sid-1", { cwd: "/home/u/code", model: "Sonnet 4.7" });
|
|
130
|
+
|
|
131
|
+
const reader = createCursorSessionMetaStore(storePath);
|
|
132
|
+
await expect(reader.get("sid-1")).resolves.toEqual({
|
|
133
|
+
cwd: "/home/u/code",
|
|
134
|
+
model: "Sonnet 4.7",
|
|
135
|
+
});
|
|
136
|
+
});
|
|
137
|
+
|
|
138
|
+
it("set 部分合并:只更新 cwd 不会清空已有 model", async () => {
|
|
139
|
+
const store = createCursorSessionMetaStore(storePath);
|
|
140
|
+
await store.set("sid-1", { cwd: "/old", model: "Composer 2 Fast" });
|
|
141
|
+
await store.set("sid-1", { cwd: "/new" });
|
|
142
|
+
await expect(store.get("sid-1")).resolves.toEqual({
|
|
143
|
+
cwd: "/new",
|
|
144
|
+
model: "Composer 2 Fast",
|
|
145
|
+
});
|
|
146
|
+
});
|
|
147
|
+
|
|
148
|
+
it("set 部分合并:只更新 model 不会清空已有 cwd", async () => {
|
|
149
|
+
const store = createCursorSessionMetaStore(storePath);
|
|
150
|
+
await store.set("sid-1", { cwd: "/keep", model: "v1" });
|
|
151
|
+
await store.set("sid-1", { model: "v2" });
|
|
152
|
+
await expect(store.get("sid-1")).resolves.toEqual({
|
|
153
|
+
cwd: "/keep",
|
|
154
|
+
model: "v2",
|
|
155
|
+
});
|
|
156
|
+
});
|
|
157
|
+
|
|
158
|
+
it("set 时 partial 中的空字符串 / undefined 字段不会覆盖已有值", async () => {
|
|
159
|
+
const store = createCursorSessionMetaStore(storePath);
|
|
160
|
+
await store.set("sid-1", { cwd: "/keep", model: "v1" });
|
|
161
|
+
await store.set("sid-1", { cwd: "", model: undefined });
|
|
162
|
+
await expect(store.get("sid-1")).resolves.toEqual({
|
|
163
|
+
cwd: "/keep",
|
|
164
|
+
model: "v1",
|
|
165
|
+
});
|
|
166
|
+
});
|
|
167
|
+
|
|
168
|
+
it("第一次 set 不含 cwd → 记录不完整 → get 返回 undefined", async () => {
|
|
169
|
+
const store = createCursorSessionMetaStore(storePath);
|
|
170
|
+
await store.set("sid-1", { model: "Composer 2 Fast" });
|
|
171
|
+
await expect(store.get("sid-1")).resolves.toBeUndefined();
|
|
172
|
+
});
|
|
173
|
+
|
|
174
|
+
it("多 sessionId 互不影响", async () => {
|
|
175
|
+
const store = createCursorSessionMetaStore(storePath);
|
|
176
|
+
await store.set("sid-A", { cwd: "/a", model: "mA" });
|
|
177
|
+
await store.set("sid-B", { cwd: "/b" });
|
|
178
|
+
await store.set("sid-C", { cwd: "/c", model: "mC" });
|
|
179
|
+
|
|
180
|
+
await expect(store.get("sid-A")).resolves.toEqual({ cwd: "/a", model: "mA" });
|
|
181
|
+
await expect(store.get("sid-B")).resolves.toEqual({ cwd: "/b" });
|
|
182
|
+
await expect(store.get("sid-C")).resolves.toEqual({ cwd: "/c", model: "mC" });
|
|
183
|
+
await expect(store.get("sid-missing")).resolves.toBeUndefined();
|
|
184
|
+
});
|
|
185
|
+
|
|
186
|
+
it("set 完全相同的 partial 不会重复写盘(性能优化,行为不变)", async () => {
|
|
187
|
+
const store = createCursorSessionMetaStore(storePath);
|
|
188
|
+
await store.set("sid-1", { cwd: "/same", model: "mSame" });
|
|
189
|
+
|
|
190
|
+
// 先把文件覆盖为非法内容;如果跳过 IO 则文件保持非法内容
|
|
191
|
+
await writeFile(storePath, "MARKER_NOT_JSON", "utf-8");
|
|
192
|
+
await store.set("sid-1", { cwd: "/same", model: "mSame" });
|
|
193
|
+
|
|
194
|
+
const raw = await readFile(storePath, "utf-8");
|
|
195
|
+
expect(raw).toBe("MARKER_NOT_JSON");
|
|
196
|
+
});
|
|
197
|
+
|
|
198
|
+
it("父目录不存在时 set 会自动创建", async () => {
|
|
199
|
+
const nestedPath = join(tmpDir, "a", "b", "c", "meta.json");
|
|
200
|
+
const store = createCursorSessionMetaStore(nestedPath);
|
|
201
|
+
await store.set("sid-1", { cwd: "/deep", model: "deepModel" });
|
|
202
|
+
await expect(store.get("sid-1")).resolves.toEqual({
|
|
203
|
+
cwd: "/deep",
|
|
204
|
+
model: "deepModel",
|
|
205
|
+
});
|
|
206
|
+
|
|
207
|
+
const raw = await readFile(nestedPath, "utf-8");
|
|
208
|
+
expect(JSON.parse(raw)).toEqual({
|
|
209
|
+
"sid-1": { cwd: "/deep", model: "deepModel" },
|
|
210
|
+
});
|
|
211
|
+
});
|
|
212
|
+
});
|
|
@@ -0,0 +1,5 @@
|
|
|
1
|
+
{"type":"system","subtype":"init","apiKeySource":"login","cwd":"F:\\Users\\weizhangjian\\feishuclauderprivate","session_id":"abc-only-partial","model":"Composer 2 Fast","permissionMode":"default"}
|
|
2
|
+
{"type":"user","message":{"role":"user","content":[{"type":"text","text":"'hi'"}]},"session_id":"abc-only-partial"}
|
|
3
|
+
{"type":"assistant","message":{"role":"assistant","content":[{"type":"text","text":"hello"}]},"session_id":"abc-only-partial","timestamp_ms":1778411927583}
|
|
4
|
+
{"type":"assistant","message":{"role":"assistant","content":[{"type":"text","text":" world"}]},"session_id":"abc-only-partial","timestamp_ms":1778411927587}
|
|
5
|
+
{"type":"result","subtype":"success","duration_ms":1000,"duration_api_ms":1000,"is_error":false,"result":"hello world","session_id":"abc-only-partial","request_id":"req-only-partial","usage":{"inputTokens":1,"outputTokens":2}}
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
{"type":"system","subtype":"init","apiKeySource":"login","cwd":"F:\\Users\\weizhangjian\\feishuclauderprivate","session_id":"b60ebd57-33cb-4364-b6fa-bb69657be6e8","model":"Composer 2 Fast","permissionMode":"default"}
|
|
2
|
+
{"type":"user","message":{"role":"user","content":[{"type":"text","text":"'刚才你算的是什么题?'"}]},"session_id":"b60ebd57-33cb-4364-b6fa-bb69657be6e8"}
|
|
3
|
+
{"type":"assistant","message":{"role":"assistant","content":[{"type":"text","text":"你"}]},"session_id":"b60ebd57-33cb-4364-b6fa-bb69657be6e8","timestamp_ms":1778411927583}
|
|
4
|
+
{"type":"assistant","message":{"role":"assistant","content":[{"type":"text","text":"上一题问"}]},"session_id":"b60ebd57-33cb-4364-b6fa-bb69657be6e8","timestamp_ms":1778411927587}
|
|
5
|
+
{"type":"assistant","message":{"role":"assistant","content":[{"type":"text","text":"的是 **1"}]},"session_id":"b60ebd57-33cb-4364-b6fa-bb69657be6e8","timestamp_ms":1778411927587}
|
|
6
|
+
{"type":"assistant","message":{"role":"assistant","content":[{"type":"text","text":"+"}]},"session_id":"b60ebd57-33cb-4364-b6fa-bb69657be6e8","timestamp_ms":1778411927588}
|
|
7
|
+
{"type":"assistant","message":{"role":"assistant","content":[{"type":"text","text":"2=?"}]},"session_id":"b60ebd57-33cb-4364-b6fa-bb69657be6e8","timestamp_ms":1778411927588}
|
|
8
|
+
{"type":"assistant","message":{"role":"assistant","content":[{"type":"text","text":"**(一加"}]},"session_id":"b60ebd57-33cb-4364-b6fa-bb69657be6e8","timestamp_ms":1778411927588}
|
|
9
|
+
{"type":"assistant","message":{"role":"assistant","content":[{"type":"text","text":"二"}]},"session_id":"b60ebd57-33cb-4364-b6fa-bb69657be6e8","timestamp_ms":1778411927589}
|
|
10
|
+
{"type":"assistant","message":{"role":"assistant","content":[{"type":"text","text":"等于几"}]},"session_id":"b60ebd57-33cb-4364-b6fa-bb69657be6e8","timestamp_ms":1778411927589}
|
|
11
|
+
{"type":"assistant","message":{"role":"assistant","content":[{"type":"text","text":")。"}]},"session_id":"b60ebd57-33cb-4364-b6fa-bb69657be6e8","timestamp_ms":1778411927589}
|
|
12
|
+
{"type":"assistant","message":{"role":"assistant","content":[{"type":"text","text":"你上一题问的是 **1+2=?**(一加二等于几)。"}]},"session_id":"b60ebd57-33cb-4364-b6fa-bb69657be6e8"}
|
|
13
|
+
{"type":"result","subtype":"success","duration_ms":5811,"duration_api_ms":5811,"is_error":false,"result":"你上一题问的是 **1+2=?**(一加二等于几)。","session_id":"b60ebd57-33cb-4364-b6fa-bb69657be6e8","request_id":"ab6f7855-8c3d-414e-b749-ce8ecc062a00","usage":{"inputTokens":34,"outputTokens":92,"cacheReadTokens":10208,"cacheWriteTokens":0}}
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
{"type":"system","subtype":"init","apiKeySource":"login","cwd":"/tmp","session_id":"sid-tool","model":"Composer 2 Fast","permissionMode":"default"}
|
|
2
|
+
{"type":"user","message":{"role":"user","content":[{"type":"text","text":"列出当前目录"}]},"session_id":"sid-tool"}
|
|
3
|
+
{"type":"assistant","message":{"role":"assistant","content":[{"type":"text","text":"我"}]},"session_id":"sid-tool","timestamp_ms":1}
|
|
4
|
+
{"type":"assistant","message":{"role":"assistant","content":[{"type":"text","text":"看下"}]},"session_id":"sid-tool","timestamp_ms":2}
|
|
5
|
+
{"type":"assistant","message":{"role":"assistant","content":[{"type":"text","text":"。"}]},"session_id":"sid-tool","timestamp_ms":3}
|
|
6
|
+
{"type":"assistant","message":{"role":"assistant","content":[{"type":"text","text":"我看下。"},{"type":"tool_use","name":"ls","input":{"path":"."}}]},"session_id":"sid-tool","timestamp_ms":4,"model_call_id":"mc-1"}
|
|
7
|
+
{"type":"user","message":{"role":"user","content":[{"type":"tool_result","tool_use_id":"tool-1","content":"file1\nfile2","is_error":false}]},"session_id":"sid-tool"}
|
|
8
|
+
{"type":"assistant","message":{"role":"assistant","content":[{"type":"text","text":"两"}]},"session_id":"sid-tool","timestamp_ms":5}
|
|
9
|
+
{"type":"assistant","message":{"role":"assistant","content":[{"type":"text","text":"个文件"}]},"session_id":"sid-tool","timestamp_ms":6}
|
|
10
|
+
{"type":"assistant","message":{"role":"assistant","content":[{"type":"text","text":"。"}]},"session_id":"sid-tool","timestamp_ms":7}
|
|
11
|
+
{"type":"assistant","message":{"role":"assistant","content":[{"type":"text","text":"两个文件。"}]},"session_id":"sid-tool"}
|
|
12
|
+
{"type":"result","subtype":"success","duration_ms":1000,"is_error":false,"result":"我看下。两个文件。","session_id":"sid-tool","request_id":"req-tool","usage":{"inputTokens":1,"outputTokens":2}}
|
|
@@ -0,0 +1,288 @@
|
|
|
1
|
+
import { describe, it, expect } from "vitest";
|
|
2
|
+
import { EventEmitter } from "node:events";
|
|
3
|
+
import { Readable } from "node:stream";
|
|
4
|
+
import { mkdtemp, rm } from "node:fs/promises";
|
|
5
|
+
import { tmpdir } from "node:os";
|
|
6
|
+
import { join } from "node:path";
|
|
7
|
+
|
|
8
|
+
import {
|
|
9
|
+
runGitCommand,
|
|
10
|
+
formatGitResult,
|
|
11
|
+
gitResultHeaderTemplate,
|
|
12
|
+
type GitCommandResult,
|
|
13
|
+
} from "../git-command.ts";
|
|
14
|
+
|
|
15
|
+
// ---------------------------------------------------------------------------
|
|
16
|
+
// 通过自定义 spawn 桩测试纯逻辑(流处理 / 超时 / 截断 / 退出码)
|
|
17
|
+
// ---------------------------------------------------------------------------
|
|
18
|
+
|
|
19
|
+
interface StubSpawnOptions {
|
|
20
|
+
stdout?: string[];
|
|
21
|
+
stderr?: string[];
|
|
22
|
+
exitCode?: number | null;
|
|
23
|
+
/** 数据推送 / close 事件相对于 spawn 的延迟(ms) */
|
|
24
|
+
emitDelayMs?: number;
|
|
25
|
+
/** 模拟 spawn 同步抛出(如可执行文件不存在) */
|
|
26
|
+
throwOnStart?: Error;
|
|
27
|
+
/** 模拟 child.on("error") 异步触发(如 ENOENT) */
|
|
28
|
+
emitErrorAfterMs?: number;
|
|
29
|
+
emitErrorMessage?: string;
|
|
30
|
+
/** 是否永远不结束(用来测超时) */
|
|
31
|
+
hang?: boolean;
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
function makeStubSpawn(opts: StubSpawnOptions): any {
|
|
35
|
+
return ((..._args: unknown[]) => {
|
|
36
|
+
if (opts.throwOnStart) throw opts.throwOnStart;
|
|
37
|
+
|
|
38
|
+
const child = new EventEmitter() as EventEmitter & {
|
|
39
|
+
stdout: Readable;
|
|
40
|
+
stderr: Readable;
|
|
41
|
+
kill: (sig?: string) => void;
|
|
42
|
+
};
|
|
43
|
+
child.stdout = new Readable({ read() {} });
|
|
44
|
+
child.stderr = new Readable({ read() {} });
|
|
45
|
+
|
|
46
|
+
let killed = false;
|
|
47
|
+
child.kill = (_sig?: string) => {
|
|
48
|
+
killed = true;
|
|
49
|
+
child.stdout.push(null);
|
|
50
|
+
child.stderr.push(null);
|
|
51
|
+
setImmediate(() => child.emit("close", null));
|
|
52
|
+
};
|
|
53
|
+
|
|
54
|
+
const delay = opts.emitDelayMs ?? 5;
|
|
55
|
+
setTimeout(() => {
|
|
56
|
+
if (killed) return;
|
|
57
|
+
for (const c of opts.stdout ?? []) child.stdout.push(Buffer.from(c));
|
|
58
|
+
child.stdout.push(null);
|
|
59
|
+
for (const c of opts.stderr ?? []) child.stderr.push(Buffer.from(c));
|
|
60
|
+
child.stderr.push(null);
|
|
61
|
+
if (opts.emitErrorAfterMs !== undefined) {
|
|
62
|
+
setTimeout(
|
|
63
|
+
() => child.emit("error", new Error(opts.emitErrorMessage ?? "stub error")),
|
|
64
|
+
opts.emitErrorAfterMs,
|
|
65
|
+
);
|
|
66
|
+
}
|
|
67
|
+
if (!opts.hang) {
|
|
68
|
+
setTimeout(() => {
|
|
69
|
+
if (!killed) child.emit("close", opts.exitCode ?? 0);
|
|
70
|
+
}, 2);
|
|
71
|
+
}
|
|
72
|
+
}, delay);
|
|
73
|
+
|
|
74
|
+
return child;
|
|
75
|
+
}) as any;
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
describe("runGitCommand (with stub spawn)", () => {
|
|
79
|
+
it("collects stdout and reports exit code 0", async () => {
|
|
80
|
+
const result = await runGitCommand("status", "/some/dir", {
|
|
81
|
+
spawnImpl: makeStubSpawn({ stdout: ["On branch main\n", "nothing to commit\n"], exitCode: 0 }),
|
|
82
|
+
});
|
|
83
|
+
expect(result.exitCode).toBe(0);
|
|
84
|
+
expect(result.stdout).toBe("On branch main\nnothing to commit\n");
|
|
85
|
+
expect(result.stderr).toBe("");
|
|
86
|
+
expect(result.timedOut).toBe(false);
|
|
87
|
+
expect(result.truncated).toBe(false);
|
|
88
|
+
expect(result.spawnError).toBeUndefined();
|
|
89
|
+
});
|
|
90
|
+
|
|
91
|
+
it("collects stderr and non-zero exit code", async () => {
|
|
92
|
+
const result = await runGitCommand("notacommand", "/some/dir", {
|
|
93
|
+
spawnImpl: makeStubSpawn({
|
|
94
|
+
stderr: ["git: 'notacommand' is not a git command\n"],
|
|
95
|
+
exitCode: 1,
|
|
96
|
+
}),
|
|
97
|
+
});
|
|
98
|
+
expect(result.exitCode).toBe(1);
|
|
99
|
+
expect(result.stdout).toBe("");
|
|
100
|
+
expect(result.stderr).toContain("not a git command");
|
|
101
|
+
});
|
|
102
|
+
|
|
103
|
+
it("truncates stdout when exceeding maxBytes", async () => {
|
|
104
|
+
const big = "x".repeat(5000);
|
|
105
|
+
const result = await runGitCommand("log", "/some/dir", {
|
|
106
|
+
maxBytes: 1024,
|
|
107
|
+
spawnImpl: makeStubSpawn({ stdout: [big], exitCode: 0 }),
|
|
108
|
+
});
|
|
109
|
+
expect(result.truncated).toBe(true);
|
|
110
|
+
// 截断后 stdout 长度 ≤ 1024
|
|
111
|
+
expect(Buffer.byteLength(result.stdout, "utf-8")).toBeLessThanOrEqual(1024);
|
|
112
|
+
});
|
|
113
|
+
|
|
114
|
+
it("truncates stderr when exceeding maxBytes", async () => {
|
|
115
|
+
const big = "e".repeat(3000);
|
|
116
|
+
const result = await runGitCommand("log", "/some/dir", {
|
|
117
|
+
maxBytes: 512,
|
|
118
|
+
spawnImpl: makeStubSpawn({ stderr: [big], exitCode: 1 }),
|
|
119
|
+
});
|
|
120
|
+
expect(result.truncated).toBe(true);
|
|
121
|
+
expect(Buffer.byteLength(result.stderr, "utf-8")).toBeLessThanOrEqual(512);
|
|
122
|
+
});
|
|
123
|
+
|
|
124
|
+
it("times out hung command and sets timedOut=true with exitCode=null", async () => {
|
|
125
|
+
const result = await runGitCommand("log", "/some/dir", {
|
|
126
|
+
timeoutMs: 30,
|
|
127
|
+
spawnImpl: makeStubSpawn({ hang: true, stdout: ["partial output\n"] }),
|
|
128
|
+
});
|
|
129
|
+
expect(result.timedOut).toBe(true);
|
|
130
|
+
expect(result.exitCode).toBeNull();
|
|
131
|
+
// 超时前已收集的 partial output 应保留
|
|
132
|
+
expect(result.stdout).toContain("partial output");
|
|
133
|
+
});
|
|
134
|
+
|
|
135
|
+
it("captures spawn synchronous throw as spawnError", async () => {
|
|
136
|
+
const result = await runGitCommand("status", "/some/dir", {
|
|
137
|
+
spawnImpl: makeStubSpawn({ throwOnStart: new Error("ENOENT git") }),
|
|
138
|
+
});
|
|
139
|
+
expect(result.spawnError).toBe("ENOENT git");
|
|
140
|
+
expect(result.exitCode).toBeNull();
|
|
141
|
+
});
|
|
142
|
+
|
|
143
|
+
it("records durationMs as a non-negative number", async () => {
|
|
144
|
+
const result = await runGitCommand("status", "/some/dir", {
|
|
145
|
+
spawnImpl: makeStubSpawn({ stdout: ["ok\n"], exitCode: 0, emitDelayMs: 10 }),
|
|
146
|
+
});
|
|
147
|
+
expect(typeof result.durationMs).toBe("number");
|
|
148
|
+
expect(result.durationMs).toBeGreaterThanOrEqual(0);
|
|
149
|
+
});
|
|
150
|
+
});
|
|
151
|
+
|
|
152
|
+
// ---------------------------------------------------------------------------
|
|
153
|
+
// formatGitResult —— 渲染逻辑
|
|
154
|
+
// ---------------------------------------------------------------------------
|
|
155
|
+
|
|
156
|
+
describe("formatGitResult", () => {
|
|
157
|
+
const baseResult = (overrides: Partial<GitCommandResult> = {}): GitCommandResult => ({
|
|
158
|
+
exitCode: 0,
|
|
159
|
+
stdout: "",
|
|
160
|
+
stderr: "",
|
|
161
|
+
durationMs: 12,
|
|
162
|
+
truncated: false,
|
|
163
|
+
timedOut: false,
|
|
164
|
+
...overrides,
|
|
165
|
+
});
|
|
166
|
+
|
|
167
|
+
it("includes the rendered command, cwd and exit code header", () => {
|
|
168
|
+
const out = formatGitResult("status", "/repo", baseResult({ stdout: "ok\n" }));
|
|
169
|
+
expect(out).toContain("git status");
|
|
170
|
+
expect(out).toContain("/repo");
|
|
171
|
+
expect(out).toContain("退出码: `0`");
|
|
172
|
+
});
|
|
173
|
+
|
|
174
|
+
it("renders stdout in a fenced block when present", () => {
|
|
175
|
+
const out = formatGitResult("status", "/repo", baseResult({ stdout: "On branch dev" }));
|
|
176
|
+
expect(out).toContain("**stdout:**");
|
|
177
|
+
expect(out).toContain("On branch dev");
|
|
178
|
+
expect(out.match(/```/g)?.length).toBeGreaterThanOrEqual(2);
|
|
179
|
+
});
|
|
180
|
+
|
|
181
|
+
it("renders stderr block when present", () => {
|
|
182
|
+
const out = formatGitResult(
|
|
183
|
+
"push",
|
|
184
|
+
"/repo",
|
|
185
|
+
baseResult({ exitCode: 1, stderr: "fatal: remote rejected" }),
|
|
186
|
+
);
|
|
187
|
+
expect(out).toContain("**stderr:**");
|
|
188
|
+
expect(out).toContain("fatal: remote rejected");
|
|
189
|
+
expect(out).toContain("退出码: `1`");
|
|
190
|
+
});
|
|
191
|
+
|
|
192
|
+
it("hints empty output when both streams are blank", () => {
|
|
193
|
+
const out = formatGitResult("status", "/repo", baseResult({ stdout: "", stderr: "" }));
|
|
194
|
+
expect(out).toContain("(命令无输出)");
|
|
195
|
+
});
|
|
196
|
+
|
|
197
|
+
it("annotates timedOut, truncated and spawnError flags", () => {
|
|
198
|
+
const out = formatGitResult(
|
|
199
|
+
"log",
|
|
200
|
+
"/repo",
|
|
201
|
+
baseResult({ exitCode: null, timedOut: true, truncated: true, spawnError: "ENOENT" }),
|
|
202
|
+
);
|
|
203
|
+
expect(out).toContain("超时");
|
|
204
|
+
expect(out).toContain("截断");
|
|
205
|
+
expect(out).toContain("ENOENT");
|
|
206
|
+
expect(out).toContain("退出码: `(无)`");
|
|
207
|
+
});
|
|
208
|
+
|
|
209
|
+
it("truncates very long stdout via truncateContent", () => {
|
|
210
|
+
const long = Array.from({ length: 500 }, (_, i) => `line${i + 1}`).join("\n");
|
|
211
|
+
const out = formatGitResult("log", "/repo", baseResult({ stdout: long }), {
|
|
212
|
+
maxLines: 5,
|
|
213
|
+
maxChars: 1000,
|
|
214
|
+
});
|
|
215
|
+
expect(out).toContain("...");
|
|
216
|
+
// 只保留前 1 行 + "..." + 后 4 行
|
|
217
|
+
expect(out).toContain("line1");
|
|
218
|
+
expect(out).toContain("line500");
|
|
219
|
+
expect(out).not.toContain("line250");
|
|
220
|
+
});
|
|
221
|
+
});
|
|
222
|
+
|
|
223
|
+
// ---------------------------------------------------------------------------
|
|
224
|
+
// gitResultHeaderTemplate
|
|
225
|
+
// ---------------------------------------------------------------------------
|
|
226
|
+
|
|
227
|
+
describe("gitResultHeaderTemplate", () => {
|
|
228
|
+
const r = (overrides: Partial<GitCommandResult>): GitCommandResult => ({
|
|
229
|
+
exitCode: 0,
|
|
230
|
+
stdout: "",
|
|
231
|
+
stderr: "",
|
|
232
|
+
durationMs: 0,
|
|
233
|
+
truncated: false,
|
|
234
|
+
timedOut: false,
|
|
235
|
+
...overrides,
|
|
236
|
+
});
|
|
237
|
+
|
|
238
|
+
it("returns green when exitCode=0", () => {
|
|
239
|
+
expect(gitResultHeaderTemplate(r({ exitCode: 0 }))).toBe("green");
|
|
240
|
+
});
|
|
241
|
+
|
|
242
|
+
it("returns red when exitCode≠0", () => {
|
|
243
|
+
expect(gitResultHeaderTemplate(r({ exitCode: 1 }))).toBe("red");
|
|
244
|
+
expect(gitResultHeaderTemplate(r({ exitCode: 128 }))).toBe("red");
|
|
245
|
+
});
|
|
246
|
+
|
|
247
|
+
it("returns yellow when timedOut", () => {
|
|
248
|
+
expect(gitResultHeaderTemplate(r({ exitCode: null, timedOut: true }))).toBe("yellow");
|
|
249
|
+
});
|
|
250
|
+
|
|
251
|
+
it("returns yellow when spawnError set", () => {
|
|
252
|
+
expect(gitResultHeaderTemplate(r({ exitCode: null, spawnError: "x" }))).toBe("yellow");
|
|
253
|
+
});
|
|
254
|
+
});
|
|
255
|
+
|
|
256
|
+
// ---------------------------------------------------------------------------
|
|
257
|
+
// 集成 smoke test:真正调起 `git --version` 在临时目录
|
|
258
|
+
// (前置条件:开发机已安装 git)
|
|
259
|
+
// ---------------------------------------------------------------------------
|
|
260
|
+
|
|
261
|
+
describe("runGitCommand integration (real git)", () => {
|
|
262
|
+
it("`git --version` runs successfully in a tmp dir", async () => {
|
|
263
|
+
const dir = await mkdtemp(join(tmpdir(), "chatccc-git-test-"));
|
|
264
|
+
try {
|
|
265
|
+
const result = await runGitCommand("--version", dir, { timeoutMs: 15_000 });
|
|
266
|
+
// git 不在 PATH 时会得到 spawnError 或非 0 退出,这里整体期望成功
|
|
267
|
+
expect(result.spawnError).toBeUndefined();
|
|
268
|
+
expect(result.exitCode).toBe(0);
|
|
269
|
+
expect(result.stdout.toLowerCase()).toContain("git version");
|
|
270
|
+
} finally {
|
|
271
|
+
await rm(dir, { recursive: true, force: true });
|
|
272
|
+
}
|
|
273
|
+
});
|
|
274
|
+
|
|
275
|
+
it("`git status` outside repo reports non-zero exit code with helpful stderr", async () => {
|
|
276
|
+
const dir = await mkdtemp(join(tmpdir(), "chatccc-git-test-"));
|
|
277
|
+
try {
|
|
278
|
+
const result = await runGitCommand("status", dir, { timeoutMs: 15_000 });
|
|
279
|
+
expect(result.spawnError).toBeUndefined();
|
|
280
|
+
// not a git repo → exitCode ≠ 0
|
|
281
|
+
expect(result.exitCode).not.toBe(0);
|
|
282
|
+
const combined = (result.stdout + result.stderr).toLowerCase();
|
|
283
|
+
expect(combined).toMatch(/not a git repository|fatal/);
|
|
284
|
+
} finally {
|
|
285
|
+
await rm(dir, { recursive: true, force: true });
|
|
286
|
+
}
|
|
287
|
+
});
|
|
288
|
+
});
|