pi-opencode-go-provider 1.1.21 → 1.1.26

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/sync-policy.ts ADDED
@@ -0,0 +1,309 @@
1
+ /**
2
+ * Quiet startup sync — shared policy for background model-catalog revalidation.
3
+ *
4
+ * Every pi process (interactive start, /new, /reload, `pi -p`, and every child
5
+ * agent a fan-out tool spawns) fires `session_start`. Revalidating the live
6
+ * `/models` catalog on each of those spams the provider API, so this module
7
+ * decides — without any network I/O and without ever throwing — whether *this*
8
+ * process should fetch at all:
9
+ *
10
+ * 1. No credentials → no fetch (serve disk cache → embedded models.json).
11
+ * 2. Freshness window → skip while the disk cache is younger than the TTL.
12
+ * TTL source: the cache file's mtime. The cache is only (re)written after a
13
+ * successful live fetch, so mtime is "last fetched at" — and caches written
14
+ * by older extension versions carry it too, with no format change.
15
+ * Default 1 hour; override with PI_PROVIDER_SYNC_TTL_MS (0 = always).
16
+ * 3. Forced refresh ignores the TTL: cache missing/corrupt, API key changed
17
+ * since the cache was fetched (compared via a salted sha256 fingerprint —
18
+ * never the key itself), or the caller passes `force` (e.g. after /login).
19
+ * 4. Failure backoff → after a failed fetch with the same key, non-forced
20
+ * attempts wait min(5 min, TTL) so a bad key or outage is not retried by
21
+ * every process that starts.
22
+ * 5. Cross-process single-flight → an atomic lock file (`open(…, "wx")`) next
23
+ * to the cache; whoever creates it fetches, everyone else skips and keeps
24
+ * serving the cache. Locks older than the stale timeout (crashed holder)
25
+ * are reclaimed. Any filesystem error fails open to "skip the fetch".
26
+ *
27
+ * Files (for a cache at `<agentDir>/cache/<provider>-models.json`):
28
+ * <provider>-models.json the cache itself — unchanged plain JSON array
29
+ * <provider>-models.sync.json sidecar: { version, keyFingerprint, fetchedAt, failedAt?, failedKeyFingerprint? }
30
+ * <provider>-models.lock present only while one process is fetching
31
+ *
32
+ * Older extension versions ignore the sidecar/lock and read the cache as
33
+ * before; a cache without a sidecar (written by an older version) is treated
34
+ * as "fetched with an unknown key" and revalidated once (still single-flight).
35
+ *
36
+ * This file is provider-agnostic: it is copied verbatim into every
37
+ * pi-*-provider repo. Keep it free of pi imports and provider specifics.
38
+ *
39
+ * Typical use inside a provider's revalidateModels():
40
+ *
41
+ * const lease = acquireModelSync({ cachePath: CACHE_PATH, apiKey, force });
42
+ * if (!lease) return cacheChangedSinceLoad(CACHE_PATH) ? loadStaleModels(embedded) : null;
43
+ * let merged = null;
44
+ * try { …fetch, merge, cacheModels(merged)…; return merged; }
45
+ * finally { lease.release(merged ? "fetched" : signal?.aborted ? "aborted" : "failed"); }
46
+ */
47
+
48
+ import crypto from "crypto";
49
+ import fs from "fs";
50
+ import path from "path";
51
+
52
+ /** Env override for the freshness window, shared by all pi-*-provider extensions. */
53
+ export const SYNC_TTL_ENV = "PI_PROVIDER_SYNC_TTL_MS";
54
+ export const DEFAULT_SYNC_TTL_MS = 60 * 60 * 1000;
55
+ /** A lock older than this is assumed abandoned (crashed holder). Must exceed the fetch timeout. */
56
+ export const DEFAULT_LOCK_STALE_MS = 60 * 1000;
57
+ /** Pause after a failed fetch (same key) before non-forced retries; capped at the TTL. */
58
+ export const FAILURE_BACKOFF_MS = 5 * 60 * 1000;
59
+
60
+ /** Why this process was granted the fetch. */
61
+ export type SyncReason = "missing" | "key-changed" | "forced" | "stale";
62
+ /** Why this process must not fetch (serve cache/embedded instead). */
63
+ export type SkipReason = "no-key" | "fresh" | "backoff" | "locked" | "unwritable";
64
+ /** How a granted fetch ended; "aborted" (session replaced/shut down) records no failure. */
65
+ export type SyncOutcome = "fetched" | "failed" | "aborted";
66
+
67
+ export type SyncPlan = { fetch: true; reason: SyncReason } | { fetch: false; reason: SkipReason };
68
+
69
+ export interface ModelSyncOptions {
70
+ /** Absolute path of the provider's disk cache, e.g. `<agentDir>/cache/<provider>-models.json`. */
71
+ cachePath: string;
72
+ /** Resolved credential. Falsy → never fetch. */
73
+ apiKey: string | undefined | null;
74
+ /** Revalidate regardless of TTL/backoff (e.g. right after /login). Still single-flight. */
75
+ force?: boolean;
76
+ /** Freshness window; defaults to $PI_PROVIDER_SYNC_TTL_MS, else 1 hour. */
77
+ ttlMs?: number;
78
+ lockStaleMs?: number;
79
+ /** Cache validity check; defaults to "non-empty JSON array" (the models cache format). */
80
+ isValidCache?: (data: unknown) => boolean;
81
+ /** Clock override for tests. */
82
+ now?: number;
83
+ /** Optional diagnostics hook: called with the reason whenever the fetch is skipped. */
84
+ onSkip?: (reason: SkipReason) => void;
85
+ }
86
+
87
+ export interface ModelSyncLease {
88
+ readonly reason: SyncReason;
89
+ /** Always call exactly once (use try/finally). Records the outcome and drops the lock. */
90
+ release(outcome: SyncOutcome): void;
91
+ }
92
+
93
+ interface SyncMeta {
94
+ version: 1;
95
+ keyFingerprint?: string;
96
+ fetchedAt?: number;
97
+ failedAt?: number;
98
+ failedKeyFingerprint?: string;
99
+ }
100
+
101
+ // ─── Small helpers ────────────────────────────────────────────────────────────
102
+
103
+ /** Salted, truncated sha256 of the key: detects key changes, cannot be reversed into the key. */
104
+ export function keyFingerprint(apiKey: string): string {
105
+ return crypto.createHash("sha256").update(`pi-provider-sync\0${apiKey}`).digest("hex").slice(0, 16);
106
+ }
107
+
108
+ export function resolveSyncTtlMs(ttlMs?: number): number {
109
+ if (typeof ttlMs === "number" && Number.isFinite(ttlMs) && ttlMs >= 0) return ttlMs;
110
+ const raw = process.env[SYNC_TTL_ENV];
111
+ const fromEnv = raw === undefined || raw.trim() === "" ? NaN : Number(raw);
112
+ return Number.isFinite(fromEnv) && fromEnv >= 0 ? fromEnv : DEFAULT_SYNC_TTL_MS;
113
+ }
114
+
115
+ /** `foo-models.json` → `foo-models` (sidecar/lock base name). */
116
+ function sidecarBase(cachePath: string): string {
117
+ return cachePath.replace(/\.json$/i, "");
118
+ }
119
+ export const syncMetaPath = (cachePath: string): string => `${sidecarBase(cachePath)}.sync.json`;
120
+ export const syncLockPath = (cachePath: string): string => `${sidecarBase(cachePath)}.lock`;
121
+
122
+ function mtimeMs(file: string): number | null {
123
+ try {
124
+ return fs.statSync(file).mtimeMs;
125
+ } catch {
126
+ return null;
127
+ }
128
+ }
129
+
130
+ function readJson(file: string): unknown {
131
+ try {
132
+ return JSON.parse(fs.readFileSync(file, "utf8"));
133
+ } catch {
134
+ return undefined;
135
+ }
136
+ }
137
+
138
+ function readMeta(cachePath: string): SyncMeta | null {
139
+ const data = readJson(syncMetaPath(cachePath));
140
+ return data && typeof data === "object" && !Array.isArray(data) ? (data as SyncMeta) : null;
141
+ }
142
+
143
+ /**
144
+ * Write via temp file + rename so concurrent readers in other processes never
145
+ * observe a half-written file (a torn cache would otherwise read as "corrupt"
146
+ * and force a refetch). Throws on failure — callers decide whether that is fatal.
147
+ */
148
+ export function writeFileAtomic(file: string, contents: string): void {
149
+ const tmp = `${file}.${process.pid}.${crypto.randomBytes(4).toString("hex")}.tmp`;
150
+ try {
151
+ fs.writeFileSync(tmp, contents);
152
+ fs.renameSync(tmp, file);
153
+ } catch (error) {
154
+ try { fs.unlinkSync(tmp); } catch { /* already gone */ }
155
+ throw error;
156
+ }
157
+ }
158
+
159
+ function writeMeta(cachePath: string, meta: SyncMeta): void {
160
+ try {
161
+ writeFileAtomic(syncMetaPath(cachePath), JSON.stringify(meta) + "\n");
162
+ } catch {
163
+ // Non-fatal: worst case the next process revalidates once more.
164
+ }
165
+ }
166
+
167
+ // ─── In-process view of the shared cache ──────────────────────────────────────
168
+
169
+ // mtime of the cache as this process last loaded/wrote it, per cache path.
170
+ const loadedCacheMtimes = new Map<string, number>();
171
+
172
+ /** Call right before reading the disk cache at startup (stat-before-read keeps races harmless). */
173
+ export function markCacheLoaded(cachePath: string): void {
174
+ loadedCacheMtimes.set(cachePath, mtimeMs(cachePath) ?? 0);
175
+ }
176
+
177
+ /**
178
+ * True when another process rewrote the shared cache since this process last
179
+ * loaded it, so a long-lived session can adopt the newer catalog from disk
180
+ * instead of fetching it again.
181
+ */
182
+ export function cacheChangedSinceLoad(cachePath: string): boolean {
183
+ const current = mtimeMs(cachePath);
184
+ return current !== null && current !== loadedCacheMtimes.get(cachePath);
185
+ }
186
+
187
+ // ─── Policy ───────────────────────────────────────────────────────────────────
188
+
189
+ const isNonEmptyArray = (data: unknown): boolean => Array.isArray(data) && data.length > 0;
190
+
191
+ /** Decide whether a fetch is warranted (no lock taken, no I/O beyond local stat/read). */
192
+ export function planModelSync(options: ModelSyncOptions): SyncPlan {
193
+ const { cachePath, apiKey, force = false } = options;
194
+ if (!apiKey) return { fetch: false, reason: "no-key" };
195
+
196
+ const now = options.now ?? Date.now();
197
+ const ttlMs = resolveSyncTtlMs(options.ttlMs);
198
+ const fingerprint = keyFingerprint(apiKey);
199
+ const meta = readMeta(cachePath);
200
+ const cacheMtime = mtimeMs(cachePath);
201
+ const valid = cacheMtime !== null && (options.isValidCache ?? isNonEmptyArray)(readJson(cachePath));
202
+
203
+ let reason: SyncReason;
204
+ if (!valid) reason = "missing";
205
+ // A cache without a sidecar (older extension version) counts as an unknown key.
206
+ else if (meta?.keyFingerprint !== fingerprint) reason = "key-changed";
207
+ else if (force) reason = "forced";
208
+ else if (now - cacheMtime < ttlMs) return { fetch: false, reason: "fresh" };
209
+ else reason = "stale";
210
+
211
+ if (!force && meta?.failedKeyFingerprint === fingerprint && typeof meta.failedAt === "number"
212
+ && now - meta.failedAt < Math.min(FAILURE_BACKOFF_MS, ttlMs)) {
213
+ return { fetch: false, reason: "backoff" };
214
+ }
215
+ return { fetch: true, reason };
216
+ }
217
+
218
+ /** Atomically create the lock file; reclaim it once if its holder looks dead. */
219
+ function tryLock(lockPath: string, token: string, lockStaleMs: number, now: number): "locked" | "held" | "unwritable" {
220
+ try {
221
+ fs.mkdirSync(path.dirname(lockPath), { recursive: true });
222
+ } catch {
223
+ return "unwritable";
224
+ }
225
+ for (let attempt = 0; attempt < 2; attempt++) {
226
+ let fd: number;
227
+ try {
228
+ fd = fs.openSync(lockPath, "wx");
229
+ } catch (error) {
230
+ // EEXIST: someone holds the lock. Anything else (EACCES, ENOTDIR, EROFS…):
231
+ // the cache dir is unusable — fail open to "skip the fetch".
232
+ if ((error as NodeJS.ErrnoException)?.code !== "EEXIST") return "unwritable";
233
+ if (attempt > 0) return "held";
234
+ const lockMtime = mtimeMs(lockPath);
235
+ if (lockMtime === null) continue; // released between open and stat: retry once
236
+ if (now - lockMtime <= lockStaleMs) return "held"; // a live process is fetching
237
+ // Stale: the holder crashed or hung. Reclaim and retry once. (Two processes
238
+ // reclaiming the same stale lock at the same instant may both fetch — a rare,
239
+ // harmless duplicate.)
240
+ try { fs.unlinkSync(lockPath); } catch { /* someone else reclaimed it first */ }
241
+ continue;
242
+ }
243
+ // We own the lock. Record a token so release() only deletes our own lock.
244
+ let wrote = false;
245
+ try {
246
+ fs.writeSync(fd, JSON.stringify({ pid: process.pid, token, at: now }));
247
+ wrote = true;
248
+ } catch {
249
+ // e.g. ENOSPC — handled below
250
+ } finally {
251
+ try { fs.closeSync(fd); } catch { /* ignore */ }
252
+ }
253
+ if (wrote) return "locked";
254
+ try { fs.unlinkSync(lockPath); } catch { /* ignore */ }
255
+ return "unwritable";
256
+ }
257
+ return "held";
258
+ }
259
+
260
+ /**
261
+ * Decide and, when this process should fetch, take the cross-process lock.
262
+ * Returns null when the caller must skip the network (serve cache/embedded).
263
+ * Never throws.
264
+ */
265
+ export function acquireModelSync(options: ModelSyncOptions): ModelSyncLease | null {
266
+ try {
267
+ const plan = planModelSync(options);
268
+ if (!plan.fetch) return skip(options, plan.reason);
269
+
270
+ const { cachePath } = options;
271
+ const now = options.now ?? Date.now();
272
+ const lockPath = syncLockPath(cachePath);
273
+ const token = crypto.randomBytes(8).toString("hex");
274
+ const lock = tryLock(lockPath, token, options.lockStaleMs ?? DEFAULT_LOCK_STALE_MS, now);
275
+ if (lock !== "locked") return skip(options, lock === "held" ? "locked" : "unwritable");
276
+
277
+ const fingerprint = keyFingerprint(options.apiKey as string);
278
+ let released = false;
279
+ return {
280
+ reason: plan.reason,
281
+ release(outcome: SyncOutcome): void {
282
+ if (released) return;
283
+ released = true;
284
+ try {
285
+ const at = Date.now();
286
+ if (outcome === "fetched") {
287
+ writeMeta(cachePath, { version: 1, keyFingerprint: fingerprint, fetchedAt: at });
288
+ markCacheLoaded(cachePath); // our own write is not "another process's" update
289
+ } else if (outcome === "failed") {
290
+ const previous = readMeta(cachePath);
291
+ writeMeta(cachePath, { ...previous, version: 1, failedAt: at, failedKeyFingerprint: fingerprint });
292
+ }
293
+ // Only remove the lock if it is still ours (it may have been reclaimed as stale).
294
+ const held = readJson(lockPath) as { token?: string } | undefined;
295
+ if (held?.token === token) fs.unlinkSync(lockPath);
296
+ } catch {
297
+ // Never throw from cleanup; a leftover lock expires after lockStaleMs.
298
+ }
299
+ },
300
+ };
301
+ } catch {
302
+ return skip(options, "unwritable");
303
+ }
304
+ }
305
+
306
+ function skip(options: ModelSyncOptions, reason: SkipReason): null {
307
+ try { options.onSkip?.(reason); } catch { /* diagnostics must never break startup */ }
308
+ return null;
309
+ }
@@ -1,5 +1,8 @@
1
1
  import assert from "node:assert/strict";
