// @vitest-environment node import { mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs"; import { tmpdir } from "node:os"; import { join } from "node:path"; import { afterEach, beforeEach, describe, expect, it } from "vitest"; import { MEMORY_TEXT_MAX, addMemory, memoryPath, memoryTextProblem, readMemory, removeMemory, } from "./userMemory.js"; let configDir: string; const previous = process.env.HYPERFRAMES_CONFIG_DIR; beforeEach(() => { configDir = mkdtempSync(join(tmpdir(), "hf-memory-")); process.env.HYPERFRAMES_CONFIG_DIR = configDir; }); afterEach(() => { if (previous === undefined) delete process.env.HYPERFRAMES_CONFIG_DIR; else process.env.HYPERFRAMES_CONFIG_DIR = previous; rmSync(configDir, { recursive: true, force: true }); }); describe("user memory", () => { it("starts empty and keeps items in the order they were added", () => { expect(readMemory()).toEqual([]); addMemory("Never open Studio in my browser", new Date("2026-12-01T00:00:00Z")); addMemory(" Captions in Chinese "); expect(readMemory().map(({ id, text }) => [id, text])).toEqual([ [1, "Never open Studio in my browser"], [2, "Captions in Chinese"], ]); expect(readMemory()[0]!.addedAt).toBe("2026-12-01T00:00:00.000Z"); expect(memoryPath()).toBe(join(configDir, "memory.json")); }); it("does not add the same words twice", () => { const first = addMemory("Always 9:16"); const again = addMemory("always 9:16"); expect(again).toEqual({ added: false, item: first.item }); expect(readMemory()).toHaveLength(1); }); it("removes by id without reusing the number", () => { addMemory("a"); addMemory("b"); expect(removeMemory(1)?.text).toBe("a"); expect(removeMemory(1)).toBeUndefined(); expect(addMemory("c").item.id).toBe(3); }); it("does not reuse the number of the last item removed", () => { addMemory("a"); expect(removeMemory(1)?.text).toBe("a"); expect(addMemory("b").item.id).toBe(2); }); it("refuses empty and overlong text", () => { expect(memoryTextProblem(" ")).toMatch(/empty/); expect(memoryTextProblem("x".repeat(MEMORY_TEXT_MAX + 1))).toMatch(/under 500/); expect(() => addMemory("")).toThrow(/empty/); expect(readMemory()).toEqual([]); }); it("reads a damaged file as empty and skips malformed entries", () => { writeFileSync(memoryPath(), "{oops"); expect(readMemory()).toEqual([]); writeFileSync( memoryPath(), JSON.stringify({ items: [ { id: 1, text: "ok", addedAt: "t" }, { id: "2", text: "bad" }, ], }), ); expect(readMemory().map((item) => item.text)).toEqual(["ok"]); addMemory("next"); expect(JSON.parse(readFileSync(memoryPath(), "utf-8")).version).toBe(1); }); });