@firstpick/pi-package-webui 0.8.3 → 0.8.4
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 +67 -16
- package/bin/pi-webui.mjs +769 -130
- package/lib/WEBUI_TUI_NATIVE_PARITY.json +26 -0
- package/lib/optional-feature-catalog.mjs +29 -0
- package/lib/optional-feature-migration.mjs +410 -0
- package/lib/session-summary-core.mjs +320 -0
- package/lib/session-summary-preferences.mjs +267 -0
- package/package.json +5 -42
- package/public/app.js +1280 -51
- package/public/index.html +42 -0
- package/public/styles.css +345 -1
- package/session-summary.ts +403 -0
- package/tests/aur-review-widget-static.test.mjs +3 -2
- package/tests/browser/session-summary.spec.mjs +271 -0
- package/tests/codex-fast-mode-static.test.mjs +8 -7
- package/tests/http-endpoints-harness.test.mjs +419 -3
- package/tests/mobile-static.test.mjs +90 -92
- package/tests/native-parity-harness.test.mjs +9 -1
- package/tests/native-parity.test.mjs +23 -1
- package/tests/optional-feature-migration-frontend.test.mjs +72 -0
- package/tests/optional-feature-migration.test.mjs +142 -0
- package/tests/session-summary-core.test.mjs +491 -0
- package/tests/session-summary-preferences.test.mjs +103 -0
|
@@ -0,0 +1,142 @@
|
|
|
1
|
+
import assert from "node:assert/strict";
|
|
2
|
+
import { mkdir, mkdtemp, readFile, rm, stat } from "node:fs/promises";
|
|
3
|
+
import { tmpdir } from "node:os";
|
|
4
|
+
import path from "node:path";
|
|
5
|
+
import { setTimeout as delay } from "node:timers/promises";
|
|
6
|
+
import {
|
|
7
|
+
OptionalFeatureAuditCoordinator,
|
|
8
|
+
OptionalFeatureMigrationStore,
|
|
9
|
+
classifyOptionalFeature,
|
|
10
|
+
} from "../lib/optional-feature-migration.mjs";
|
|
11
|
+
|
|
12
|
+
const root = await mkdtemp(path.join(tmpdir(), "pi-webui-optional-feature-migration-"));
|
|
13
|
+
const stateFile = path.join(root, "private", "optional-feature-migration.json");
|
|
14
|
+
const catalog = [
|
|
15
|
+
{ featureId: "registered", packageName: "@test/registered", expectedSpec: "^1.0.0" },
|
|
16
|
+
{ featureId: "local", packageName: "@test/local", expectedSpec: "^1.0.0" },
|
|
17
|
+
{ featureId: "legacy", packageName: "@test/legacy", expectedSpec: "^1.0.0" },
|
|
18
|
+
{ featureId: "conflict", packageName: "@test/conflict", expectedSpec: "^1.0.0" },
|
|
19
|
+
{ featureId: "missing", packageName: "@test/missing", expectedSpec: "^1.0.0" },
|
|
20
|
+
];
|
|
21
|
+
|
|
22
|
+
try {
|
|
23
|
+
assert.equal(classifyOptionalFeature({ configured: true, installed: true }, {}).state, "registered");
|
|
24
|
+
assert.equal(classifyOptionalFeature({ locallyConfigured: true }, {}).state, "local-resource");
|
|
25
|
+
assert.equal(classifyOptionalFeature({ legacyEvidence: true }, {}).state, "legacy-migratable");
|
|
26
|
+
assert.equal(classifyOptionalFeature({ installed: true }, {}).state, "unknown");
|
|
27
|
+
assert.equal(classifyOptionalFeature({}, {}).state, "missing");
|
|
28
|
+
assert.equal(classifyOptionalFeature({ resourceConflict: true }, {}).state, "conflict");
|
|
29
|
+
assert.equal(classifyOptionalFeature({ configured: true, installed: true, updateAvailable: true }, {}).state, "update-available");
|
|
30
|
+
assert.equal(classifyOptionalFeature({}, { available: true, enabled: false }).state, "disabled");
|
|
31
|
+
|
|
32
|
+
const store = new OptionalFeatureMigrationStore({ filePath: stateFile });
|
|
33
|
+
await store.write({
|
|
34
|
+
schemaVersion: 1,
|
|
35
|
+
lastSuccessfulAudit: {
|
|
36
|
+
webuiVersion: "0.8.2",
|
|
37
|
+
completedAt: "2026-01-01T00:00:00.000Z",
|
|
38
|
+
features: { legacy: { available: true, enabled: true, sourceKind: "legacy-webui-bundled", installedVersion: "1.0.0" } },
|
|
39
|
+
},
|
|
40
|
+
pendingUpgrade: { fromVersion: "0.8.2", startedAt: "2026-01-02T00:00:00.000Z", featureIds: ["legacy"] },
|
|
41
|
+
secret: "must-not-survive",
|
|
42
|
+
});
|
|
43
|
+
const persisted = JSON.parse(await readFile(stateFile, "utf8"));
|
|
44
|
+
assert.equal(persisted.schemaVersion, 1);
|
|
45
|
+
assert.equal(Object.hasOwn(persisted, "secret"), false);
|
|
46
|
+
if (process.platform !== "win32") assert.equal((await stat(stateFile)).mode & 0o777, 0o600);
|
|
47
|
+
|
|
48
|
+
const events = [];
|
|
49
|
+
const coordinator = new OptionalFeatureAuditCoordinator({
|
|
50
|
+
catalog,
|
|
51
|
+
store,
|
|
52
|
+
webuiVersion: "0.8.3",
|
|
53
|
+
deadlineMs: 250,
|
|
54
|
+
onEvent: (event) => events.push(event),
|
|
55
|
+
collectStatuses: async () => [
|
|
56
|
+
{ ...catalog[0], configured: true, installed: true, installedVersion: "1.0.0", installedRoot: "/private/registered", topLevelResources: [] },
|
|
57
|
+
{ ...catalog[1], locallyConfigured: true, installed: true, installedVersion: "1.0.0", topLevelResources: ["/private/local/index.ts"] },
|
|
58
|
+
{ ...catalog[2], legacyEvidence: true, installed: true, installedVersion: "1.0.0", legacyPath: "/private/legacy" },
|
|
59
|
+
{ ...catalog[3], configured: true, locallyConfigured: true, resourceConflict: true, installed: true },
|
|
60
|
+
{ ...catalog[4], installed: false },
|
|
61
|
+
],
|
|
62
|
+
});
|
|
63
|
+
await assert.rejects(
|
|
64
|
+
coordinator.runMutation("pending", async () => {}),
|
|
65
|
+
(error) => error.statusCode === 409 && /not actionable/.test(error.message),
|
|
66
|
+
"checking snapshots must never authorize mutations",
|
|
67
|
+
);
|
|
68
|
+
|
|
69
|
+
const snapshot = await coordinator.recheck({ reason: "test" });
|
|
70
|
+
assert.equal(snapshot.phase, "action-required");
|
|
71
|
+
assert.equal(snapshot.installKind, "upgrade");
|
|
72
|
+
assert.match(snapshot.revision, /^sha256:[a-f0-9]{64}$/);
|
|
73
|
+
assert.deepEqual(snapshot.summary, { ready: 2, migratable: 1, missing: 1, conflicts: 1, disabled: 0, unknown: 0 });
|
|
74
|
+
assert.deepEqual(snapshot.features.map(({ state }) => state), ["registered", "local-resource", "legacy-migratable", "conflict", "missing"]);
|
|
75
|
+
assert.equal(snapshot.features[2].selectedByDefault, true);
|
|
76
|
+
assert.equal(JSON.stringify(snapshot).includes("/private/"), false, "browser snapshot must not expose host paths");
|
|
77
|
+
assert.equal(Object.isFrozen(snapshot), true);
|
|
78
|
+
assert.equal(Object.isFrozen(snapshot.features), true);
|
|
79
|
+
assert.throws(() => coordinator.assertRevision("sha256:stale"), (error) => error.statusCode === 409);
|
|
80
|
+
assert.ok(events.some(({ event }) => event === "audit-complete"));
|
|
81
|
+
|
|
82
|
+
await coordinator.dismiss(snapshot.revision);
|
|
83
|
+
assert.equal(coordinator.current().phase, "action-required", "conflicts remain actionable after migration dismissal");
|
|
84
|
+
assert.equal(coordinator.current().features.find(({ featureId }) => featureId === "legacy").selectedByDefault, false);
|
|
85
|
+
const dismissed = await store.read();
|
|
86
|
+
assert.deepEqual(dismissed.dismissedMigration.featureIds, ["legacy"]);
|
|
87
|
+
const afterDismissRecheck = await coordinator.recheck({ reason: "dismiss-persistence" });
|
|
88
|
+
assert.equal(afterDismissRecheck.phase, "action-required", "conflict remains actionable across rechecks");
|
|
89
|
+
assert.equal(afterDismissRecheck.features.find(({ featureId }) => featureId === "legacy").selectedByDefault, false, "dismissed migration stays unselected across rechecks");
|
|
90
|
+
|
|
91
|
+
let releaseMutation;
|
|
92
|
+
const blockedMutation = coordinator.runMutation(coordinator.current().revision, () => new Promise((resolve) => { releaseMutation = resolve; }));
|
|
93
|
+
await assert.rejects(
|
|
94
|
+
coordinator.runMutation(coordinator.current().revision, async () => {}),
|
|
95
|
+
(error) => error.statusCode === 409,
|
|
96
|
+
);
|
|
97
|
+
assert.throws(() => coordinator.assertIdle(), (error) => error.statusCode === 409, "recheck routes must reject while mutation is active");
|
|
98
|
+
await assert.rejects(
|
|
99
|
+
coordinator.dismiss(coordinator.current().revision),
|
|
100
|
+
(error) => error.statusCode === 409,
|
|
101
|
+
"dismiss must reject while mutation is active",
|
|
102
|
+
);
|
|
103
|
+
releaseMutation("done");
|
|
104
|
+
assert.equal(await blockedMutation, "done");
|
|
105
|
+
|
|
106
|
+
const timeoutStore = new OptionalFeatureMigrationStore({ filePath: path.join(root, "timeout", "state.json") });
|
|
107
|
+
const timeoutCoordinator = new OptionalFeatureAuditCoordinator({
|
|
108
|
+
catalog: [catalog[0]],
|
|
109
|
+
store: timeoutStore,
|
|
110
|
+
webuiVersion: "0.8.3",
|
|
111
|
+
deadlineMs: 20,
|
|
112
|
+
collectStatuses: async () => {
|
|
113
|
+
await delay(100);
|
|
114
|
+
return [{ ...catalog[0], configured: true, installed: true }];
|
|
115
|
+
},
|
|
116
|
+
});
|
|
117
|
+
const timeoutSnapshot = await timeoutCoordinator.recheck();
|
|
118
|
+
assert.equal(timeoutSnapshot.phase, "degraded");
|
|
119
|
+
assert.equal(timeoutSnapshot.features[0].state, "unknown");
|
|
120
|
+
assert.equal(timeoutSnapshot.diagnostic.kind, "audit-timeout");
|
|
121
|
+
assert.deepEqual([...timeoutCoordinator.excludedPackageNames()], ["@test/registered"]);
|
|
122
|
+
await assert.rejects(
|
|
123
|
+
timeoutCoordinator.runMutation(timeoutSnapshot.revision, async () => {}),
|
|
124
|
+
(error) => error.statusCode === 409 && /not actionable/.test(error.message),
|
|
125
|
+
"degraded snapshots must never authorize mutations",
|
|
126
|
+
);
|
|
127
|
+
|
|
128
|
+
const malformedFile = path.join(root, "malformed", "state.json");
|
|
129
|
+
await mkdir(path.dirname(malformedFile), { recursive: true });
|
|
130
|
+
await import("node:fs/promises").then(({ writeFile }) => writeFile(malformedFile, "{not-json", "utf8"));
|
|
131
|
+
const malformedCoordinator = new OptionalFeatureAuditCoordinator({
|
|
132
|
+
catalog: [catalog[0]],
|
|
133
|
+
store: new OptionalFeatureMigrationStore({ filePath: malformedFile }),
|
|
134
|
+
webuiVersion: "0.8.3",
|
|
135
|
+
collectStatuses: async () => [{ ...catalog[0], configured: true, installed: true }],
|
|
136
|
+
});
|
|
137
|
+
assert.equal((await malformedCoordinator.recheck()).phase, "degraded");
|
|
138
|
+
|
|
139
|
+
console.log("optional feature migration tests passed");
|
|
140
|
+
} finally {
|
|
141
|
+
await rm(root, { recursive: true, force: true });
|
|
142
|
+
}
|
|
@@ -0,0 +1,491 @@
|
|
|
1
|
+
import assert from "node:assert/strict";
|
|
2
|
+
import { mkdtemp, rm } from "node:fs/promises";
|
|
3
|
+
import { tmpdir } from "node:os";
|
|
4
|
+
import { join } from "node:path";
|
|
5
|
+
import { writeSessionSummaryPreferences } from "../lib/session-summary-preferences.mjs";
|
|
6
|
+
import {
|
|
7
|
+
SESSION_SUMMARY_DISPLAY_TYPE,
|
|
8
|
+
SESSION_SUMMARY_INJECTION_TYPE,
|
|
9
|
+
SESSION_SUMMARY_INPUT_MAX_CHARS,
|
|
10
|
+
SESSION_SUMMARY_MAX_OUTPUT_TOKENS,
|
|
11
|
+
SESSION_SUMMARY_NAME_PROVENANCE_TYPE,
|
|
12
|
+
SESSION_SUMMARY_OUTPUT_MAX_CHARS,
|
|
13
|
+
SESSION_SUMMARY_RAW_OUTPUT_MAX_CHARS,
|
|
14
|
+
SESSION_SUMMARY_RPC_TYPE,
|
|
15
|
+
SESSION_SUMMARY_STATE_TYPE,
|
|
16
|
+
boundedRpcPayload,
|
|
17
|
+
captureSummarySource,
|
|
18
|
+
createSummaryScheduler,
|
|
19
|
+
filterAndInjectSummaryContext,
|
|
20
|
+
isSummarySourceCurrent,
|
|
21
|
+
latestSummaryNameProvenance,
|
|
22
|
+
latestSummaryState,
|
|
23
|
+
normalizeSummaryTitle,
|
|
24
|
+
parseSummaryOutput,
|
|
25
|
+
serializeSummarySource,
|
|
26
|
+
shouldApplySummaryTitle,
|
|
27
|
+
} from "../lib/session-summary-core.mjs";
|
|
28
|
+
|
|
29
|
+
const entries = [
|
|
30
|
+
{ type: "message", id: "u1", message: { role: "user", content: [{ type: "text", text: "Please fix auth" }, { type: "image", data: "SECRET_IMAGE" }] } },
|
|
31
|
+
{ type: "message", id: "a1", message: { role: "assistant", content: [
|
|
32
|
+
{ type: "thinking", thinking: "SECRET_THINKING" },
|
|
33
|
+
{ type: "text", text: "I inspected the flow." },
|
|
34
|
+
{ type: "toolCall", name: "read", arguments: { path: "/secret/path", token: "SECRET_ARG" } },
|
|
35
|
+
] } },
|
|
36
|
+
{ type: "message", id: "tool", message: { role: "toolResult", content: [{ type: "text", text: "SECRET_RESULT" }] } },
|
|
37
|
+
{ type: "custom_message", customType: SESSION_SUMMARY_DISPLAY_TYPE, content: "RECURSIVE_SUMMARY", display: true },
|
|
38
|
+
{ type: "custom", customType: SESSION_SUMMARY_STATE_TYPE, data: { raw: "RECURSIVE_STATE" } },
|
|
39
|
+
{ type: "message", id: "u2", message: { role: "user", content: "Ship it" } },
|
|
40
|
+
];
|
|
41
|
+
const serialized = serializeSummarySource(entries);
|
|
42
|
+
assert.match(serialized.text, /User:\nPlease fix auth/);
|
|
43
|
+
assert.match(serialized.text, /Assistant:\nI inspected the flow\./);
|
|
44
|
+
assert.match(serialized.text, /Tool used: read/);
|
|
45
|
+
assert.match(serialized.text, /User:\nShip it/);
|
|
46
|
+
for (const secret of ["SECRET_IMAGE", "SECRET_THINKING", "SECRET_ARG", "SECRET_RESULT", "RECURSIVE_SUMMARY", "RECURSIVE_STATE", "/secret/path"]) {
|
|
47
|
+
assert.equal(serialized.text.includes(secret), false, `serializer excludes ${secret}`);
|
|
48
|
+
}
|
|
49
|
+
assert.equal(serialized.userTurns, 2);
|
|
50
|
+
assert.equal(serialized.entryCount, entries.length);
|
|
51
|
+
assert.equal(serialized.fingerprint.length, 64);
|
|
52
|
+
assert.equal(serializeSummarySource(entries).fingerprint, serialized.fingerprint, "fingerprint is deterministic");
|
|
53
|
+
|
|
54
|
+
const bounded = serializeSummarySource([
|
|
55
|
+
{ type: "message", message: { role: "user", content: "a".repeat(SESSION_SUMMARY_INPUT_MAX_CHARS + 100) } },
|
|
56
|
+
], { maxChars: 128 });
|
|
57
|
+
assert.equal(bounded.text.length, 128);
|
|
58
|
+
assert.match(bounded.text, /^\[Earlier conversation omitted/);
|
|
59
|
+
assert.equal(bounded.omitted, true);
|
|
60
|
+
|
|
61
|
+
assert.deepEqual(parseSummaryOutput(JSON.stringify({ version: 1, title: " Auth\nflow ", summaryMarkdown: "# Done\n\nSafe" })), {
|
|
62
|
+
version: 1,
|
|
63
|
+
title: "Auth flow",
|
|
64
|
+
summaryMarkdown: "# Done\n\nSafe",
|
|
65
|
+
});
|
|
66
|
+
assert.equal(normalizeSummaryTitle("a".repeat(100)).length, 44);
|
|
67
|
+
assert.equal(parseSummaryOutput(JSON.stringify({ version: 1, title: "\u0000\n", summaryMarkdown: "ok" })).title, undefined, "invalid title does not corrupt a valid summary");
|
|
68
|
+
await assert.rejects(async () => parseSummaryOutput("```json\n{}\n```"), /invalid JSON/);
|
|
69
|
+
await assert.rejects(async () => parseSummaryOutput('{"version":2,"summaryMarkdown":"ok"}'), /unsupported schema/);
|
|
70
|
+
await assert.rejects(async () => parseSummaryOutput('{"version":1,"summaryMarkdown":""}'), /empty/);
|
|
71
|
+
await assert.rejects(async () => parseSummaryOutput(JSON.stringify({ version: 1, title: 42, summaryMarkdown: "ok" })), /title has an invalid type/);
|
|
72
|
+
await assert.rejects(async () => parseSummaryOutput(JSON.stringify({ version: 1, summaryMarkdown: "ok", extra: true })), /unknown schema fields/);
|
|
73
|
+
await assert.rejects(async () => parseSummaryOutput(JSON.stringify({
|
|
74
|
+
version: 1,
|
|
75
|
+
summaryMarkdown: "ok",
|
|
76
|
+
unknown: "x".repeat(SESSION_SUMMARY_RAW_OUTPUT_MAX_CHARS),
|
|
77
|
+
})), /total response bound/);
|
|
78
|
+
await assert.rejects(async () => parseSummaryOutput(JSON.stringify({ version: 1, summaryMarkdown: "x".repeat(SESSION_SUMMARY_OUTPUT_MAX_CHARS + 1) })), /exceeds/);
|
|
79
|
+
|
|
80
|
+
const baseState = {
|
|
81
|
+
version: 1,
|
|
82
|
+
source: { sessionId: "s1", leafId: "u2", fingerprint: serialized.fingerprint, entryCount: entries.length },
|
|
83
|
+
result: { title: "Auth flow", summaryMarkdown: "# Current" },
|
|
84
|
+
generation: { provider: "fake", modelId: "fake", thinkingLevel: "low", promptRevision: "v1" },
|
|
85
|
+
generatedAt: "2026-08-04T00:00:00.000Z",
|
|
86
|
+
settledTurnOrdinal: 2,
|
|
87
|
+
titleAppliedAtOrdinal: 2,
|
|
88
|
+
};
|
|
89
|
+
assert.deepEqual(latestSummaryState([
|
|
90
|
+
{ type: "custom", customType: SESSION_SUMMARY_STATE_TYPE, data: { ...baseState, result: { ...baseState.result, summaryMarkdown: "# Older" } } },
|
|
91
|
+
{ type: "custom", customType: "other", data: baseState },
|
|
92
|
+
{ type: "custom", customType: SESSION_SUMMARY_STATE_TYPE, data: baseState },
|
|
93
|
+
]), baseState);
|
|
94
|
+
const escapedPersistedSummary = "\\".repeat(12_000);
|
|
95
|
+
assert.equal(latestSummaryState([{
|
|
96
|
+
type: "custom",
|
|
97
|
+
customType: SESSION_SUMMARY_STATE_TYPE,
|
|
98
|
+
data: { ...baseState, result: { ...baseState.result, summaryMarkdown: escapedPersistedSummary } },
|
|
99
|
+
}]).result.summaryMarkdown, escapedPersistedSummary, "persisted state validation uses the decoded Markdown bound");
|
|
100
|
+
assert.equal(latestSummaryState([{ type: "custom", customType: SESSION_SUMMARY_STATE_TYPE, data: { version: 99 } }]), undefined);
|
|
101
|
+
assert.deepEqual(latestSummaryNameProvenance([
|
|
102
|
+
{ type: "custom", customType: SESSION_SUMMARY_NAME_PROVENANCE_TYPE, data: { version: 1, explicit: true } },
|
|
103
|
+
{ type: "custom", customType: SESSION_SUMMARY_NAME_PROVENANCE_TYPE, data: { version: 99, explicit: false } },
|
|
104
|
+
{ type: "custom", customType: SESSION_SUMMARY_NAME_PROVENANCE_TYPE, data: { version: 1, explicit: false } },
|
|
105
|
+
]), { version: 1, explicit: false });
|
|
106
|
+
|
|
107
|
+
const originalMessages = [
|
|
108
|
+
{ role: "user", content: "direct", timestamp: 1 },
|
|
109
|
+
{ role: "custom", customType: SESSION_SUMMARY_DISPLAY_TYPE, content: "old display", display: true, timestamp: 2 },
|
|
110
|
+
{ role: "custom", customType: SESSION_SUMMARY_RPC_TYPE, content: "old rpc", display: false, timestamp: 3 },
|
|
111
|
+
{ role: "custom", customType: SESSION_SUMMARY_INJECTION_TYPE, content: "old injection", display: false, timestamp: 4 },
|
|
112
|
+
];
|
|
113
|
+
assert.deepEqual(filterAndInjectSummaryContext(originalMessages), [originalMessages[0]]);
|
|
114
|
+
const injected = filterAndInjectSummaryContext(originalMessages, { injectLatest: true, state: baseState });
|
|
115
|
+
assert.equal(injected.length, 2);
|
|
116
|
+
assert.equal(injected[1].customType, SESSION_SUMMARY_INJECTION_TYPE);
|
|
117
|
+
assert.match(injected[1].content, /Reference-only generated session summary/);
|
|
118
|
+
assert.match(injected[1].content, /# Current/);
|
|
119
|
+
assert.equal(injected.filter((message) => message.customType === SESSION_SUMMARY_INJECTION_TYPE).length, 1);
|
|
120
|
+
|
|
121
|
+
assert.equal(shouldApplySummaryTitle({ candidate: "First", settledTurnOrdinal: 1 }), true, "first generated title applies immediately");
|
|
122
|
+
assert.equal(shouldApplySummaryTitle({ candidate: "Changed", currentSessionName: "Manual name", settledTurnOrdinal: 10 }), false, "explicit name wins");
|
|
123
|
+
assert.equal(shouldApplySummaryTitle({ candidate: "Changed", currentSessionName: "Auth flow", previousState: baseState, settledTurnOrdinal: 4, minSettledTurns: 3 }), false);
|
|
124
|
+
assert.equal(shouldApplySummaryTitle({ candidate: "Changed", currentSessionName: "Auth flow", previousState: baseState, settledTurnOrdinal: 5, minSettledTurns: 3 }), true);
|
|
125
|
+
assert.equal(shouldApplySummaryTitle({ candidate: "Auth flow", currentSessionName: "Auth flow", previousState: baseState, settledTurnOrdinal: 9 }), false, "unchanged candidate never reapplies");
|
|
126
|
+
assert.equal(shouldApplySummaryTitle({ candidate: "Changed", currentSessionName: "Explicit", previousState: baseState, settledTurnOrdinal: 9 }), false, "manual rename after generated title wins");
|
|
127
|
+
assert.equal(shouldApplySummaryTitle({ candidate: "Changed", currentSessionName: "Auth flow", previousState: baseState, explicitName: true, settledTurnOrdinal: 9 }), false, "same-text explicit rename wins");
|
|
128
|
+
assert.equal(shouldApplySummaryTitle({ candidate: "Changed", currentSessionName: undefined, previousState: baseState, explicitName: false, settledTurnOrdinal: 9 }), true, "clearing an explicit name re-enables generated titles");
|
|
129
|
+
|
|
130
|
+
const branch = [...entries];
|
|
131
|
+
const session = {
|
|
132
|
+
getBranch: () => branch,
|
|
133
|
+
getSessionId: () => "s1",
|
|
134
|
+
getSessionFile: () => "/tmp/s1.jsonl",
|
|
135
|
+
getLeafId: () => "u2",
|
|
136
|
+
};
|
|
137
|
+
const captured = captureSummarySource(session);
|
|
138
|
+
assert.equal(isSummarySourceCurrent(session, captured), true);
|
|
139
|
+
branch.push({ type: "message", id: "u3", message: { role: "user", content: "new work" } });
|
|
140
|
+
assert.equal(isSummarySourceCurrent({ ...session, getLeafId: () => "u3" }, captured), false, "new leaf makes result stale");
|
|
141
|
+
|
|
142
|
+
assert.deepEqual(boundedRpcPayload("setup", { configured: true, enabled: false, credentials: "secret" }), {
|
|
143
|
+
version: 1, kind: "setup", configured: true, enabled: false,
|
|
144
|
+
});
|
|
145
|
+
assert.equal(boundedRpcPayload("success", { title: "t".repeat(100), summaryMarkdown: "s".repeat(20_000) }).title.length, 44);
|
|
146
|
+
assert.equal(boundedRpcPayload("success", { summaryMarkdown: "s".repeat(20_000) }).summaryMarkdown.length, SESSION_SUMMARY_OUTPUT_MAX_CHARS);
|
|
147
|
+
assert.equal(boundedRpcPayload("failure", { message: "x".repeat(1000) }).message.length, 512);
|
|
148
|
+
assert.throws(() => boundedRpcPayload("unknown"), /Unsupported/);
|
|
149
|
+
|
|
150
|
+
let releaseFirst;
|
|
151
|
+
const firstBlocked = new Promise((resolve) => { releaseFirst = resolve; });
|
|
152
|
+
const calls = [];
|
|
153
|
+
const statuses = [];
|
|
154
|
+
const scheduler = createSummaryScheduler({
|
|
155
|
+
run: async (input) => {
|
|
156
|
+
calls.push(input);
|
|
157
|
+
if (input === "first") await firstBlocked;
|
|
158
|
+
return input;
|
|
159
|
+
},
|
|
160
|
+
onState: (status) => statuses.push(status),
|
|
161
|
+
});
|
|
162
|
+
const firstPromise = scheduler.schedule("first");
|
|
163
|
+
assert.equal(calls.length, 0, "schedule defers generation so lifecycle handlers can return immediately");
|
|
164
|
+
await Promise.resolve();
|
|
165
|
+
assert.deepEqual(calls, ["first"]);
|
|
166
|
+
assert.equal(scheduler.getState().inFlight, true);
|
|
167
|
+
const joined = scheduler.schedule("second");
|
|
168
|
+
scheduler.schedule("newest");
|
|
169
|
+
assert.equal(joined, firstPromise, "one in-flight promise is reused");
|
|
170
|
+
releaseFirst();
|
|
171
|
+
assert.equal((await firstPromise).status, "success");
|
|
172
|
+
await new Promise((resolve) => setTimeout(resolve, 0));
|
|
173
|
+
assert.deepEqual(calls, ["first", "newest"], "automatic work coalesces to the newest pending input");
|
|
174
|
+
assert.equal(statuses.filter((status) => status === "generating").length, 2);
|
|
175
|
+
|
|
176
|
+
let now = 100;
|
|
177
|
+
let attempts = 0;
|
|
178
|
+
const cooldownScheduler = createSummaryScheduler({
|
|
179
|
+
now: () => now,
|
|
180
|
+
cooldownMs: 300,
|
|
181
|
+
run: async () => { attempts += 1; throw new Error("provider failed"); },
|
|
182
|
+
});
|
|
183
|
+
assert.equal((await cooldownScheduler.schedule("a")).status, "failure");
|
|
184
|
+
assert.equal((await cooldownScheduler.schedule("b")).status, "cooldown");
|
|
185
|
+
assert.equal(attempts, 1);
|
|
186
|
+
assert.equal((await cooldownScheduler.schedule("manual", { manual: true })).status, "failure", "manual refresh bypasses cooldown");
|
|
187
|
+
assert.equal(attempts, 2);
|
|
188
|
+
now = 401;
|
|
189
|
+
assert.equal((await cooldownScheduler.schedule("c")).status, "failure");
|
|
190
|
+
assert.equal(attempts, 3);
|
|
191
|
+
|
|
192
|
+
let rejectBlockedFailure;
|
|
193
|
+
let interactionAttempts = 0;
|
|
194
|
+
const blockedFailure = new Promise((_resolve, reject) => { rejectBlockedFailure = reject; });
|
|
195
|
+
const interactionScheduler = createSummaryScheduler({
|
|
196
|
+
now: () => 1_000,
|
|
197
|
+
cooldownMs: 300,
|
|
198
|
+
run: async (input) => {
|
|
199
|
+
interactionAttempts += 1;
|
|
200
|
+
if (input === "first") return blockedFailure;
|
|
201
|
+
throw new Error(`failed ${input}`);
|
|
202
|
+
},
|
|
203
|
+
});
|
|
204
|
+
const interactionFirst = interactionScheduler.schedule("first");
|
|
205
|
+
await Promise.resolve();
|
|
206
|
+
interactionScheduler.schedule("pending");
|
|
207
|
+
rejectBlockedFailure(new Error("automatic failed"));
|
|
208
|
+
assert.equal((await interactionFirst).status, "failure");
|
|
209
|
+
await new Promise((resolve) => setImmediate(resolve));
|
|
210
|
+
assert.equal(interactionScheduler.getState().inFlight, false, "cooldown-skipped pending work does not wedge inFlight");
|
|
211
|
+
assert.equal(interactionScheduler.getState().pending, false);
|
|
212
|
+
assert.equal(interactionAttempts, 1);
|
|
213
|
+
assert.equal((await interactionScheduler.schedule("manual", { manual: true })).status, "failure", "manual refresh still bypasses cooldown after a coalesced failure");
|
|
214
|
+
assert.equal(interactionAttempts, 2);
|
|
215
|
+
|
|
216
|
+
let observedAbort = false;
|
|
217
|
+
const abortScheduler = createSummaryScheduler({ run: (_input, signal) => new Promise((_resolve, reject) => {
|
|
218
|
+
signal.addEventListener("abort", () => { observedAbort = true; reject(Object.assign(new Error("aborted"), { name: "AbortError" })); });
|
|
219
|
+
}) });
|
|
220
|
+
const aborted = abortScheduler.schedule("work");
|
|
221
|
+
await Promise.resolve();
|
|
222
|
+
abortScheduler.abort();
|
|
223
|
+
assert.equal((await aborted).status, "aborted");
|
|
224
|
+
assert.equal(observedAbort, true);
|
|
225
|
+
assert.equal(abortScheduler.getState().disposed, true);
|
|
226
|
+
|
|
227
|
+
// Load the public TypeScript extension with an injected fake completion. No provider is contacted.
|
|
228
|
+
const extensionTemp = await mkdtemp(join(tmpdir(), "session-summary-extension-"));
|
|
229
|
+
const previousConfigFile = process.env.PI_SESSION_SUMMARY_CONFIG_FILE;
|
|
230
|
+
try {
|
|
231
|
+
const configFile = join(extensionTemp, "summary.json");
|
|
232
|
+
process.env.PI_SESSION_SUMMARY_CONFIG_FILE = configFile;
|
|
233
|
+
await writeSessionSummaryPreferences({
|
|
234
|
+
configured: true,
|
|
235
|
+
enabled: true,
|
|
236
|
+
model: { provider: "openai-codex", modelId: "gpt-5.6-luna", thinkingLevel: "low" },
|
|
237
|
+
}, configFile);
|
|
238
|
+
const { createSessionSummaryExtension } = await import("../session-summary.ts");
|
|
239
|
+
const branchEntries = [
|
|
240
|
+
{ type: "message", id: "u1", parentId: null, message: { role: "user", content: "Implement summaries" } },
|
|
241
|
+
{ type: "message", id: "a1", parentId: "u1", message: { role: "assistant", content: [{ type: "text", text: "Core is ready" }] } },
|
|
242
|
+
];
|
|
243
|
+
let activeBranch = branchEntries;
|
|
244
|
+
let leafId = "a1";
|
|
245
|
+
let sessionName;
|
|
246
|
+
let releaseComplete;
|
|
247
|
+
let completeGate = new Promise((resolve) => { releaseComplete = resolve; });
|
|
248
|
+
let nextCompletionError;
|
|
249
|
+
let fakeOutput = { version: 1, title: "Summary core", summaryMarkdown: "# Summary\n\nCore is ready." };
|
|
250
|
+
const completionCalls = [];
|
|
251
|
+
const handlers = new Map();
|
|
252
|
+
const commands = new Map();
|
|
253
|
+
const renderers = new Map();
|
|
254
|
+
const api = {
|
|
255
|
+
on(name, handler) { handlers.set(name, handler); },
|
|
256
|
+
registerCommand(name, options) { commands.set(name, options); },
|
|
257
|
+
registerEntryRenderer(name, renderer) { renderers.set(name, renderer); },
|
|
258
|
+
sendMessage(message) {
|
|
259
|
+
const id = `e${activeBranch.length + 1}`;
|
|
260
|
+
activeBranch.push({ type: "custom_message", id, parentId: leafId, ...message });
|
|
261
|
+
leafId = id;
|
|
262
|
+
},
|
|
263
|
+
appendEntry(customType, data) {
|
|
264
|
+
const id = `e${activeBranch.length + 1}`;
|
|
265
|
+
activeBranch.push({ type: "custom", id, parentId: leafId, customType, data });
|
|
266
|
+
leafId = id;
|
|
267
|
+
},
|
|
268
|
+
setSessionName(name) {
|
|
269
|
+
sessionName = name.trim() || undefined;
|
|
270
|
+
const id = `e${activeBranch.length + 1}`;
|
|
271
|
+
activeBranch.push({ type: "session_info", id, parentId: leafId, name: sessionName });
|
|
272
|
+
leafId = id;
|
|
273
|
+
handlers.get("session_info_changed")?.({ type: "session_info_changed", name: sessionName }, ctx);
|
|
274
|
+
},
|
|
275
|
+
getSessionName() { return sessionName; },
|
|
276
|
+
};
|
|
277
|
+
let fakeModel = { provider: "openai-codex", id: "gpt-5.6-luna", api: "openai-codex-responses", reasoning: true };
|
|
278
|
+
let fakeAuth = { ok: true, apiKey: "fake-key", headers: { "x-fake": "yes" }, env: {} };
|
|
279
|
+
const ctx = {
|
|
280
|
+
mode: "rpc",
|
|
281
|
+
hasUI: true,
|
|
282
|
+
ui: { notify() {} },
|
|
283
|
+
sessionManager: {
|
|
284
|
+
getBranch: () => activeBranch.slice(),
|
|
285
|
+
getSessionId: () => "fake-session",
|
|
286
|
+
getSessionFile: () => "/tmp/fake-session.jsonl",
|
|
287
|
+
getLeafId: () => leafId,
|
|
288
|
+
},
|
|
289
|
+
modelRegistry: {
|
|
290
|
+
find: (provider, modelId) => provider === fakeModel.provider && modelId === fakeModel.id ? fakeModel : undefined,
|
|
291
|
+
getApiKeyAndHeaders: async () => fakeAuth,
|
|
292
|
+
},
|
|
293
|
+
};
|
|
294
|
+
const fakeComplete = async (...args) => {
|
|
295
|
+
completionCalls.push(args);
|
|
296
|
+
const gate = completeGate;
|
|
297
|
+
const error = nextCompletionError;
|
|
298
|
+
nextCompletionError = undefined;
|
|
299
|
+
await gate;
|
|
300
|
+
if (error) throw error;
|
|
301
|
+
return {
|
|
302
|
+
stopReason: "stop",
|
|
303
|
+
content: [{ type: "text", text: JSON.stringify(fakeOutput) }],
|
|
304
|
+
};
|
|
305
|
+
};
|
|
306
|
+
createSessionSummaryExtension({ completeFn: fakeComplete })(api);
|
|
307
|
+
|
|
308
|
+
assert.deepEqual([...commands.keys()].sort(), ["summary", "summary-setup"]);
|
|
309
|
+
assert.equal(renderers.has(SESSION_SUMMARY_DISPLAY_TYPE), true, "non-contextual TUI Markdown entry renderer is registered");
|
|
310
|
+
assert.equal(handlers.has("agent_settled"), true);
|
|
311
|
+
assert.equal(handlers.has("agent_end"), false, "generation is never registered on agent_end");
|
|
312
|
+
const settledReturn = handlers.get("agent_settled")({ type: "agent_settled" }, ctx);
|
|
313
|
+
assert.equal(settledReturn, undefined, "settled handler returns synchronously");
|
|
314
|
+
assert.equal(completionCalls.length, 0, "provider work does not delay outward settlement");
|
|
315
|
+
for (let i = 0; i < 20 && completionCalls.length === 0; i += 1) await new Promise((resolve) => setImmediate(resolve));
|
|
316
|
+
assert.equal(completionCalls.length, 1);
|
|
317
|
+
const [, completionContext, completionOptions] = completionCalls[0];
|
|
318
|
+
assert.equal(completionContext.tools, undefined);
|
|
319
|
+
assert.match(completionContext.systemPrompt, /untrusted data/);
|
|
320
|
+
assert.equal(completionOptions.cacheRetention, "none");
|
|
321
|
+
assert.equal(completionOptions.reasoning, "low");
|
|
322
|
+
assert.equal(completionOptions.reasoningEffort, undefined, "provider-specific raw reasoning options are not used");
|
|
323
|
+
assert.equal(completionOptions.onPayload, undefined, "provider payloads are not unconditionally mutated");
|
|
324
|
+
assert.equal(completionOptions.maxRetries, 0);
|
|
325
|
+
assert.equal(completionOptions.maxTokens, SESSION_SUMMARY_MAX_OUTPUT_TOKENS);
|
|
326
|
+
assert.equal(completionOptions.timeoutMs, 90_000);
|
|
327
|
+
assert.equal(typeof completionOptions.sessionId, "string");
|
|
328
|
+
assert.notEqual(completionOptions.sessionId, "fake-session", "completion uses a fresh routing ID");
|
|
329
|
+
releaseComplete();
|
|
330
|
+
for (let i = 0; i < 20 && !branchEntries.some((entry) => entry.customType === SESSION_SUMMARY_STATE_TYPE); i += 1) await new Promise((resolve) => setImmediate(resolve));
|
|
331
|
+
const persistedState = latestSummaryState(branchEntries);
|
|
332
|
+
assert.equal(persistedState.result.summaryMarkdown, "# Summary\n\nCore is ready.");
|
|
333
|
+
assert.equal(sessionName, "Summary core", "first generated title applies immediately");
|
|
334
|
+
assert.equal(branchEntries.filter((entry) => entry.customType === SESSION_SUMMARY_STATE_TYPE).length, 1);
|
|
335
|
+
assert.equal(branchEntries.filter((entry) => entry.customType === SESSION_SUMMARY_RPC_TYPE).every((entry) => entry.content === ""), true, "RPC control messages carry no context text");
|
|
336
|
+
|
|
337
|
+
const contextResult = await handlers.get("context")({ type: "context", messages: [
|
|
338
|
+
{ role: "user", content: "latest", timestamp: 1 },
|
|
339
|
+
{ role: "custom", customType: SESSION_SUMMARY_RPC_TYPE, content: "", display: false, timestamp: 2 },
|
|
340
|
+
] }, ctx);
|
|
341
|
+
assert.equal(contextResult.messages.some((message) => message.customType === SESSION_SUMMARY_RPC_TYPE), false);
|
|
342
|
+
assert.equal(contextResult.messages.some((message) => message.customType === SESSION_SUMMARY_INJECTION_TYPE), false, "context injection remains off by default");
|
|
343
|
+
|
|
344
|
+
completeGate = new Promise((resolve) => { releaseComplete = resolve; });
|
|
345
|
+
nextCompletionError = new Error("overlap failed");
|
|
346
|
+
const overlapCallIndex = completionCalls.length;
|
|
347
|
+
handlers.get("agent_settled")({ type: "agent_settled" }, ctx);
|
|
348
|
+
for (let i = 0; i < 20 && completionCalls.length === overlapCallIndex; i += 1) await new Promise((resolve) => setImmediate(resolve));
|
|
349
|
+
assert.equal(completionCalls.length, overlapCallIndex + 1);
|
|
350
|
+
const overlapRefresh = commands.get("summary").handler("refresh", ctx);
|
|
351
|
+
releaseComplete();
|
|
352
|
+
await overlapRefresh;
|
|
353
|
+
const overlapFailures = branchEntries.filter((entry) => entry.details?.kind === "failure" && entry.details?.message === "overlap failed");
|
|
354
|
+
assert.equal(overlapFailures.length, 1, "manual refresh joining an automatic failure emits one terminal RPC event");
|
|
355
|
+
handlers.get("session_shutdown")({ type: "session_shutdown" }, ctx);
|
|
356
|
+
createSessionSummaryExtension({ completeFn: fakeComplete })(api);
|
|
357
|
+
|
|
358
|
+
completeGate = new Promise((resolve) => { releaseComplete = resolve; });
|
|
359
|
+
nextCompletionError = undefined;
|
|
360
|
+
fakeOutput = { version: 1, summaryMarkdown: "# First automatic refresh" };
|
|
361
|
+
const coalescedFailureCountBefore = branchEntries.filter((entry) => entry.details?.kind === "failure" && entry.details?.message === "pending automatic failed").length;
|
|
362
|
+
const coalescedCallIndex = completionCalls.length;
|
|
363
|
+
handlers.get("agent_settled")({ type: "agent_settled" }, ctx);
|
|
364
|
+
for (let i = 0; i < 20 && completionCalls.length === coalescedCallIndex; i += 1) await new Promise((resolve) => setImmediate(resolve));
|
|
365
|
+
assert.equal(completionCalls.length, coalescedCallIndex + 1);
|
|
366
|
+
handlers.get("agent_settled")({ type: "agent_settled" }, ctx);
|
|
367
|
+
nextCompletionError = new Error("pending automatic failed");
|
|
368
|
+
completeGate = Promise.resolve();
|
|
369
|
+
releaseComplete();
|
|
370
|
+
for (let i = 0; i < 40 && !branchEntries.some((entry) => entry.details?.kind === "failure" && entry.details?.message === "pending automatic failed"); i += 1) {
|
|
371
|
+
await new Promise((resolve) => setImmediate(resolve));
|
|
372
|
+
}
|
|
373
|
+
assert.equal(completionCalls.length, coalescedCallIndex + 2, "pending automatic refresh launches after the first succeeds");
|
|
374
|
+
const coalescedFailures = branchEntries.filter((entry) => entry.details?.kind === "failure" && entry.details?.message === "pending automatic failed");
|
|
375
|
+
assert.equal(coalescedFailures.length - coalescedFailureCountBefore, 1, "an internally launched pending failure emits exactly one terminal RPC event");
|
|
376
|
+
|
|
377
|
+
for (let i = 0; i < 20 && !branchEntries.some((entry) => entry.details?.kind === "success"); i += 1) await new Promise((resolve) => setImmediate(resolve));
|
|
378
|
+
assert.equal(latestSummaryNameProvenance(branchEntries), undefined, "self-generated rename does not record explicit provenance");
|
|
379
|
+
|
|
380
|
+
api.setSessionName("Summary core");
|
|
381
|
+
assert.equal(latestSummaryNameProvenance(branchEntries)?.explicit, true, "same-text explicit rename is recorded");
|
|
382
|
+
for (let index = 0; index < 3; index += 1) {
|
|
383
|
+
const id = `manual-u${index}`;
|
|
384
|
+
activeBranch.push({ type: "message", id, parentId: leafId, message: { role: "user", content: `Follow-up ${index}` } });
|
|
385
|
+
leafId = id;
|
|
386
|
+
}
|
|
387
|
+
fakeOutput = { version: 1, title: "Must not replace explicit", summaryMarkdown: "# Explicit protected" };
|
|
388
|
+
await commands.get("summary").handler("refresh", ctx);
|
|
389
|
+
assert.equal(sessionName, "Summary core", "same-text explicit rename is not overwritten after cadence");
|
|
390
|
+
assert.equal(latestSummaryState(branchEntries).result.title, "Summary core");
|
|
391
|
+
assert.equal(branchEntries.some((entry) => entry.type === "custom_message" && entry.customType === SESSION_SUMMARY_DISPLAY_TYPE), false, "TUI display does not append contextual custom messages");
|
|
392
|
+
const displayEntry = branchEntries.findLast((entry) => entry.type === "custom" && entry.customType === SESSION_SUMMARY_DISPLAY_TYPE);
|
|
393
|
+
assert.equal(displayEntry.data.summaryMarkdown, "# Explicit protected", "manual display appends a non-contextual rendered entry");
|
|
394
|
+
|
|
395
|
+
api.setSessionName("");
|
|
396
|
+
assert.equal(latestSummaryNameProvenance(branchEntries)?.explicit, false, "clearing an explicit name records branch-local cleared provenance");
|
|
397
|
+
fakeOutput = { version: 1, title: "Generated after clear", summaryMarkdown: "# Name cleared" };
|
|
398
|
+
await commands.get("summary").handler("refresh", ctx);
|
|
399
|
+
assert.equal(sessionName, "Generated after clear", "clearing an explicit name re-enables generated titles");
|
|
400
|
+
assert.equal(latestSummaryNameProvenance(branchEntries)?.explicit, false, "self rename preserves the preceding cleared provenance");
|
|
401
|
+
|
|
402
|
+
const branchA = activeBranch;
|
|
403
|
+
const branchB = [
|
|
404
|
+
{ type: "message", id: "b-u1", parentId: null, message: { role: "user", content: "Alternate branch" } },
|
|
405
|
+
{ type: "message", id: "b-a1", parentId: "b-u1", message: { role: "assistant", content: "No summary here yet" } },
|
|
406
|
+
];
|
|
407
|
+
activeBranch = branchB;
|
|
408
|
+
leafId = "b-a1";
|
|
409
|
+
sessionName = undefined;
|
|
410
|
+
await handlers.get("session_tree")({ type: "session_tree", oldLeafId: branchA.at(-1).id, newLeafId: leafId }, ctx);
|
|
411
|
+
const branchBProjection = branchB.findLast((entry) => entry.details?.kind === "state")?.details;
|
|
412
|
+
assert.equal(branchBProjection?.summaryMarkdown, undefined, "tree navigation publishes the active branch's empty projection");
|
|
413
|
+
activeBranch = branchA;
|
|
414
|
+
leafId = branchA.at(-1).id;
|
|
415
|
+
sessionName = "Generated after clear";
|
|
416
|
+
await handlers.get("session_tree")({ type: "session_tree", oldLeafId: "b-a1", newLeafId: leafId }, ctx);
|
|
417
|
+
const branchAProjection = branchA.findLast((entry) => entry.details?.kind === "state")?.details;
|
|
418
|
+
assert.equal(branchAProjection?.summaryMarkdown, "# Name cleared", "tree navigation restores the latest active-branch summary");
|
|
419
|
+
|
|
420
|
+
completeGate = new Promise((resolve) => { releaseComplete = resolve; });
|
|
421
|
+
fakeOutput = { version: 1, title: "Stale title", summaryMarkdown: "# Stale result" };
|
|
422
|
+
const staleCallIndex = completionCalls.length;
|
|
423
|
+
const staleRefresh = commands.get("summary").handler("refresh", ctx);
|
|
424
|
+
for (let i = 0; i < 20 && completionCalls.length === staleCallIndex; i += 1) await new Promise((resolve) => setImmediate(resolve));
|
|
425
|
+
assert.equal(completionCalls.length, staleCallIndex + 1);
|
|
426
|
+
activeBranch = branchB;
|
|
427
|
+
leafId = branchB.at(-1).id;
|
|
428
|
+
sessionName = undefined;
|
|
429
|
+
await handlers.get("session_tree")({ type: "session_tree", oldLeafId: branchA.at(-1).id, newLeafId: leafId }, ctx);
|
|
430
|
+
releaseComplete();
|
|
431
|
+
await staleRefresh;
|
|
432
|
+
assert.equal(latestSummaryState(branchB), undefined, "stale in-flight output is discarded after tree navigation");
|
|
433
|
+
const terminalProjection = branchB.findLast((entry) => entry.details?.kind === "state")?.details;
|
|
434
|
+
assert.equal(terminalProjection?.summaryMarkdown, undefined, "stale generation emits a terminal restored state");
|
|
435
|
+
assert.equal(branchB.findLast((entry) => entry.details?.kind)?.details.kind, "state", "stale generation does not leave the projection generating");
|
|
436
|
+
|
|
437
|
+
completeGate = Promise.resolve();
|
|
438
|
+
fakeOutput = { version: 1, summaryMarkdown: "# Provider-neutral" };
|
|
439
|
+
const representativeCases = [
|
|
440
|
+
{
|
|
441
|
+
model: { provider: "openai", id: "gpt-fake", api: "openai-responses", reasoning: true },
|
|
442
|
+
auth: { ok: true, apiKey: "openai-key", headers: { "x-openai": "yes" }, env: {} },
|
|
443
|
+
},
|
|
444
|
+
{
|
|
445
|
+
model: { provider: "anthropic", id: "claude-fake", api: "anthropic-messages", reasoning: true },
|
|
446
|
+
auth: { ok: true, headers: { "x-api-key": "header-only" }, env: {} },
|
|
447
|
+
},
|
|
448
|
+
{
|
|
449
|
+
model: { provider: "google", id: "gemini-fake", api: "google-generative-ai", reasoning: true },
|
|
450
|
+
auth: { ok: true, apiKey: "google-key", headers: {}, env: { GOOGLE_CLOUD_PROJECT: "fake" } },
|
|
451
|
+
},
|
|
452
|
+
{
|
|
453
|
+
model: { provider: "amazon-bedrock", id: "bedrock-fake", api: "bedrock-converse-stream", reasoning: true },
|
|
454
|
+
auth: { ok: true, headers: { "x-trace": "ambient" }, env: { AWS_PROFILE: "fake" } },
|
|
455
|
+
},
|
|
456
|
+
];
|
|
457
|
+
const routingIds = new Set();
|
|
458
|
+
for (const representative of representativeCases) {
|
|
459
|
+
fakeModel = representative.model;
|
|
460
|
+
fakeAuth = representative.auth;
|
|
461
|
+
await writeSessionSummaryPreferences({
|
|
462
|
+
configured: true,
|
|
463
|
+
enabled: true,
|
|
464
|
+
model: { provider: fakeModel.provider, modelId: fakeModel.id, thinkingLevel: "low" },
|
|
465
|
+
title: { enabled: false, minSettledTurns: 3 },
|
|
466
|
+
}, configFile);
|
|
467
|
+
const callIndex = completionCalls.length;
|
|
468
|
+
await commands.get("summary").handler("refresh", ctx);
|
|
469
|
+
assert.equal(completionCalls.length, callIndex + 1, `${fakeModel.api} uses exactly one request`);
|
|
470
|
+
const [calledModel, calledContext, calledOptions] = completionCalls.at(-1);
|
|
471
|
+
assert.equal(calledModel, fakeModel);
|
|
472
|
+
assert.equal(calledContext.tools, undefined, `${fakeModel.api} receives no tools`);
|
|
473
|
+
assert.equal(calledOptions.reasoning, "low", `${fakeModel.api} receives provider-neutral reasoning`);
|
|
474
|
+
assert.equal(calledOptions.reasoningEffort, undefined);
|
|
475
|
+
assert.equal(calledOptions.onPayload, undefined, `${fakeModel.api} payload is left to the installed adapter`);
|
|
476
|
+
assert.equal(calledOptions.maxTokens, SESSION_SUMMARY_MAX_OUTPUT_TOKENS);
|
|
477
|
+
assert.equal(calledOptions.cacheRetention, "none");
|
|
478
|
+
assert.equal(calledOptions.maxRetries, 0);
|
|
479
|
+
assert.equal(calledOptions.apiKey, representative.auth.apiKey);
|
|
480
|
+
assert.deepEqual(calledOptions.headers, representative.auth.headers);
|
|
481
|
+
assert.deepEqual(calledOptions.env, representative.auth.env);
|
|
482
|
+
routingIds.add(calledOptions.sessionId);
|
|
483
|
+
}
|
|
484
|
+
assert.equal(routingIds.size, representativeCases.length, "each representative provider call gets a fresh routing ID");
|
|
485
|
+
} finally {
|
|
486
|
+
if (previousConfigFile === undefined) delete process.env.PI_SESSION_SUMMARY_CONFIG_FILE;
|
|
487
|
+
else process.env.PI_SESSION_SUMMARY_CONFIG_FILE = previousConfigFile;
|
|
488
|
+
await rm(extensionTemp, { recursive: true, force: true });
|
|
489
|
+
}
|
|
490
|
+
|
|
491
|
+
console.log("session-summary core tests passed");
|