refactor: centralize history context wrapping

This commit is contained in:
Peter Steinberger
2026-01-10 19:09:06 +01:00
parent b977ae19af
commit 82f71d25e5
8 changed files with 137 additions and 83 deletions

View File

@@ -3,6 +3,7 @@ import {
appendHistoryEntry,
buildHistoryContext,
buildHistoryContextFromEntries,
buildHistoryContextFromMap,
HISTORY_CONTEXT_MARKER,
} from "./history.js";
import { CURRENT_MESSAGE_MARKER } from "./mentions.js";
@@ -60,4 +61,31 @@ describe("history helpers", () => {
"three",
]);
});
it("builds context from map and appends entry", () => {
const historyMap = new Map<string, { sender: string; body: string }[]>();
historyMap.set("room", [
{ sender: "A", body: "one" },
{ sender: "B", body: "two" },
]);
const result = buildHistoryContextFromMap({
historyMap,
historyKey: "room",
limit: 3,
entry: { sender: "C", body: "three" },
currentMessage: "current",
formatEntry: (entry) => `${entry.sender}: ${entry.body}`,
});
expect(historyMap.get("room")?.map((entry) => entry.body)).toEqual([
"one",
"two",
"three",
]);
expect(result).toContain(HISTORY_CONTEXT_MARKER);
expect(result).toContain("A: one");
expect(result).toContain("B: two");
expect(result).not.toContain("C: three");
});
});

View File

@@ -43,6 +43,41 @@ export function appendHistoryEntry(params: {
return history;
}
export function buildHistoryContextFromMap(params: {
historyMap: Map<string, HistoryEntry[]>;
historyKey: string;
limit: number;
entry?: HistoryEntry;
currentMessage: string;
formatEntry: (entry: HistoryEntry) => string;
lineBreak?: string;
excludeLast?: boolean;
}): string {
if (params.limit <= 0) return params.currentMessage;
const entries = params.entry
? appendHistoryEntry({
historyMap: params.historyMap,
historyKey: params.historyKey,
entry: params.entry,
limit: params.limit,
})
: (params.historyMap.get(params.historyKey) ?? []);
return buildHistoryContextFromEntries({
entries,
currentMessage: params.currentMessage,
formatEntry: params.formatEntry,
lineBreak: params.lineBreak,
excludeLast: params.excludeLast,
});
}
export function clearHistoryEntries(params: {
historyMap: Map<string, HistoryEntry[]>;
historyKey: string;
}): void {
params.historyMap.set(params.historyKey, []);
}
export function buildHistoryContextFromEntries(params: {
entries: HistoryEntry[];
currentMessage: string;