Spaces:
Paused
Paused
icebear icebear0828 commited on
fix: write runtime cache to data/ instead of git-tracked config/ (#138)
Browse filesmodel-store synced merged catalog back to config/models.yaml on every
backend fetch (~1h), and update-checker mutated config/default.yaml on
version detection. Both made the repo dirty after normal runtime.
- syncStaticModels() → data/models-cache.yaml (gitignored)
- applyVersionUpdate() → data/version-state.json (gitignored)
- loadStaticModels() overlays cache on cold start for fallback
- loadCurrentConfig() checks version override before YAML baseline
- config/ is now read-only for runtime operations
Co-authored-by: icebear0828 <icebear0828@users.noreply.github.com>
Files changed (5)
17 unmodified lines18192021222317 unmodified lines### Fixed- Responses SSE 新事件(`response.output_item.added` with `item.type=message`、`response.content_part.added/done`)未被识别,导致 `[CodexEvents] Unknown event` 日志刷屏- 新模型(如 `gpt-5.4-mini`)无法被动态发现的问题- 移除 `isCodexCompatibleId()` 白名单过滤,信任后端 `/codex/models` 返回17 unmodified lines181920212223242526272817 unmodified lines### Fixed- 运行时缓存(模型目录同步、版本检测结果)直接写入 git 跟踪的 `config/` 文件,导致仓库频繁变脏- `model-store` 的 `syncStaticModels()` 改写 `data/models-cache.yaml`(gitignored)- `update-checker` 的 `applyVersionUpdate()` 改写 `data/version-state.json`(gitignored)- `config/` 目录现在对运行时操作只读,仅 admin API 设置变更例外- Responses SSE 新事件(`response.output_item.added` with `item.type=message`、`response.content_part.added/done`)未被识别,导致 `[CodexEvents] Unknown event` 日志刷屏- 新模型(如 `gpt-5.4-mini`)无法被动态发现的问题- 移除 `isCodexCompatibleId()` 白名单过滤,信任后端 `/codex/models` 返回
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129/** * Tests that update-checker writes version state to data/ (gitignored), * NOT to config/default.yaml (git-tracked). */
import { describe, it, expect, beforeEach, vi } from "vitest";
const mockWriteFileSync = vi.fn();const mockExistsSync = vi.fn(() => false);const mockMkdirSync = vi.fn();const mockReadFileSync = vi.fn();const mockMutateClientConfig = vi.fn();
vi.mock("../config.js", () => ({ mutateClientConfig: mockMutateClientConfig, reloadAllConfigs: vi.fn(),}));
vi.mock("../paths.js", () => ({ getConfigDir: vi.fn(() => "/fake/config"), getDataDir: vi.fn(() => "/fake/data"), isEmbedded: vi.fn(() => false),}));
vi.mock("../utils/jitter.js", () => ({ jitterInt: vi.fn((ms: number) => ms),}));
vi.mock("../tls/curl-fetch.js", () => ({ curlFetchGet: vi.fn(),}));
vi.mock("fs", async (importOriginal) => { const actual = await importOriginal<typeof import("fs")>(); return { ...actual, readFileSync: mockReadFileSync, writeFileSync: mockWriteFileSync, existsSync: mockExistsSync, mkdirSync: mockMkdirSync, };});
vi.mock("js-yaml", () => ({ default: { load: vi.fn(() => ({ client: { app_version: "1.0.0", build_number: "100" }, })), },}));
import { curlFetchGet } from "../tls/curl-fetch.js";
const APPCAST_XML = `<?xml version="1.0"?><rss><channel><item> <enclosure sparkle:shortVersionString="2.0.0" sparkle:version="200" url="https://example.com/download"/></item></channel></rss>`;
describe("update-checker writes to data/, not config/", () => { beforeEach(() => { vi.clearAllMocks(); mockExistsSync.mockReturnValue(false); mockReadFileSync.mockReturnValue(""); });
it("applyVersionUpdate writes to data/version-state.json, not config/default.yaml", async () => { vi.mocked(curlFetchGet).mockResolvedValue({ ok: true, status: 200, body: APPCAST_XML, headers: {}, });
// Dynamic import to get fresh module state const { checkForUpdate } = await import("../update-checker.js"); await checkForUpdate();
// Should write version-state.json to data/ const versionWrites = mockWriteFileSync.mock.calls.filter( (call) => (call[0] as string).includes("version-state.json"), ); expect(versionWrites.length).toBeGreaterThanOrEqual(1); const writePath = versionWrites[0][0] as string; expect(writePath).toBe("/fake/data/version-state.json");
// Parse the written content const written = JSON.parse(versionWrites[0][1] as string) as { app_version: string; build_number: string; }; expect(written.app_version).toBe("2.0.0"); expect(written.build_number).toBe("200"); });
it("never calls mutateYaml on config/default.yaml", async () => { vi.mocked(curlFetchGet).mockResolvedValue({ ok: true, status: 200, body: APPCAST_XML, headers: {}, });
const { checkForUpdate } = await import("../update-checker.js"); await checkForUpdate();
// No writes should target config/default.yaml const configWrites = mockWriteFileSync.mock.calls.filter( (call) => (call[0] as string).includes("/fake/config/"), ); expect(configWrites).toHaveLength(0); });
it("updates runtime config via mutateClientConfig", async () => { vi.mocked(curlFetchGet).mockResolvedValue({ ok: true, status: 200, body: APPCAST_XML, headers: {}, });
const { checkForUpdate } = await import("../update-checker.js"); await checkForUpdate();
expect(mockMutateClientConfig).toHaveBeenCalledWith({ app_version: "2.0.0", build_number: "200", }); });});1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071/** * Tests that model-store writes cache to data/ (gitignored), * NOT to config/models.yaml (git-tracked). */
import { describe, it, expect, beforeEach, vi } from "vitest";
vi.mock("../../config.js", () => ({ getConfig: vi.fn(() => ({ server: {}, model: { default: "gpt-5.2-codex" }, api: { base_url: "https://chatgpt.com/backend-api" }, client: { app_version: "1.0.0" }, })),}));
vi.mock("../../paths.js", () => ({ getConfigDir: vi.fn(() => "/fake/config"), getDataDir: vi.fn(() => "/fake/data"),}));
vi.mock("fs", async (importOriginal) => { const actual = await importOriginal<typeof import("fs")>(); return { ...actual, readFileSync: vi.fn(() => "models: []\naliases: {}"), writeFileSync: vi.fn(), writeFile: vi.fn((_p: string, _d: string, _e: string, cb: (err: Error | null) => void) => cb(null)), existsSync: vi.fn(() => false), mkdirSync: vi.fn(), };});
vi.mock("js-yaml", () => ({ default: { load: vi.fn(() => ({ models: [], aliases: {} })), dump: vi.fn(() => "models: []"), },}));
import { writeFile, mkdirSync, existsSync } from "fs";import { loadStaticModels, applyBackendModels } from "../model-store.js";
describe("model cache writes to data/, not config/", () => { beforeEach(() => { vi.clearAllMocks(); vi.mocked(existsSync).mockReturnValue(false); loadStaticModels(); });
it("syncStaticModels writes to data/models-cache.yaml", () => { applyBackendModels([{ slug: "gpt-5.4", name: "GPT 5.4" }]);
expect(writeFile).toHaveBeenCalledOnce(); const writePath = vi.mocked(writeFile).mock.calls[0][0] as string; expect(writePath).toContain("/fake/data/models-cache.yaml"); });
it("syncStaticModels never writes to config/models.yaml", () => { applyBackendModels([{ slug: "gpt-5.4", name: "GPT 5.4" }]);
const writePath = vi.mocked(writeFile).mock.calls[0][0] as string; expect(writePath).not.toContain("/fake/config/"); });
it("ensures data dir exists before writing cache", () => { applyBackendModels([{ slug: "gpt-5.4", name: "GPT 5.4" }]);
expect(mkdirSync).toHaveBeenCalledWith("/fake/data", { recursive: true }); });});8 unmodified lines91011121314151617181940 unmodified lines606162636465135 unmodified lines2012022032042052062072082092102112122132142152162172182192202212222232242 unmodified lines2272282292302312322332342352362378 unmodified lines* Aliases always come from YAML (user-customizable), never from backend.*/import { readFileSync, writeFile } from "fs";import { resolve } from "path";import yaml from "js-yaml";import { getConfig } from "../config.js";import { getConfigDir } from "../paths.js";export interface CodexModelInfo {id: string;40 unmodified lines_planModelMap = new Map(); // Reset plan maps on reload_modelPlanIndex = new Map();console.log(`[ModelStore] Loaded ${_catalog.length} static models, ${Object.keys(_aliases).length} aliases`);}// ── Backend merge ──────────────────────────────────────────────────135 unmodified lines}/*** Write the current merged catalog back to config/models.yaml so it stays* up-to-date as a fallback for future cold starts. Fire-and-forget.*/function syncStaticModels(): void {const configPath = resolve(getConfigDir(), "models.yaml");const today = new Date().toISOString().slice(0, 10);// Strip internal `source` field before serializingconst models = _catalog.map(({ source: _s, ...rest }) => rest);const header = ["# Codex model catalog","#","# Sources:","# 1. Static (below) — baseline for cold starts","# 2. Dynamic — fetched from /backend-api/codex/models, auto-synced here","#",`# Last updated: ${today} (auto-synced by model-store)`,"",].join("\n");2 unmodified lines{ lineWidth: 120, noRefs: true, sortKeys: false },);writeFile(configPath, header + body, "utf-8", (err) => {if (err) {console.warn(`[ModelStore] Failed to sync models.yaml: ${err.message}`);} else {console.log(`[ModelStore] Synced ${models.length} models to models.yaml`);}});}8 unmodified lines91011121314151617181940 unmodified lines606162636465666768697071727374757677787980818283848586878889135 unmodified lines2252262272282292302312322332342352362372382392402412422432442452462472482492502 unmodified lines2532542552562572582592602612622632642652662672682698 unmodified lines* Aliases always come from YAML (user-customizable), never from backend.*/import { readFileSync, writeFile, existsSync, mkdirSync } from "fs";import { resolve } from "path";import yaml from "js-yaml";import { getConfig } from "../config.js";import { getConfigDir, getDataDir } from "../paths.js";export interface CodexModelInfo {id: string;40 unmodified lines_planModelMap = new Map(); // Reset plan maps on reload_modelPlanIndex = new Map();console.log(`[ModelStore] Loaded ${_catalog.length} static models, ${Object.keys(_aliases).length} aliases`);// Overlay cached backend models from data/ (cold-start fallback)try {const cachePath = resolve(getDataDir(), "models-cache.yaml");if (existsSync(cachePath)) {const cached = yaml.load(readFileSync(cachePath, "utf-8")) as ModelsConfig;const cachedModels = cached.models ?? [];if (cachedModels.length > 0) {const staticIds = new Set(_catalog.map((m) => m.id));let added = 0;for (const m of cachedModels) {if (!staticIds.has(m.id)) {_catalog.push({ ...m, source: "backend" as const });added++;}}if (added > 0) {console.log(`[ModelStore] Overlaid ${added} cached backend models from data/models-cache.yaml`);}}}} catch {// Cache missing or corrupt — safe to ignore, backend fetch will repopulate}}// ── Backend merge ──────────────────────────────────────────────────135 unmodified lines}/*** Write the current merged catalog to data/models-cache.yaml so it serves* as a fallback for future cold starts. Fire-and-forget.** config/models.yaml stays read-only (git-tracked baseline).*/function syncStaticModels(): void {const dataDir = getDataDir();const cachePath = resolve(dataDir, "models-cache.yaml");const today = new Date().toISOString().slice(0, 10);// Strip internal `source` field before serializingconst models = _catalog.map(({ source: _s, ...rest }) => rest);const header = ["# Codex model cache","#","# Auto-synced by model-store from backend fetch results.","# This is a runtime cache — do NOT commit to git.","#",`# Last updated: ${today}`,"",].join("\n");2 unmodified lines{ lineWidth: 120, noRefs: true, sortKeys: false },);try {mkdirSync(dataDir, { recursive: true });} catch {// already exists}writeFile(cachePath, header + body, "utf-8", (err) => {if (err) {console.warn(`[ModelStore] Failed to sync models cache: ${err.message}`);} else {console.log(`[ModelStore] Synced ${models.length} models to data/models-cache.yaml`);}});}
2 unmodified lines34567891011121314151619 unmodified lines3637383940414226 unmodified lines69707172737475767778792 unmodified lines* Automatically applies version updates to config file and runtime.*/import { readFileSync, writeFileSync, mkdirSync } from "fs";import { resolve } from "path";import { fork } from "child_process";import yaml from "js-yaml";import { mutateClientConfig, reloadAllConfigs } from "./config.js";import { jitterInt } from "./utils/jitter.js";import { curlFetchGet } from "./tls/curl-fetch.js";import { mutateYaml } from "./utils/yaml-mutate.js";import { getConfigDir, getDataDir, isEmbedded } from "./paths.js";function getConfigPath(): string {19 unmodified lineslet _pollTimer: ReturnType<typeof setTimeout> | null = null;let _updateInProgress = false;function loadCurrentConfig(): { app_version: string; build_number: string } {const raw = yaml.load(readFileSync(getConfigPath(), "utf-8")) as Record<string, unknown>;const client = raw.client as Record<string, string>;return {26 unmodified lines}function applyVersionUpdate(version: string, build: string): void {mutateYaml(getConfigPath(), (data) => {const client = data.client as Record<string, unknown>;client.app_version = version;client.build_number = build;});mutateClientConfig({ app_version: version, build_number: build });}2 unmodified lines345678910111213141519 unmodified lines35363738394041424344454647484950515253545556575859606126 unmodified lines8889909192939495969798991001011021031041052 unmodified lines* Automatically applies version updates to config file and runtime.*/import { readFileSync, writeFileSync, mkdirSync, existsSync } from "fs";import { resolve } from "path";import { fork } from "child_process";import yaml from "js-yaml";import { mutateClientConfig, reloadAllConfigs } from "./config.js";import { jitterInt } from "./utils/jitter.js";import { curlFetchGet } from "./tls/curl-fetch.js";import { getConfigDir, getDataDir, isEmbedded } from "./paths.js";function getConfigPath(): string {19 unmodified lineslet _pollTimer: ReturnType<typeof setTimeout> | null = null;let _updateInProgress = false;function getVersionOverridePath(): string {return resolve(getDataDir(), "version-state.json");}function loadCurrentConfig(): { app_version: string; build_number: string } {// Check runtime override first (written by applyVersionUpdate)try {const overridePath = getVersionOverridePath();if (existsSync(overridePath)) {const override = JSON.parse(readFileSync(overridePath, "utf-8")) as {app_version: string;build_number: string;};if (override.app_version && override.build_number) {return override;}}} catch {// Corrupt override — fall through to YAML baseline}const raw = yaml.load(readFileSync(getConfigPath(), "utf-8")) as Record<string, unknown>;const client = raw.client as Record<string, string>;return {26 unmodified lines}function applyVersionUpdate(version: string, build: string): void {// Persist to data/ (gitignored) — config/default.yaml stays read-onlytry {const dataDir = getDataDir();mkdirSync(dataDir, { recursive: true });writeFileSync(getVersionOverridePath(),JSON.stringify({ app_version: version, build_number: build }, null, 2),);} catch {// best-effort persistence}// Update runtime config in memorymutateClientConfig({ app_version: version, build_number: build });}
CHANGELOG.md+5
src/__tests__/update-checker.test.tsAdded+129
src/models/__tests__/model-cache.test.tsAdded+71
src/models/model-store.ts+45-13
src/update-checker.ts+33-7