-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsession-lifecycle.test.ts
More file actions
238 lines (207 loc) · 9.36 KB
/
Copy pathsession-lifecycle.test.ts
File metadata and controls
238 lines (207 loc) · 9.36 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
import { describe, expect, it, beforeEach } from "vitest";
import fs from "node:fs";
import os from "node:os";
import path from "node:path";
import { pickLatestSessionForCwd, resolveInteractiveSession } from "../src/cli/sessions.js";
import { SessionManager } from "../src/session/manager.js";
import { bootstrapHarness, type Harness } from "../src/bootstrap.js";
import { fauxAssistantMessage, fauxToolCall } from "@earendil-works/pi-ai";
/**
* Regression tests for the default session lifecycle:
* tinycode → live new session
* tinycode --continue → newest session for THIS cwd only
* tinycode --session → that session
* /new → fresh id + cleared context, harness intact
* /resume <id> → live context replaced by target session
*/
let home: string;
let sessDir: string;
beforeEach(() => {
home = fs.mkdtempSync(path.join(os.tmpdir(), "tc-session-lifecycle-"));
process.env.TINYCODE_HOME = home;
// Production storage lives at $TINYCODE_HOME/sessions.
sessDir = path.join(home, "sessions");
});
describe("resolveInteractiveSession (CLI lifecycle)", () => {
it("plain launch always starts a new session", () => {
const option = resolveInteractiveSession({ continueLast: false, sessionId: undefined }, "/anywhere");
expect(option).toEqual({ mode: "new" });
});
it("--continue picks the newest session for the same cwd", () => {
const manager = new SessionManager(sessDir);
const aOld = manager.start("/proj-a", "m");
const b = manager.start("/proj-b", "m"); // most recent globally
const aNew = manager.start("/proj-a", "m");
// Deterministic mtimes: b newest overall, aNew newer than aOld.
const t = (offset: number) => new Date(Date.now() + offset);
fs.utimesSync(path.join(sessDir, `${aOld}.jsonl`), t(0), t(0));
fs.utimesSync(path.join(sessDir, `${b}.jsonl`), t(2000), t(2000));
fs.utimesSync(path.join(sessDir, `${aNew}.jsonl`), t(1000), t(1000));
const picked = pickLatestSessionForCwd(manager, "/proj-a");
expect(picked!.id).toBe(aNew);
const option = resolveInteractiveSession({ continueLast: true, sessionId: undefined }, "/proj-a", () => {});
expect(option.mode).toBe("attach");
if (option.mode === "attach") expect(option.id).toBe(aNew);
void aOld;
});
it("--continue never restores another project's session", () => {
const manager = new SessionManager(sessDir);
manager.start("/proj-a", "m");
manager.start("/proj-b", "m"); // most recent globally
const option = resolveInteractiveSession(
{ continueLast: true, sessionId: undefined },
"/proj-a",
() => {},
);
expect(option.mode).toBe("attach");
if (option.mode === "attach") {
expect(option.id).toBe(pickLatestSessionForCwd(manager, "/proj-a")!.id);
}
});
it("--continue falls back to a new session when cwd has no history", () => {
const manager = new SessionManager(sessDir);
manager.start("/other-project", "m");
const notes: string[] = [];
const option = resolveInteractiveSession(
{ continueLast: true, sessionId: undefined },
"/fresh-project",
(line) => notes.push(line),
);
expect(option).toEqual({ mode: "new" });
expect(notes[0]).toContain("no previous session");
});
it("--session attaches exactly the requested id", () => {
const option = resolveInteractiveSession(
{ continueLast: false, sessionId: "abc123" },
"/x",
);
expect(option).toEqual({ mode: "attach", id: "abc123" });
});
});
describe("default interactive session lifecycle (harness level)", () => {
async function bootInteractive(): Promise<Harness> {
return bootstrapHarness({
projectRoot: fs.mkdtempSync(path.join(os.tmpdir(), "tc-life-proj-")),
config: { permissionMode: "auto" },
mock: true,
// what plain `tinycode` now does
session: resolveInteractiveSession({ continueLast: false, sessionId: undefined }, process.cwd()),
});
}
it("default interactive harness creates an active session (Test 1)", async () => {
const harness = await bootInteractive();
try {
expect(harness.session).toBeDefined();
expect(harness.session!.id).toBeDefined();
await harness.runtime.prompt("first message");
const files = fs.readdirSync(sessDir).filter((f) => f.endsWith(".jsonl"));
expect(files).toHaveLength(1);
const raw = fs.readFileSync(path.join(sessDir, files[0]!), "utf8");
expect(raw).toContain("first message");
// /sessions would show the current session on first run.
const list = harness.session!.list();
expect(list.map((s) => s.id)).toContain(harness.session!.id);
} finally {
await harness.shutdown();
}
}, 30000);
it("/new creates a different session and later prompts write to the new file (Test 2)", async () => {
const harness = await bootInteractive();
try {
const oldId = harness.session!.id!;
await harness.runtime.prompt("belongs to old session");
// What TuiApp.startNewSession + agent.reset do for /new:
const newId = harness.session!.start(harness.projectRoot, "mock/tinycode-mock");
harness.runtime.agent.reset();
expect(newId).not.toBe(oldId);
await harness.runtime.prompt("belongs to new session");
const oldRaw = fs.readFileSync(path.join(sessDir, `${oldId}.jsonl`), "utf8");
const newRaw = fs.readFileSync(path.join(sessDir, `${newId}.jsonl`), "utf8");
expect(oldRaw).toContain("belongs to old session");
expect(oldRaw).not.toContain("belongs to new session");
expect(newRaw).toContain("belongs to new session");
expect(newRaw).not.toContain("belongs to old session");
} finally {
await harness.shutdown();
}
}, 30000);
it("/new keeps the harness intact — tool calling still works after reset", async () => {
const workdir = fs.mkdtempSync(path.join(os.tmpdir(), "tc-life-reset-"));
fs.writeFileSync(path.join(workdir, "marker.txt"), "still here\n");
const harness = await bootstrapHarness({
projectRoot: workdir,
config: { permissionMode: "auto" },
mock: true,
session: { mode: "new" },
});
try {
const modelBefore = harness.runtime.agent.state.model;
const toolsBefore = harness.tools.names().join(",");
// /new
harness.session!.start(workdir, "mock/tinycode-mock");
harness.runtime.agent.reset();
expect(harness.runtime.agent.state.model).toBe(modelBefore);
expect(harness.tools.names().join(",")).toBe(toolsBefore);
expect(harness.runtime.agent.state.systemPrompt.length).toBeGreaterThan(0);
harness.models.mockHandle!.setResponses([
fauxAssistantMessage([fauxToolCall("read", { path: "marker.txt" })]),
fauxAssistantMessage("Read marker after /new."),
]);
await harness.runtime.prompt("read the marker again");
const results = harness.runtime.agent.state.messages.filter((m) => m.role === "toolResult");
expect(results).toHaveLength(1);
expect(results[0]!.isError).toBe(false);
expect(JSON.stringify(results[0]!.content)).toContain("still here");
} finally {
await harness.shutdown();
}
}, 30000);
it("/resume replaces the live context with the target session (Test 3)", async () => {
const harnessA = await bootstrapHarness({
projectRoot: fs.mkdtempSync(path.join(os.tmpdir(), "tc-life-a-")),
config: { permissionMode: "auto" },
mock: true,
session: { mode: "new" },
});
harnessA.models.mockHandle!.setResponses([fauxAssistantMessage("answer A2")]);
await harnessA.runtime.prompt("question A1");
const idA = harnessA.session!.id!;
const harnessB = await bootstrapHarness({
projectRoot: fs.mkdtempSync(path.join(os.tmpdir(), "tc-life-b-")),
config: { permissionMode: "auto" },
mock: true,
session: { mode: "new" },
});
harnessB.models.mockHandle!.setResponses([fauxAssistantMessage("answer B2")]);
await harnessB.runtime.prompt("question B1");
const idB = harnessB.session!.id!;
await harnessB.shutdown();
await harnessA.shutdown();
// Fresh interactive process resumes B then switches to A (/resume A).
const resumed = await bootstrapHarness({
projectRoot: fs.mkdtempSync(path.join(os.tmpdir(), "tc-life-c-")),
config: { permissionMode: "auto" },
mock: true,
session: { mode: "attach", id: idB },
});
try {
expect(resumed.runtime.agent.state.messages.length).toBeGreaterThan(0);
// /resume(idA): attach + replace live transcript.
resumed.session!.attach(idA, resumed.projectRoot, "mock/tinycode-mock");
const loadedA = resumed.session!.load(idA)!;
const current = [...resumed.runtime.agent.state.messages];
current.splice(0, current.length, ...loadedA.messages);
resumed.runtime.agent.state.messages = current;
const texts = JSON.stringify(resumed.runtime.agent.state.messages);
expect(texts).toContain("question A1");
expect(texts).not.toContain("question B1");
// Subsequent messages append to the resumed session's file.
const sizeBefore = fs.statSync(path.join(sessDir, `${idA}.jsonl`)).size;
resumed.models.mockHandle!.setResponses([fauxAssistantMessage("answer A3")]);
await resumed.runtime.prompt("follow-up on A");
expect(fs.statSync(path.join(sessDir, `${idA}.jsonl`)).size).toBeGreaterThan(sizeBefore);
} finally {
await resumed.shutdown();
}
}, 60000);
});