fix: refresh Qoder models before startup
This commit is contained in:
@@ -1,5 +1,12 @@
|
||||
import { existsSync, readFileSync, rmSync, writeFileSync } from "node:fs";
|
||||
import { homedir } from "node:os";
|
||||
import { join } from "node:path";
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import { updateQoderModelsCache } from "../models.js";
|
||||
import { autoLoginQoderFromEnvironment, getCachedCredentials, getQoderPatForMode } from "../oauth.js";
|
||||
import { credentialsFromPat } from "../pat.js";
|
||||
|
||||
const AUTH_FILE = join(homedir(), ".pi", "agent", "auth.json");
|
||||
|
||||
vi.mock("../pat.js", () => ({
|
||||
credentialsFromPat: vi.fn().mockResolvedValue({
|
||||
@@ -26,14 +33,18 @@ vi.mock("../models.js", () => ({
|
||||
|
||||
describe("oauth autoLoginQoderFromEnvironment", () => {
|
||||
const originalEnv = process.env;
|
||||
let originalAuth: string | undefined;
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
process.env = { ...originalEnv };
|
||||
originalAuth = existsSync(AUTH_FILE) ? readFileSync(AUTH_FILE, "utf8") : undefined;
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
process.env = originalEnv;
|
||||
if (originalAuth === undefined) rmSync(AUTH_FILE, { force: true });
|
||||
else writeFileSync(AUTH_FILE, originalAuth, "utf8");
|
||||
});
|
||||
|
||||
it("extracts PAT correctly from env for global and CN mode", () => {
|
||||
@@ -52,4 +63,28 @@ describe("oauth autoLoginQoderFromEnvironment", () => {
|
||||
await autoLoginQoderFromEnvironment("qoder-test-provider", "global");
|
||||
expect(getCachedCredentials("mock-token", "qoder-test-provider")).toBeNull();
|
||||
});
|
||||
|
||||
it("re-exchanges an environment PAT even when cached credentials exist", async () => {
|
||||
process.env.QODER_PERSONAL_ACCESS_TOKEN = "pt-global-new-account";
|
||||
const auth = existsSync(AUTH_FILE) ? JSON.parse(readFileSync(AUTH_FILE, "utf8")) : {};
|
||||
auth["qoder-test-provider"] = {
|
||||
type: "oauth",
|
||||
access: "old-access-token",
|
||||
refresh: "old-refresh-token",
|
||||
expires: Date.now() + 3600000,
|
||||
userID: "old-user",
|
||||
};
|
||||
writeFileSync(AUTH_FILE, JSON.stringify(auth), "utf8");
|
||||
|
||||
await autoLoginQoderFromEnvironment("qoder-test-provider", "global");
|
||||
|
||||
expect(credentialsFromPat).toHaveBeenCalledWith("pt-global-new-account", "global");
|
||||
expect(updateQoderModelsCache).toHaveBeenCalledWith(
|
||||
"mock-access-token",
|
||||
"mock-user-123",
|
||||
"Test User",
|
||||
"test@example.com",
|
||||
"global",
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -64,6 +64,21 @@ function registerQoderProvider(pi: ExtensionAPI, providerID: string, mode: strin
|
||||
});
|
||||
}
|
||||
|
||||
async function refreshModelsAtStartup(providerID: string, mode: string): Promise<void> {
|
||||
if (!isCacheStale(mode)) return;
|
||||
|
||||
const credentials = getCachedCredentials("", providerID);
|
||||
if (!credentials?.access) return;
|
||||
|
||||
await updateQoderModelsCache(
|
||||
credentials.access,
|
||||
credentials.userID || "qoder-user",
|
||||
credentials.name || (isQoderCNMode(mode) ? "Qoder CN User" : "Qoder User"),
|
||||
credentials.email || getQoderUserEmailFallback(mode),
|
||||
mode,
|
||||
);
|
||||
}
|
||||
|
||||
export default async function (pi: ExtensionAPI) {
|
||||
for (const [providerID, mode] of [
|
||||
["qoder", getQoderMode()],
|
||||
@@ -71,6 +86,7 @@ export default async function (pi: ExtensionAPI) {
|
||||
] as const) {
|
||||
try {
|
||||
await autoLoginQoderFromEnvironment(providerID, mode);
|
||||
await refreshModelsAtStartup(providerID, mode);
|
||||
} catch (error) {
|
||||
const message = error instanceof Error ? error.message : String(error);
|
||||
console.error(`[pi-provider-qoder] Automatic login failed for ${providerID}: ${message}`);
|
||||
|
||||
+7
-3
@@ -49,8 +49,10 @@ export async function autoLoginQoderFromEnvironment(providerID: string, mode: st
|
||||
const pat = getQoderPatForMode(mode);
|
||||
if (!pat) return;
|
||||
|
||||
if (getCachedCredentials("", providerID)) return;
|
||||
|
||||
// An explicitly supplied PAT is authoritative. The auth file only stores
|
||||
// the exchanged job token, so it cannot tell us whether the environment
|
||||
// token changed. Re-exchange it on startup to avoid silently using an old
|
||||
// account's credentials.
|
||||
const credentials = await credentialsFromPat(pat, mode);
|
||||
|
||||
if (typeof AuthStorage !== "undefined" && typeof AuthStorage?.create === "function") {
|
||||
@@ -65,7 +67,9 @@ export async function autoLoginQoderFromEnvironment(providerID: string, mode: st
|
||||
}
|
||||
|
||||
const qCreds = credentials as QoderCredentials;
|
||||
updateQoderModelsCache(qCreds.access, qCreds.userID, qCreds.name, qCreds.email, mode).catch(() => {});
|
||||
// Wait for the model cache before the provider is registered. This matters
|
||||
// for `pi --list-models`, which can exit before background work completes.
|
||||
await updateQoderModelsCache(qCreds.access, qCreds.userID, qCreds.name, qCreds.email, mode);
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
Reference in New Issue
Block a user