2
- import { test } from "node:test";
2
+ import fs from "node:fs";
3
+ import os from "node:os";
4
+ import path from "node:path";
5
+ import { afterEach, beforeEach, test } from "node:test";
3
6
  import type { ExtensionContext } from "@earendil-works/pi-coding-agent";
4
7
  import { DEFAULT_USAGE_CONFIG, PROVIDER_ID } from "../config.ts";
5
8
  import {
@@ -10,6 +13,21 @@ import {
10
13
  } from "../multiprovider.ts";
11
14
  import { UsageController } from "../usage-controller.ts";
12
15
 
16
+ // Usage polls share a snapshot under <agentDir>/cache (quiet startup sync):
17
+ // give every test its own empty agent dir so each one polls, and never touch ~/.pi.
18
+ let agentDir: string;
19
+ let previousAgentDir: string | undefined;
20
+ beforeEach(() => {
21
+ previousAgentDir = process.env.PI_CODING_AGENT_DIR;
22
+ agentDir = fs.mkdtempSync(path.join(os.tmpdir(), "pi-opencode-go-multiprovider-"));
23
+ process.env.PI_CODING_AGENT_DIR = agentDir;
24
+ });
25
+ afterEach(() => {
26
+ if (previousAgentDir === undefined) delete process.env.PI_CODING_AGENT_DIR;
27
+ else process.env.PI_CODING_AGENT_DIR = previousAgentDir;
28
+ fs.rmSync(agentDir, { recursive: true, force: true });
29
+ });
30
+
13
31
  function fakeService(
14
32
  resolve: () => Promise<MultiproviderAccountAuth | undefined>,
15
33
  ): { value: MultiproviderService; resolveActiveAccountAuth: () => Promise<MultiproviderAccountAuth | undefined> } {
@@ -0,0 +1,267 @@
1
+ /**
2
+ * Quiet startup sync, end to end through the extension's real session_start
3
+ * handler: the live /models catalog is fetched only with a key, only when the
4
+ * disk cache is stale (or the key changed), only by one process at a time, and
5
+ * never on the session_start critical path.
6
+ *
7
+ * Porting: only the "Provider specifics" block below differs between
8
+ * pi-*-provider repos.
9
+ */
10
+
11
+ import { afterEach, describe, expect, it, vi } from "vitest";
12
+ import fs from "node:fs";
13
+ import os from "node:os";
14
+ import path from "node:path";
15
+ import { keyFingerprint, syncLockPath, syncMetaPath } from "../sync-policy";
16
+ import embeddedModels from "../models.json" with { type: "json" };
17
+
18
+ // ─── Provider specifics ───────────────────────────────────────────────────────
19
+ const PROVIDER_ID = "opencode-go";
20
+ const LIVE_ONLY_ID = "live-only-test-model";
21
+ /** A minimal successful /models response containing LIVE_ONLY_ID. */
22
+ const liveModelsResponse = () => Response.json({
23
+ object: "list",
24
+ data: [{ id: LIVE_ONLY_ID, object: "model", created: 0, owned_by: "opencode" }],
25
+ });
26
+ /**
27
+ * session_start ctx. hasUI: false (print mode / child agent) keeps the usage
28
+ * widget from polling, so every fetch counted here is a /models request.
29
+ * Usage polling dedupe is covered in usage-sync.test.ts.
30
+ */
31
+ const sessionCtx = (getApiKeyForProvider: unknown) => ({ hasUI: false, modelRegistry: { getApiKeyForProvider } });
32
+ // ──────────────────────────────────────────────────────────────────────────────
33
+
34
+ const HOUR = 60 * 60 * 1000;
35
+ const KEY = "sk-quiet-sync-test";
36
+
37
+ let home: string;
38
+ let cachePath: string;
39
+
40
+ afterEach(() => {
41
+ vi.unstubAllEnvs();
42
+ vi.unstubAllGlobals();
43
+ vi.resetModules();
44
+ if (home) fs.rmSync(home, { recursive: true, force: true });
45
+ });
46
+
47
+ function setupHome(): void {
48
+ home = fs.mkdtempSync(path.join(os.tmpdir(), `pi-${PROVIDER_ID}-sync-`));
49
+ cachePath = path.join(home, "cache", `${PROVIDER_ID}-models.json`);
50
+ vi.stubEnv("PI_CODING_AGENT_DIR", home);
51
+ vi.stubEnv("PI_PROVIDER_SYNC_TTL_MS", "");
52
+ }
53
+
54
+ function writeCache(ageMs: number, models: unknown[] = embeddedModels, fingerprintKey: string | null = KEY): void {
55
+ fs.mkdirSync(path.dirname(cachePath), { recursive: true });
56
+ fs.writeFileSync(cachePath, JSON.stringify(models));
57
+ const t = new Date(Date.now() - ageMs);
58
+ fs.utimesSync(cachePath, t, t);
59
+ if (fingerprintKey !== null) {
60
+ fs.writeFileSync(syncMetaPath(cachePath), JSON.stringify({ version: 1, keyFingerprint: keyFingerprint(fingerprintKey) }));
61
+ }
62
+ }
63
+
64
+ function stubFetch(impl: () => Promise<Response> = async () => liveModelsResponse()) {
65
+ const fetch = vi.fn(impl);
66
+ vi.stubGlobal("fetch", fetch);
67
+ return fetch;
68
+ }
69
+
70
+ /** Load the extension fresh (module-level cache paths read PI_CODING_AGENT_DIR). */
71
+ async function loadExtension() {
72
+ vi.resetModules();
73
+ const mod = await import("../index");
74
+ const handlers = new Map<string, (...args: any[]) => any>();
75
+ const registrations: Array<{ models: Array<{ id: string }> }> = [];
76
+ mod.default({
77
+ on: (event: string, handler: (...args: any[]) => any) => handlers.set(event, handler),
78
+ registerProvider: (_id: string, config: any) => registrations.push(config),
79
+ registerCommand: () => {},
80
+ } as any);
81
+ const getApiKeyForProvider = vi.fn(async (): Promise<string | undefined> => KEY);
82
+ const startSession = () => handlers.get("session_start")!({ type: "session_start" }, sessionCtx(getApiKeyForProvider));
83
+ return { handlers, registrations, getApiKeyForProvider, startSession };
84
+ }
85
+
86
+ /** Let the fire-and-forget revalidation chain run to completion. */
87
+ const settle = () => new Promise((resolve) => setTimeout(resolve, 50));
88
+ const hasLiveModel = (config: { models: Array<{ id: string }> } | undefined) => !!config?.models.some((m) => m.id === LIVE_ONLY_ID);
89
+
90
+ describe("quiet startup sync", () => {
91
+ it("skips the live fetch while the disk cache is fresher than the TTL", async () => {
92
+ setupHome();
93
+ writeCache(10 * 60 * 1000);
94
+ const fetch = stubFetch();
95
+ const ext = await loadExtension();
96
+ await ext.startSession();
97
+ await settle();
98
+ expect(ext.getApiKeyForProvider).toHaveBeenCalled();
99
+ expect(fetch).not.toHaveBeenCalled();
100
+ expect(ext.registrations).toHaveLength(1);
101
+ });
102
+
103
+ it("revalidates a stale cache once, hot-swaps the catalog and rewrites the cache", async () => {
104
+ setupHome();
105
+ writeCache(2 * HOUR);
106
+ const fetch = stubFetch();
107
+ const ext = await loadExtension();
108
+ await ext.startSession();
109
+ await vi.waitFor(() => expect(hasLiveModel(ext.registrations.at(-1))).toBe(true));
110
+ expect(fetch).toHaveBeenCalledOnce();
111
+ const cached = JSON.parse(fs.readFileSync(cachePath, "utf8"));
112
+ // Cache stays a plain JSON array so older extension versions still read it.
113
+ expect(Array.isArray(cached)).toBe(true);
114
+ expect(cached.some((m: { id: string }) => m.id === LIVE_ONLY_ID)).toBe(true);
115
+ expect(Date.now() - fs.statSync(cachePath).mtimeMs).toBeLessThan(60_000);
116
+ expect(fs.existsSync(syncLockPath(cachePath))).toBe(false);
117
+ const meta = fs.readFileSync(syncMetaPath(cachePath), "utf8");
118
+ expect(meta).not.toContain(KEY);
119
+ expect(JSON.parse(meta).keyFingerprint).toBe(keyFingerprint(KEY));
120
+
121
+ // A second session in the same process (/new) is now inside the TTL.
122
+ await ext.startSession();
123
+ await settle();
124
+ expect(fetch).toHaveBeenCalledOnce();
125
+ });
126
+
127
+ it("never touches the network without an API key", async () => {
128
+ setupHome();
129
+ const fetch = stubFetch();
130
+ const ext = await loadExtension();
131
+ ext.getApiKeyForProvider.mockResolvedValue(undefined);
132
+ await ext.startSession();
133
+ await settle();
134
+ expect(fetch).not.toHaveBeenCalled();
135
+ expect(fs.existsSync(syncLockPath(cachePath))).toBe(false);
136
+ expect(ext.registrations).toHaveLength(1);
137
+ });
138
+
139
+ it("skips when another process holds the revalidation lock", async () => {
140
+ setupHome();
141
+ writeCache(2 * HOUR);
142
+ fs.writeFileSync(syncLockPath(cachePath), JSON.stringify({ pid: 999999, token: "other-process" }));
143
+ const fetch = stubFetch();
144
+ const ext = await loadExtension();
145
+ await ext.startSession();
146
+ await settle();
147
+ expect(fetch).not.toHaveBeenCalled();
148
+ expect(JSON.parse(fs.readFileSync(syncLockPath(cachePath), "utf8")).token).toBe("other-process");
149
+ });
150
+
151
+ it("reclaims a stale lock left by a crashed process", async () => {
152
+ setupHome();
153
+ writeCache(2 * HOUR);
154
+ const lockPath = syncLockPath(cachePath);
155
+ fs.writeFileSync(lockPath, JSON.stringify({ pid: 999999, token: "crashed" }));
156
+ const old = new Date(Date.now() - 10 * 60 * 1000);
157
+ fs.utimesSync(lockPath, old, old);
158
+ const fetch = stubFetch();
159
+ const ext = await loadExtension();
160
+ await ext.startSession();
161
+ await vi.waitFor(() => expect(hasLiveModel(ext.registrations.at(-1))).toBe(true));
162
+ expect(fetch).toHaveBeenCalledOnce();
163
+ expect(fs.existsSync(lockPath)).toBe(false);
164
+ });
165
+
166
+ it("forces a revalidation when the API key changed, even inside the TTL", async () => {
167
+ setupHome();
168
+ writeCache(60 * 1000, embeddedModels, "previous-key");
169
+ const fetch = stubFetch();
170
+ const ext = await loadExtension();
171
+ await ext.startSession();
172
+ await vi.waitFor(() => expect(hasLiveModel(ext.registrations.at(-1))).toBe(true));
173
+ expect(fetch).toHaveBeenCalledOnce();
174
+ });
175
+
176
+ it("revalidates once when the cache predates the sync sidecar (older extension version)", async () => {
177
+ setupHome();
178
+ writeCache(60 * 1000, embeddedModels, null);
179
+ const fetch = stubFetch();
180
+ const ext = await loadExtension();
181
+ expect(ext.registrations[0].models.length).toBeGreaterThan(0); // old cache is still served
182
+ await ext.startSession();
183
+ await vi.waitFor(() => expect(hasLiveModel(ext.registrations.at(-1))).toBe(true));
184
+ expect(fetch).toHaveBeenCalledOnce();
185
+ });
186
+
187
+ it("does not throw or fetch when the cache dir is unwritable", async () => {
188
+ setupHome();
189
+ fs.writeFileSync(path.join(home, "cache"), "a file where the cache dir should be");
190
+ const fetch = stubFetch();
191
+ const ext = await loadExtension();
192
+ await expect(ext.startSession()).resolves.toBeUndefined();
193
+ await settle();
194
+ expect(fetch).not.toHaveBeenCalled();
195
+ expect(ext.registrations).toHaveLength(1);
196
+ });
197
+
198
+ it("does not await the network in session_start", async () => {
199
+ setupHome();
200
+ writeCache(2 * HOUR);
201
+ let release!: () => void;
202
+ const fetch = stubFetch(() => new Promise<Response>((resolve) => { release = () => resolve(liveModelsResponse()); }));
203
+ const ext = await loadExtension();
204
+ const outcome = await Promise.race([
205
+ Promise.resolve(ext.startSession()).then(() => "returned"),
206
+ new Promise((resolve) => setTimeout(() => resolve("blocked"), 1000)),
207
+ ]);
208
+ expect(outcome).toBe("returned");
209
+ await vi.waitFor(() => expect(fetch).toHaveBeenCalledOnce());
210
+ release();
211
+ await vi.waitFor(() => expect(hasLiveModel(ext.registrations.at(-1))).toBe(true));
212
+ });
213
+
214
+ it("swallows API key resolution failures (no unhandled rejection)", async () => {
215
+ setupHome();
216
+ const fetch = stubFetch();
217
+ const ext = await loadExtension();
218
+ const unhandled = vi.fn();
219
+ process.on("unhandledRejection", unhandled);
220
+ try {
221
+ ext.getApiKeyForProvider.mockRejectedValue(new Error("keychain locked"));
222
+ await ext.startSession();
223
+ await settle();
224
+ expect(unhandled).not.toHaveBeenCalled();
225
+ expect(fetch).not.toHaveBeenCalled();
226
+ } finally {
227
+ process.off("unhandledRejection", unhandled);
228
+ }
229
+ });
230
+
231
+ it("backs off after a failed fetch instead of retrying in every new process", async () => {
232
+ setupHome();
233
+ writeCache(2 * HOUR);
234
+ const fetch = stubFetch(async () => new Response("unauthorized", { status: 401 }));
235
+ let ext = await loadExtension();
236
+ await ext.startSession();
237
+ await vi.waitFor(() => expect(fetch).toHaveBeenCalledOnce());
238
+ await settle();
239
+ ext = await loadExtension(); // next pi process
240
+ await ext.startSession();
241
+ await settle();
242
+ expect(fetch).toHaveBeenCalledOnce();
243
+ });
244
+
245
+ it("adopts a cache refreshed by another process without fetching", async () => {
246
+ setupHome();
247
+ writeCache(30 * 60 * 1000);
248
+ const fetch = stubFetch();
249
+ const ext = await loadExtension();
250
+ // Another pi process revalidated after this one started.
251
+ const refreshed = [...embeddedModels, { ...embeddedModels[0], id: LIVE_ONLY_ID }];
252
+ fs.writeFileSync(cachePath, JSON.stringify(refreshed));
253
+ await ext.startSession();
254
+ await vi.waitFor(() => expect(hasLiveModel(ext.registrations.at(-1))).toBe(true));
255
+ expect(fetch).not.toHaveBeenCalled();
256
+ });
257
+
258
+ it("PI_PROVIDER_SYNC_TTL_MS=0 revalidates on every session start", async () => {
259
+ setupHome();
260
+ vi.stubEnv("PI_PROVIDER_SYNC_TTL_MS", "0");
261
+ writeCache(0);
262
+ const fetch = stubFetch();
263
+ const ext = await loadExtension();
264
+ await ext.startSession();
265
+ await vi.waitFor(() => expect(fetch).toHaveBeenCalledOnce());
266
+ });
267
+ });