@ftrdotdev/pi-tui 0.8.0 → 0.9.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/CHANGELOG.md +225 -0
- package/README.md +5 -0
- package/package.json +18 -15
- package/src/activity-service.test.ts +97 -0
- package/src/activity.test.ts +1 -1
- package/src/activity.ts +38 -0
- package/src/chrome/budget.test.ts +345 -0
- package/src/chrome/budget.ts +220 -0
- package/src/chrome/declarations.ts +303 -0
- package/src/chrome/facts.test.ts +165 -0
- package/src/chrome/facts.ts +267 -0
- package/src/chrome/frame.ts +45 -0
- package/src/chrome/laws.test.ts +231 -0
- package/src/chrome/port.test.ts +164 -0
- package/src/chrome/port.ts +67 -0
- package/src/chrome/service-provider.test.ts +383 -0
- package/src/chrome/service-provider.ts +55 -0
- package/src/commands/git-execution.test.ts +5 -2
- package/src/commands/git-execution.ts +27 -15
- package/src/commands/git-status.test.ts +47 -15
- package/src/commands/git-status.ts +83 -31
- package/src/components/bordered-box.test.ts +12 -15
- package/src/components/bordered-box.ts +11 -7
- package/src/components/define-component.ts +1 -1
- package/src/components/index.ts +7 -0
- package/src/components/row-list.test.ts +310 -0
- package/src/components/row-list.ts +272 -0
- package/src/config.test.ts +118 -3
- package/src/config.ts +46 -40
- package/src/frame/box-frame.test.ts +53 -7
- package/src/harness-policy.test.ts +47 -0
- package/src/icons.test.ts +19 -0
- package/src/icons.ts +50 -31
- package/src/index.test.ts +135 -0
- package/src/index.ts +118 -119
- package/src/layers.test.ts +94 -0
- package/src/layers.ts +92 -0
- package/src/runtime-service.test.ts +218 -0
- package/src/runtime-service.ts +103 -0
- package/src/runtime.test.ts +165 -66
- package/src/runtime.ts +127 -93
- package/src/session-lifecycle-service.test.ts +95 -0
- package/src/session-lifecycle.test.ts +77 -0
- package/src/session-lifecycle.ts +21 -0
- package/src/state.test.ts +132 -3
- package/src/state.ts +43 -13
- package/src/telemetry-service.test.ts +250 -0
- package/src/telemetry.test.ts +322 -0
- package/src/telemetry.ts +130 -23
- package/src/ui/editor-tint.test.ts +58 -45
- package/src/ui/editor-tint.ts +1 -1
- package/src/ui/editor.ts +117 -53
- package/src/ui/footer.test.ts +349 -120
- package/src/ui/footer.ts +147 -124
- package/src/ui/header.test.ts +203 -223
- package/src/ui/header.ts +32 -96
- package/src/ui/preview.test.ts +73 -70
- package/src/ui/preview.ts +48 -33
- package/src/ui/render-helpers.test.ts +82 -13
- package/src/ui/render-helpers.ts +110 -122
- package/src/ui/settings-command.test.ts +70 -11
- package/src/ui/settings-command.ts +30 -45
- package/src/ui/theme-color.test.ts +4 -3
- package/src/usage-totals-service.test.ts +230 -0
- package/src/usage-totals-service.ts +59 -0
- package/src/utils.test.ts +46 -50
- package/src/utils.ts +41 -239
- package/src/vim/editor-host.test.ts +201 -75
- package/src/vim/editor-state.ts +2 -2
- package/src/vim/mode-indicator.test.ts +6 -5
- package/src/vim/mode-indicator.ts +13 -9
- package/src/vim/selection-render.ts +8 -4
- package/src/vim/text-model.test.ts +52 -14
- package/src/vim/text-model.ts +1 -1
- package/src/vim/vim-router.test.ts +3 -0
- package/src/vim/vim-router.ts +1 -1
package/src/runtime.ts
CHANGED
|
@@ -1,10 +1,12 @@
|
|
|
1
|
-
import {
|
|
2
|
-
import
|
|
3
|
-
import
|
|
4
|
-
import {
|
|
1
|
+
import { Duration, Effect, Fiber, Option, Path, Stream } from "effect";
|
|
2
|
+
import * as FileSystem from "effect/FileSystem";
|
|
3
|
+
import * as CP from "effect/process";
|
|
4
|
+
import { isNonEmptyString } from "./utils.ts";
|
|
5
5
|
|
|
6
|
-
|
|
7
|
-
const VERSION_TIMEOUT_MS = 2500;
|
|
6
|
+
/** The version probe's fixed time cap (parity with the old `execFile` call). */
|
|
7
|
+
const VERSION_TIMEOUT_MS = Duration.millis(2500);
|
|
8
|
+
/** D18: the same 64 KiB size the old `maxBuffer` used; over the cap the head is parsed. */
|
|
9
|
+
const MAX_STDOUT_BYTES = 64 * 1024;
|
|
8
10
|
|
|
9
11
|
export interface RuntimeInfo {
|
|
10
12
|
name: string;
|
|
@@ -49,7 +51,7 @@ const RUNTIMES: readonly RuntimeDef[] = [
|
|
|
49
51
|
{
|
|
50
52
|
name: "java",
|
|
51
53
|
files: ["pom.xml", "build.gradle", "build.gradle.kts", ".java-version"],
|
|
52
|
-
versionCommand: { cmd: "java", args: ["-version"], pattern: /version\s+"(\d+\.\d+[
|
|
54
|
+
versionCommand: { cmd: "java", args: ["-version"], pattern: /version\s+"(\d+\.\d+[\d.]*)"/ },
|
|
53
55
|
},
|
|
54
56
|
{
|
|
55
57
|
name: "swift",
|
|
@@ -155,99 +157,131 @@ const RUNTIMES: readonly RuntimeDef[] = [
|
|
|
155
157
|
{ name: "dotnet", files: [".csproj", ".fsproj", "global.json", "Directory.Build.props"] },
|
|
156
158
|
{ name: "cobol", files: [], extensions: [".cbl", ".cob"] },
|
|
157
159
|
];
|
|
160
|
+
// ---------------------------------------------------------------------------
|
|
161
|
+
// RuntimeEnv — the boundary this module owns: marker matching, the marker
|
|
162
|
+
// fingerprint and the version probe. The table above stays pure data, and
|
|
163
|
+
// discovery is one loop over it (D9).
|
|
164
|
+
// ---------------------------------------------------------------------------
|
|
158
165
|
|
|
159
|
-
interface
|
|
160
|
-
|
|
161
|
-
|
|
166
|
+
export interface RuntimeEnv {
|
|
167
|
+
readonly matches: (cwd: string, def: RuntimeDef) => Effect.Effect<boolean>;
|
|
168
|
+
readonly fingerprint: (cwd: string, def: RuntimeDef) => Effect.Effect<string>;
|
|
169
|
+
readonly version: (def: RuntimeDef, cwd: string) => Effect.Effect<string | undefined>;
|
|
162
170
|
}
|
|
163
171
|
|
|
164
|
-
|
|
165
|
-
const
|
|
172
|
+
/** The directory listing, or `[]` when the directory cannot be read. */
|
|
173
|
+
const readDirectory = (fs: FileSystem.FileSystem, dir: string): Effect.Effect<readonly string[]> =>
|
|
174
|
+
fs.readDirectory(dir).pipe(Effect.orElseSucceed(() => []));
|
|
166
175
|
|
|
167
|
-
|
|
168
|
-
|
|
169
|
-
|
|
170
|
-
try {
|
|
171
|
-
const stat = statSync(join(cwd, f));
|
|
172
|
-
parts.push(`${f}:${stat.mtimeMs}`);
|
|
173
|
-
} catch {
|
|
174
|
-
/* ignore */
|
|
175
|
-
}
|
|
176
|
-
}
|
|
177
|
-
if (def.extensions || def.folders) {
|
|
178
|
-
try {
|
|
179
|
-
const entries = readdirSync(cwd);
|
|
180
|
-
parts.push(...entries.slice().sort());
|
|
181
|
-
} catch {
|
|
182
|
-
/* ignore */
|
|
183
|
-
}
|
|
184
|
-
}
|
|
185
|
-
if (def.env && process.env[def.env]) {
|
|
186
|
-
parts.push(`${def.env}=${process.env[def.env]}`);
|
|
187
|
-
}
|
|
188
|
-
return parts.join("\0");
|
|
189
|
-
}
|
|
190
|
-
|
|
191
|
-
function matchesDef(cwd: string, def: RuntimeDef): boolean {
|
|
192
|
-
if (def.env && process.env[def.env]) return true;
|
|
193
|
-
if (def.files.some((f) => existsSync(join(cwd, f)))) return true;
|
|
194
|
-
if (def.folders?.some((f) => existsSync(join(cwd, f)))) return true;
|
|
195
|
-
if (def.extensions) {
|
|
196
|
-
try {
|
|
197
|
-
const entries = readdirSync(cwd);
|
|
198
|
-
if (entries.some((e) => def.extensions!.some((ext) => e.endsWith(ext)))) return true;
|
|
199
|
-
} catch {
|
|
200
|
-
/* ignore */
|
|
201
|
-
}
|
|
202
|
-
}
|
|
203
|
-
return false;
|
|
204
|
-
}
|
|
205
|
-
|
|
206
|
-
async function fetchVersion(def: RuntimeDef, cwd: string): Promise<string | undefined> {
|
|
207
|
-
if (!def.versionCommand) return undefined;
|
|
208
|
-
try {
|
|
209
|
-
const { stdout } = await execFileAsync(def.versionCommand.cmd, def.versionCommand.args ?? [], {
|
|
210
|
-
cwd,
|
|
211
|
-
timeout: VERSION_TIMEOUT_MS,
|
|
212
|
-
maxBuffer: 64 * 1024,
|
|
213
|
-
});
|
|
214
|
-
if (def.versionCommand.pattern) {
|
|
215
|
-
const match = stdout.match(def.versionCommand.pattern);
|
|
216
|
-
return match?.[1];
|
|
217
|
-
}
|
|
218
|
-
return stdout.trim() || undefined;
|
|
219
|
-
} catch {
|
|
220
|
-
return undefined;
|
|
221
|
-
}
|
|
222
|
-
}
|
|
176
|
+
/** True when the path exists; an unreadable path is a non-match, not a failure. */
|
|
177
|
+
const exists = (fs: FileSystem.FileSystem, path: string): Effect.Effect<boolean> =>
|
|
178
|
+
fs.exists(path).pipe(Effect.orElseSucceed(() => false));
|
|
223
179
|
|
|
224
|
-
/**
|
|
225
|
-
|
|
226
|
-
* version when the runtime's version command answers. Results are cached per
|
|
227
|
-
* `(cwd, runtime)` and invalidated by a fingerprint of the marker files.
|
|
228
|
-
*/
|
|
229
|
-
export async function readRuntimeInfo(cwd: string): Promise<RuntimeInfo[]> {
|
|
180
|
+
/** Every runtime that matches `cwd`, in table order (D9: one loop). */
|
|
181
|
+
export const discoverRuntimes = Effect.fnUntraced(function* (cwd: string, env: RuntimeEnv) {
|
|
230
182
|
const matches: RuntimeInfo[] = [];
|
|
231
183
|
for (const def of RUNTIMES) {
|
|
232
|
-
if (!
|
|
233
|
-
|
|
184
|
+
if (!(yield* env.matches(cwd, def))) continue;
|
|
185
|
+
const version = yield* env.version(def, cwd);
|
|
186
|
+
matches.push({ name: def.name, ...(version === undefined ? {} : { version }) });
|
|
234
187
|
}
|
|
235
188
|
return matches;
|
|
236
|
-
}
|
|
237
|
-
|
|
238
|
-
async function resolveRuntime(cwd: string, def: RuntimeDef): Promise<RuntimeInfo> {
|
|
239
|
-
const fp = fingerprint(cwd, def);
|
|
240
|
-
const cacheKey = `${cwd}\0${def.name}`;
|
|
241
|
-
const cached = cache.get(cacheKey);
|
|
242
|
-
if (cached && cached.fingerprint === fp) return cached.runtime;
|
|
189
|
+
});
|
|
243
190
|
|
|
244
|
-
|
|
245
|
-
|
|
246
|
-
|
|
247
|
-
|
|
248
|
-
|
|
249
|
-
|
|
250
|
-
|
|
251
|
-
|
|
252
|
-
|
|
253
|
-
|
|
191
|
+
/** The production env over the platform services and two injected primitives (D19). */
|
|
192
|
+
export const platformRuntimeEnv = (
|
|
193
|
+
fs: FileSystem.FileSystem,
|
|
194
|
+
spawner: CP.ChildProcessSpawner.ChildProcessSpawner["Service"],
|
|
195
|
+
path: Path.Path,
|
|
196
|
+
getEnv: (name: string) => string | undefined,
|
|
197
|
+
): RuntimeEnv => ({
|
|
198
|
+
matches: Effect.fnUntraced(function* (cwd: string, def: RuntimeDef) {
|
|
199
|
+
// One env read: an empty name means "no environment marker" either way.
|
|
200
|
+
const envValue = isNonEmptyString(def.env) ? getEnv(def.env) : undefined;
|
|
201
|
+
if (isNonEmptyString(envValue)) return true;
|
|
202
|
+
for (const file of def.files) {
|
|
203
|
+
if (yield* exists(fs, path.join(cwd, file))) return true;
|
|
204
|
+
}
|
|
205
|
+
for (const folder of def.folders ?? []) {
|
|
206
|
+
if (yield* exists(fs, path.join(cwd, folder))) return true;
|
|
207
|
+
}
|
|
208
|
+
if (def.extensions !== undefined && def.extensions.length > 0) {
|
|
209
|
+
const entries = yield* readDirectory(fs, cwd);
|
|
210
|
+
if (entries.some((entry) => def.extensions!.some((ext) => entry.endsWith(ext)))) {
|
|
211
|
+
return true;
|
|
212
|
+
}
|
|
213
|
+
}
|
|
214
|
+
return false;
|
|
215
|
+
}),
|
|
216
|
+
fingerprint: Effect.fnUntraced(function* (cwd: string, def: RuntimeDef) {
|
|
217
|
+
const parts: string[] = [];
|
|
218
|
+
for (const file of def.files) {
|
|
219
|
+
const info = yield* Effect.option(fs.stat(path.join(cwd, file)));
|
|
220
|
+
if (Option.isNone(info)) continue;
|
|
221
|
+
// `Option.none` means the platform reports no mtime; the old
|
|
222
|
+
// `statSync(f).mtimeMs` read is `Date.getTime()` when present.
|
|
223
|
+
const mtime = Option.match(info.value.mtime, {
|
|
224
|
+
onNone: () => 0,
|
|
225
|
+
onSome: (date) => date.getTime(),
|
|
226
|
+
});
|
|
227
|
+
parts.push(`${file}:${mtime}`);
|
|
228
|
+
}
|
|
229
|
+
// A present-but-empty list matches nothing, so only a non-empty one makes the
|
|
230
|
+
// directory listing part of the fingerprint.
|
|
231
|
+
if (
|
|
232
|
+
(def.extensions !== undefined && def.extensions.length > 0) ||
|
|
233
|
+
(def.folders !== undefined && def.folders.length > 0)
|
|
234
|
+
) {
|
|
235
|
+
const entries = yield* readDirectory(fs, cwd);
|
|
236
|
+
parts.push(...entries.slice().sort());
|
|
237
|
+
}
|
|
238
|
+
const envValue = def.env === undefined ? undefined : getEnv(def.env);
|
|
239
|
+
if (isNonEmptyString(envValue)) parts.push(`${def.env}=${envValue}`);
|
|
240
|
+
return parts.join("\0");
|
|
241
|
+
}),
|
|
242
|
+
version: Effect.fnUntraced(
|
|
243
|
+
function* (def: RuntimeDef, cwd: string) {
|
|
244
|
+
const command = def.versionCommand;
|
|
245
|
+
if (command === undefined) return undefined;
|
|
246
|
+
// One run: drain both pipes (an unread pipe blocks a chatty child), keep
|
|
247
|
+
// the head of stdout, then read the exit code. `execFile` rejected on a
|
|
248
|
+
// non-zero exit and the old `catch` made that "no version"; the platform
|
|
249
|
+
// string helper ignores the code, so the check is explicit here.
|
|
250
|
+
const output = yield* Effect.scoped(
|
|
251
|
+
Effect.gen(function* () {
|
|
252
|
+
const handle = yield* spawner.spawn(
|
|
253
|
+
CP.ChildProcess.make(command.cmd, command.args ?? [], { cwd }),
|
|
254
|
+
);
|
|
255
|
+
const stderrDrain = yield* Stream.runDrain(handle.stderr).pipe(Effect.forkChild);
|
|
256
|
+
const kept: Uint8Array[] = [];
|
|
257
|
+
let keptBytes = 0;
|
|
258
|
+
yield* Stream.runForEach(handle.stdout, (chunk) =>
|
|
259
|
+
Effect.sync(() => {
|
|
260
|
+
const room = MAX_STDOUT_BYTES - keptBytes;
|
|
261
|
+
if (room <= 0) return; // over the cap: keep draining, keep nothing
|
|
262
|
+
const piece = chunk.length <= room ? chunk : chunk.subarray(0, room);
|
|
263
|
+
kept.push(piece);
|
|
264
|
+
keptBytes += piece.length;
|
|
265
|
+
}),
|
|
266
|
+
);
|
|
267
|
+
const exitCode = yield* handle.exitCode;
|
|
268
|
+
yield* Fiber.join(stderrDrain);
|
|
269
|
+
if (exitCode !== 0) return undefined;
|
|
270
|
+
const bytes = new Uint8Array(keptBytes);
|
|
271
|
+
let offset = 0;
|
|
272
|
+
for (const piece of kept) {
|
|
273
|
+
bytes.set(piece, offset);
|
|
274
|
+
offset += piece.length;
|
|
275
|
+
}
|
|
276
|
+
return new TextDecoder().decode(bytes);
|
|
277
|
+
}),
|
|
278
|
+
);
|
|
279
|
+
if (output === undefined) return undefined;
|
|
280
|
+
if (command.pattern !== undefined) return output.match(command.pattern)?.[1];
|
|
281
|
+
return output.trim() || undefined;
|
|
282
|
+
},
|
|
283
|
+
Effect.timeoutOption(VERSION_TIMEOUT_MS),
|
|
284
|
+
Effect.map(Option.getOrUndefined),
|
|
285
|
+
Effect.orElseSucceed(() => undefined),
|
|
286
|
+
),
|
|
287
|
+
});
|
|
@@ -0,0 +1,95 @@
|
|
|
1
|
+
// Each test is its own entry point: it builds a fresh layer for one scenario and
|
|
2
|
+
// runs its effects inside it, so providing there is the pattern the rule allows.
|
|
3
|
+
/* oxlint-disable effecttsgo/strict-effect-provide */
|
|
4
|
+
import { assert, it } from "@effect/vitest";
|
|
5
|
+
import { Effect } from "effect";
|
|
6
|
+
import { SessionLifecycleService } from "./session-lifecycle.ts";
|
|
7
|
+
|
|
8
|
+
// ---------------------------------------------------------------------------
|
|
9
|
+
// SessionLifecycleService — the generation counter resolved from the layer
|
|
10
|
+
// graph. Same behaviour as the plain class (session-lifecycle.test.ts), plus
|
|
11
|
+
// one instance per layer build.
|
|
12
|
+
// ---------------------------------------------------------------------------
|
|
13
|
+
|
|
14
|
+
it.effect("starting a session advances the current generation", () =>
|
|
15
|
+
Effect.gen(function* () {
|
|
16
|
+
// Arrange
|
|
17
|
+
const lifecycle = yield* SessionLifecycleService;
|
|
18
|
+
|
|
19
|
+
// Act
|
|
20
|
+
lifecycle.start();
|
|
21
|
+
|
|
22
|
+
// Assert
|
|
23
|
+
assert.strictEqual(lifecycle.currentGeneration(), 1);
|
|
24
|
+
}).pipe(Effect.provide(SessionLifecycleService.layerTest)),
|
|
25
|
+
);
|
|
26
|
+
|
|
27
|
+
it.effect("a generation captured before a restart is no longer current", () =>
|
|
28
|
+
Effect.gen(function* () {
|
|
29
|
+
// Arrange
|
|
30
|
+
const lifecycle = yield* SessionLifecycleService;
|
|
31
|
+
lifecycle.start();
|
|
32
|
+
const generation = lifecycle.currentGeneration();
|
|
33
|
+
|
|
34
|
+
// Act
|
|
35
|
+
lifecycle.start();
|
|
36
|
+
|
|
37
|
+
// Assert
|
|
38
|
+
assert.strictEqual(lifecycle.isCurrent(generation), false);
|
|
39
|
+
assert.strictEqual(lifecycle.isCurrent(lifecycle.currentGeneration()), true);
|
|
40
|
+
assert.strictEqual(lifecycle.isCurrent(), true);
|
|
41
|
+
}).pipe(Effect.provide(SessionLifecycleService.layerTest)),
|
|
42
|
+
);
|
|
43
|
+
|
|
44
|
+
it.effect("shutdown makes every generation stale, including the current one", () =>
|
|
45
|
+
Effect.gen(function* () {
|
|
46
|
+
// Arrange
|
|
47
|
+
const lifecycle = yield* SessionLifecycleService;
|
|
48
|
+
lifecycle.start();
|
|
49
|
+
|
|
50
|
+
// Act
|
|
51
|
+
lifecycle.shutdown();
|
|
52
|
+
|
|
53
|
+
// Assert
|
|
54
|
+
assert.strictEqual(lifecycle.isCurrent(), false);
|
|
55
|
+
assert.strictEqual(lifecycle.isCurrent(lifecycle.currentGeneration()), false);
|
|
56
|
+
assert.strictEqual(lifecycle.currentGeneration(), 1);
|
|
57
|
+
}).pipe(Effect.provide(SessionLifecycleService.layerTest)),
|
|
58
|
+
);
|
|
59
|
+
|
|
60
|
+
it.effect("a restart after shutdown is current again", () =>
|
|
61
|
+
Effect.gen(function* () {
|
|
62
|
+
// Arrange
|
|
63
|
+
const lifecycle = yield* SessionLifecycleService;
|
|
64
|
+
lifecycle.start();
|
|
65
|
+
lifecycle.shutdown();
|
|
66
|
+
|
|
67
|
+
// Act
|
|
68
|
+
lifecycle.start();
|
|
69
|
+
|
|
70
|
+
// Assert
|
|
71
|
+
assert.strictEqual(lifecycle.isCurrent(), true);
|
|
72
|
+
assert.strictEqual(lifecycle.currentGeneration(), 2);
|
|
73
|
+
}).pipe(Effect.provide(SessionLifecycleService.layerTest)),
|
|
74
|
+
);
|
|
75
|
+
|
|
76
|
+
it.effect("two layer builds have independent counters", () =>
|
|
77
|
+
Effect.gen(function* () {
|
|
78
|
+
// Arrange: one build advances twice.
|
|
79
|
+
const first = yield* Effect.service(SessionLifecycleService).pipe(
|
|
80
|
+
Effect.provide(SessionLifecycleService.layer),
|
|
81
|
+
);
|
|
82
|
+
first.start();
|
|
83
|
+
first.start();
|
|
84
|
+
|
|
85
|
+
// Act: a second layer build sees its own counter.
|
|
86
|
+
const second = yield* Effect.service(SessionLifecycleService).pipe(
|
|
87
|
+
Effect.provide(SessionLifecycleService.layer),
|
|
88
|
+
);
|
|
89
|
+
|
|
90
|
+
// Assert
|
|
91
|
+
assert.strictEqual(first.currentGeneration(), 2);
|
|
92
|
+
assert.strictEqual(second.currentGeneration(), 0);
|
|
93
|
+
assert.strictEqual(second.isCurrent(), true);
|
|
94
|
+
}),
|
|
95
|
+
);
|
|
@@ -0,0 +1,77 @@
|
|
|
1
|
+
import { assert, it } from "@effect/vitest";
|
|
2
|
+
import { SessionLifecycle } from "./session-lifecycle.ts";
|
|
3
|
+
|
|
4
|
+
// ---------------------------------------------------------------------------
|
|
5
|
+
// SessionLifecycle — characterisation of the pure generation counter.
|
|
6
|
+
// The class has no dependencies; these cases pin the behaviour the service
|
|
7
|
+
// wraps (D1), so the service conversion proves parity rather than existence.
|
|
8
|
+
// ---------------------------------------------------------------------------
|
|
9
|
+
|
|
10
|
+
it("starting a session advances the current generation", () => {
|
|
11
|
+
// Arrange
|
|
12
|
+
const lifecycle = new SessionLifecycle();
|
|
13
|
+
|
|
14
|
+
// Act
|
|
15
|
+
lifecycle.start();
|
|
16
|
+
|
|
17
|
+
// Assert
|
|
18
|
+
assert.strictEqual(lifecycle.currentGeneration(), 1);
|
|
19
|
+
});
|
|
20
|
+
|
|
21
|
+
it("a generation captured before a restart is no longer current", () => {
|
|
22
|
+
// Arrange
|
|
23
|
+
const lifecycle = new SessionLifecycle();
|
|
24
|
+
lifecycle.start();
|
|
25
|
+
const generation = lifecycle.currentGeneration();
|
|
26
|
+
|
|
27
|
+
// Act
|
|
28
|
+
lifecycle.start();
|
|
29
|
+
|
|
30
|
+
// Assert
|
|
31
|
+
assert.strictEqual(lifecycle.isCurrent(generation), false);
|
|
32
|
+
assert.strictEqual(lifecycle.isCurrent(lifecycle.currentGeneration()), true);
|
|
33
|
+
assert.strictEqual(lifecycle.isCurrent(), true);
|
|
34
|
+
});
|
|
35
|
+
|
|
36
|
+
it("shutdown makes every generation stale, including the current one", () => {
|
|
37
|
+
// Arrange
|
|
38
|
+
const lifecycle = new SessionLifecycle();
|
|
39
|
+
lifecycle.start();
|
|
40
|
+
|
|
41
|
+
// Act
|
|
42
|
+
lifecycle.shutdown();
|
|
43
|
+
|
|
44
|
+
// Assert
|
|
45
|
+
assert.strictEqual(lifecycle.isCurrent(), false);
|
|
46
|
+
assert.strictEqual(lifecycle.isCurrent(lifecycle.currentGeneration()), false);
|
|
47
|
+
assert.strictEqual(lifecycle.currentGeneration(), 1);
|
|
48
|
+
});
|
|
49
|
+
|
|
50
|
+
it("a restart after shutdown is current again", () => {
|
|
51
|
+
// Arrange
|
|
52
|
+
const lifecycle = new SessionLifecycle();
|
|
53
|
+
lifecycle.start();
|
|
54
|
+
lifecycle.shutdown();
|
|
55
|
+
|
|
56
|
+
// Act
|
|
57
|
+
lifecycle.start();
|
|
58
|
+
|
|
59
|
+
// Assert
|
|
60
|
+
assert.strictEqual(lifecycle.isCurrent(), true);
|
|
61
|
+
assert.strictEqual(lifecycle.currentGeneration(), 2);
|
|
62
|
+
});
|
|
63
|
+
|
|
64
|
+
it("two instances have independent counters", () => {
|
|
65
|
+
// Arrange
|
|
66
|
+
const first = new SessionLifecycle();
|
|
67
|
+
const second = new SessionLifecycle();
|
|
68
|
+
|
|
69
|
+
// Act
|
|
70
|
+
first.start();
|
|
71
|
+
first.start();
|
|
72
|
+
|
|
73
|
+
// Assert
|
|
74
|
+
assert.strictEqual(first.currentGeneration(), 2);
|
|
75
|
+
assert.strictEqual(second.currentGeneration(), 0);
|
|
76
|
+
assert.strictEqual(second.isCurrent(), true);
|
|
77
|
+
});
|
package/src/session-lifecycle.ts
CHANGED
|
@@ -1,3 +1,5 @@
|
|
|
1
|
+
import { Context, Layer } from "effect";
|
|
2
|
+
|
|
1
3
|
export class SessionLifecycle {
|
|
2
4
|
private current = 0;
|
|
3
5
|
private shutDown = false;
|
|
@@ -21,3 +23,22 @@ export class SessionLifecycle {
|
|
|
21
23
|
return this.current;
|
|
22
24
|
}
|
|
23
25
|
}
|
|
26
|
+
|
|
27
|
+
/**
|
|
28
|
+
* The session generation counter resolved from the layer graph. The pure
|
|
29
|
+
* `SessionLifecycle` class stays the state machine; the service only moves
|
|
30
|
+
* acquisition and lifetime into the environment, so two layer builds cannot
|
|
31
|
+
* see each other's generation.
|
|
32
|
+
*/
|
|
33
|
+
export class SessionLifecycleService extends Context.Service<
|
|
34
|
+
SessionLifecycleService,
|
|
35
|
+
Pick<SessionLifecycle, "start" | "shutdown" | "isCurrent" | "currentGeneration">
|
|
36
|
+
>()("@ftrdotdev/pi-tui/session-lifecycle/SessionLifecycleService") {
|
|
37
|
+
static readonly layer: Layer.Layer<SessionLifecycleService> = Layer.sync(
|
|
38
|
+
SessionLifecycleService,
|
|
39
|
+
() => SessionLifecycleService.of(new SessionLifecycle()),
|
|
40
|
+
);
|
|
41
|
+
|
|
42
|
+
/** Test layer: same construction, one fresh counter per build. */
|
|
43
|
+
static readonly layerTest: Layer.Layer<SessionLifecycleService> = SessionLifecycleService.layer;
|
|
44
|
+
}
|
package/src/state.test.ts
CHANGED
|
@@ -1,6 +1,8 @@
|
|
|
1
|
-
import { assert, it } from "@effect/vitest";
|
|
2
|
-
import
|
|
3
|
-
import {
|
|
1
|
+
import { assert, beforeEach, it } from "@effect/vitest";
|
|
2
|
+
import { themeDouble } from "@ftrdotdev/pi-test-kit";
|
|
3
|
+
import { footerCtxDouble } from "../test-support/doubles.ts";
|
|
4
|
+
import type { FooterState, SessionEntry, UsageTotals } from "./state.ts";
|
|
5
|
+
import { createInitialState, getUsageTotals, invalidateUsageCache } from "./state.ts";
|
|
4
6
|
import { GitStatus } from "./commands/git-status.ts";
|
|
5
7
|
|
|
6
8
|
it("createInitialState seeds git with an all-zero empty status", () => {
|
|
@@ -14,3 +16,130 @@ it("createInitialState starts with a fresh tracker and no done figure", () => {
|
|
|
14
16
|
assert.strictEqual(s.tracker.isWaiting(), false);
|
|
15
17
|
assert.deepStrictEqual(s.tracker.breakdown(0), { inference: 0, tool: 0, wait: 0, total: 0 });
|
|
16
18
|
});
|
|
19
|
+
|
|
20
|
+
// ---------------------------------------------------------------------------
|
|
21
|
+
// getUsageTotals — characterisation of the module cache the service replaces
|
|
22
|
+
// (D1). The adapter stays as the plain provider's parity oracle (D13).
|
|
23
|
+
// ---------------------------------------------------------------------------
|
|
24
|
+
|
|
25
|
+
/** pi's session entries carry more fields than the fold reads; one documented cast. */
|
|
26
|
+
const entry = (value: unknown): SessionEntry => value as SessionEntry;
|
|
27
|
+
|
|
28
|
+
interface ScriptedUsage {
|
|
29
|
+
input: number;
|
|
30
|
+
output: number;
|
|
31
|
+
cacheRead: number;
|
|
32
|
+
cacheWrite: number;
|
|
33
|
+
cost: number;
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
const assistant = (id: string, usage: ScriptedUsage): SessionEntry =>
|
|
37
|
+
entry({
|
|
38
|
+
type: "message",
|
|
39
|
+
id,
|
|
40
|
+
parentId: null,
|
|
41
|
+
timestamp: `t-${id}`,
|
|
42
|
+
message: {
|
|
43
|
+
role: "assistant",
|
|
44
|
+
content: [],
|
|
45
|
+
usage: {
|
|
46
|
+
input: usage.input,
|
|
47
|
+
output: usage.output,
|
|
48
|
+
cacheRead: usage.cacheRead,
|
|
49
|
+
cacheWrite: usage.cacheWrite,
|
|
50
|
+
totalTokens: usage.input + usage.output + usage.cacheRead + usage.cacheWrite,
|
|
51
|
+
cost: { total: usage.cost },
|
|
52
|
+
},
|
|
53
|
+
},
|
|
54
|
+
});
|
|
55
|
+
|
|
56
|
+
const user = (id: string): SessionEntry =>
|
|
57
|
+
entry({
|
|
58
|
+
type: "message",
|
|
59
|
+
id,
|
|
60
|
+
parentId: null,
|
|
61
|
+
timestamp: `t-${id}`,
|
|
62
|
+
message: { role: "user", content: [] },
|
|
63
|
+
});
|
|
64
|
+
|
|
65
|
+
const ctxOver = (entries: () => readonly SessionEntry[]) =>
|
|
66
|
+
footerCtxDouble({
|
|
67
|
+
model: {},
|
|
68
|
+
cwd: "/workspace/pi-mono",
|
|
69
|
+
getContextUsage: () => undefined,
|
|
70
|
+
sessionManager: { getEntries: entries },
|
|
71
|
+
ui: { theme: themeDouble() },
|
|
72
|
+
});
|
|
73
|
+
|
|
74
|
+
const EXPECTED: UsageTotals = {
|
|
75
|
+
input: 150,
|
|
76
|
+
output: 50,
|
|
77
|
+
cacheRead: 30,
|
|
78
|
+
cacheWrite: 20,
|
|
79
|
+
cost: 0.03,
|
|
80
|
+
latestCacheHitRate: 30,
|
|
81
|
+
};
|
|
82
|
+
|
|
83
|
+
const fixture = () => [
|
|
84
|
+
assistant("a1", { input: 100, output: 40, cacheRead: 0, cacheWrite: 0, cost: 0.01 }),
|
|
85
|
+
user("u1"),
|
|
86
|
+
assistant("a2", { input: 50, output: 10, cacheRead: 30, cacheWrite: 20, cost: 0.02 }),
|
|
87
|
+
];
|
|
88
|
+
|
|
89
|
+
// The cache is a single module slot, so every test starts empty.
|
|
90
|
+
beforeEach(() => invalidateUsageCache());
|
|
91
|
+
|
|
92
|
+
it("the totals fold assistant usage and ignore other roles", () => {
|
|
93
|
+
// Arrange
|
|
94
|
+
const ctx = ctxOver(() => fixture());
|
|
95
|
+
|
|
96
|
+
// Act/Assert: the user entry contributes nothing.
|
|
97
|
+
assert.deepStrictEqual(getUsageTotals(ctx), EXPECTED);
|
|
98
|
+
});
|
|
99
|
+
|
|
100
|
+
it("a repeated read with the same entries returns the same object", () => {
|
|
101
|
+
// Arrange
|
|
102
|
+
const ctx = ctxOver(() => fixture());
|
|
103
|
+
|
|
104
|
+
// Act
|
|
105
|
+
const first = getUsageTotals(ctx);
|
|
106
|
+
const second = getUsageTotals(ctx);
|
|
107
|
+
|
|
108
|
+
// Assert
|
|
109
|
+
assert.strictEqual(second, first);
|
|
110
|
+
});
|
|
111
|
+
|
|
112
|
+
it("invalidation re-folds the same entries into a new object with equal values", () => {
|
|
113
|
+
// Arrange
|
|
114
|
+
const ctx = ctxOver(() => fixture());
|
|
115
|
+
const before = getUsageTotals(ctx);
|
|
116
|
+
|
|
117
|
+
// Act
|
|
118
|
+
invalidateUsageCache();
|
|
119
|
+
const after = getUsageTotals(ctx);
|
|
120
|
+
|
|
121
|
+
// Assert
|
|
122
|
+
assert.notStrictEqual(after, before);
|
|
123
|
+
assert.deepStrictEqual(after, before);
|
|
124
|
+
});
|
|
125
|
+
|
|
126
|
+
it("a changed entries list is re-folded without an explicit invalidate", () => {
|
|
127
|
+
// Arrange: two entries, then one more assistant message.
|
|
128
|
+
const entries = fixture();
|
|
129
|
+
const ctx = ctxOver(() => entries);
|
|
130
|
+
getUsageTotals(ctx);
|
|
131
|
+
|
|
132
|
+
// Act
|
|
133
|
+
entries.push(assistant("a3", { input: 5, output: 5, cacheRead: 0, cacheWrite: 0, cost: 0.005 }));
|
|
134
|
+
const totals = getUsageTotals(ctx);
|
|
135
|
+
|
|
136
|
+
// Assert: IEEE addition of the three totals, exactly as the fold computes it.
|
|
137
|
+
assert.deepStrictEqual(totals, {
|
|
138
|
+
input: 155,
|
|
139
|
+
output: 55,
|
|
140
|
+
cacheRead: 30,
|
|
141
|
+
cacheWrite: 20,
|
|
142
|
+
cost: 0.034999999999999996,
|
|
143
|
+
latestCacheHitRate: 0,
|
|
144
|
+
});
|
|
145
|
+
});
|
package/src/state.ts
CHANGED
|
@@ -24,18 +24,16 @@ export interface UsageTotals {
|
|
|
24
24
|
latestCacheHitRate: number | undefined;
|
|
25
25
|
}
|
|
26
26
|
|
|
27
|
-
|
|
27
|
+
/** One session entry, as the usage fold reads it (role-tagged message entries). */
|
|
28
|
+
export type SessionEntry = ReturnType<ExtensionContext["sessionManager"]["getEntries"]>[number];
|
|
28
29
|
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
return `${entries.length}:${last?.id ?? ""}:${last?.timestamp ?? ""}`;
|
|
30
|
+
export interface UsageCache {
|
|
31
|
+
readonly totals: (key: string, entries: readonly SessionEntry[]) => UsageTotals;
|
|
32
|
+
readonly invalidate: () => void;
|
|
33
33
|
}
|
|
34
34
|
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
if (usageCache && usageCache.key === key) return usageCache.totals;
|
|
38
|
-
|
|
35
|
+
/** The pure fold over session entries (characterisation: `state.test.ts`). */
|
|
36
|
+
export const foldUsageTotals = (entries: readonly SessionEntry[]): UsageTotals => {
|
|
39
37
|
const totals: UsageTotals = {
|
|
40
38
|
input: 0,
|
|
41
39
|
output: 0,
|
|
@@ -44,11 +42,11 @@ export function getUsageTotals(ctx: ExtensionContext): UsageTotals {
|
|
|
44
42
|
cost: 0,
|
|
45
43
|
latestCacheHitRate: undefined,
|
|
46
44
|
};
|
|
47
|
-
for (const entry of
|
|
45
|
+
for (const entry of entries) {
|
|
48
46
|
if (entry.type === "message" && entry.message?.role === "assistant") {
|
|
49
47
|
const m = entry.message as AssistantMessage;
|
|
50
48
|
const u = m.usage;
|
|
51
|
-
if (
|
|
49
|
+
if (u === undefined) continue;
|
|
52
50
|
totals.input += u.input ?? 0;
|
|
53
51
|
totals.output += u.output ?? 0;
|
|
54
52
|
totals.cacheRead += u.cacheRead ?? 0;
|
|
@@ -60,12 +58,44 @@ export function getUsageTotals(ctx: ExtensionContext): UsageTotals {
|
|
|
60
58
|
}
|
|
61
59
|
}
|
|
62
60
|
}
|
|
63
|
-
usageCache = { key, totals };
|
|
64
61
|
return totals;
|
|
62
|
+
};
|
|
63
|
+
|
|
64
|
+
/** One cache implementation shared by the service and the legacy plain adapter. */
|
|
65
|
+
export const createUsageCache = (): UsageCache => {
|
|
66
|
+
let cached: { key: string; totals: UsageTotals } | undefined;
|
|
67
|
+
return {
|
|
68
|
+
totals: (key, entries) => {
|
|
69
|
+
if (cached !== undefined && cached.key === key) return cached.totals;
|
|
70
|
+
const totals = foldUsageTotals(entries);
|
|
71
|
+
cached = { key, totals };
|
|
72
|
+
return totals;
|
|
73
|
+
},
|
|
74
|
+
invalidate: () => {
|
|
75
|
+
cached = undefined;
|
|
76
|
+
},
|
|
77
|
+
};
|
|
78
|
+
};
|
|
79
|
+
|
|
80
|
+
function entriesKey(ctx: ExtensionContext): string {
|
|
81
|
+
const entries = ctx.sessionManager.getEntries();
|
|
82
|
+
const last = entries.at(-1);
|
|
83
|
+
return `${entries.length}:${last?.id ?? ""}:${last?.timestamp ?? ""}`;
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
/**
|
|
87
|
+
* Plain-provider adapter over the same cache implementation (legacy, D13).
|
|
88
|
+
* Plan 1's frozen provider calls this; it is the parity oracle for
|
|
89
|
+
* `UsageTotalsService` and is deleted when that provider is retired.
|
|
90
|
+
*/
|
|
91
|
+
const plainUsageCache = createUsageCache();
|
|
92
|
+
|
|
93
|
+
export function getUsageTotals(ctx: ExtensionContext): UsageTotals {
|
|
94
|
+
return plainUsageCache.totals(entriesKey(ctx), ctx.sessionManager.getEntries());
|
|
65
95
|
}
|
|
66
96
|
|
|
67
97
|
export function invalidateUsageCache(): void {
|
|
68
|
-
|
|
98
|
+
plainUsageCache.invalidate();
|
|
69
99
|
}
|
|
70
100
|
|
|
71
101
|
export function createInitialState(): FooterState {
|