Build your personal knowledge base with Trilium Notes
TypeScript electronelectron-appknowledge-baseknowledge-graphknowledge-managementknowledge-management-graphlocal-firstnote-managmentnote-takernote-takingnotebooknotesnotes-apppersonal-knowledge-basepersonal-wikiscriptableself-hostedself-hostingwiki
fix(llm): wait for Codex's account to show a completed ChatGPT sign-in
Elian Doranfbe726556b9c
diff --git a/apps/server/src/services/llm/providers/codex_agent.spec.ts b/apps/server/src/services/llm/providers/codex_agent.spec.tsindex 2b9d2c2a31..e0418b19e4 100644--- a/apps/server/src/services/llm/providers/codex_agent.spec.ts+++ b/apps/server/src/services/llm/providers/codex_agent.spec.ts@@ -52,6 +52,9 @@ class FakeAcpClient {static current: FakeAcpClient | undefined;static lastStart: { worker: boolean; binary: string; opts: { args?: string[]; env?: Record<string, string>; cwd: string } } | undefined;static signedIn = true;+ /** How many `session/new` calls after `authenticate` still find no account, as Codex's can lag a completed sign-in. */+ static accountLag = 0;+ static lagLeft = 0;/** An error `session/new` fails with, when set. */static sessionFailure: Error | undefined;/** Runs while session/prompt is answered, as the agent's own notifications and requests do. */@@ -81,10 +84,11 @@ class FakeAcpClient {this.requests.push({ method, params });if (method === "authenticate") {FakeAcpClient.signedIn = true;+ FakeAcpClient.lagLeft = FakeAcpClient.accountLag;}if (method === "session/new") {if (FakeAcpClient.sessionFailure) throw FakeAcpClient.sessionFailure;- if (!FakeAcpClient.signedIn) throw new FakeAcpError(-32000, "Authentication required");+ if (!FakeAcpClient.signedIn || FakeAcpClient.lagLeft-- > 0) throw new FakeAcpError(-32000, "Authentication required");return { sessionId: "sess-1", models: { currentModelId: "gpt-6-luna[medium]", availableModels: REMOTE_MODELS } } as T;}if (method === "session/prompt") {@@ -142,6 +146,8 @@ beforeEach(() => {FakeAcpClient.current = undefined;FakeAcpClient.lastStart = undefined;FakeAcpClient.signedIn = true;+ FakeAcpClient.accountLag = 0;+ FakeAcpClient.lagLeft = 0;FakeAcpClient.sessionFailure = undefined;FakeAcpClient.onPrompt = undefined;});@@ -184,6 +190,28 @@ describe("CodexAgentProvider", () => {expect(FakeAcpClient.current?.requests[2].params).toEqual({ methodId: "chat-gpt" });});+ it("waits for Codex's account to show a sign-in it reported complete, for a while", async () => {+ vi.useFakeTimers();+ try {+ FakeAcpClient.signedIn = false;+ FakeAcpClient.accountLag = 2;+ const listing = new CodexAgentProvider().listModels();+ await vi.advanceTimersByTimeAsync(2_000);+ expect((await listing).map(m => m.id)).toContain("gpt-6-luna");+ expect(FakeAcpClient.current?.methods()).toEqual(["initialize", "session/new", "authenticate", "session/new", "session/new", "session/new"]);++ // An account that never shows the sign-in is reported after ten seconds.+ resetAcpAgentStateForTests();+ FakeAcpClient.signedIn = false;+ FakeAcpClient.accountLag = Infinity;+ const failing = new CodexAgentProvider().listModels().then(() => "resolved", (err: Error) => err.message);+ await vi.advanceTimersByTimeAsync(11_000);+ expect(await failing).toMatch(/not signed in/);+ } finally {+ vi.useRealTimers();+ }+ });+it("explains a failure to start, sign in or answer in words the user can act on", async () => {const failureOf = async (error: Error) => {FakeAcpClient.sessionFailure = error;diff --git a/apps/server/src/services/llm/providers/codex_agent.ts b/apps/server/src/services/llm/providers/codex_agent.tsindex 7b20bc25c7..6da52d75a8 100644--- a/apps/server/src/services/llm/providers/codex_agent.ts+++ b/apps/server/src/services/llm/providers/codex_agent.ts@@ -45,6 +45,10 @@ const SIGN_IN_METHOD = "chat-gpt";/** How long the add-provider screen waits for the user to finish signing in in the browser. */export const SIGN_IN_TIMEOUT_MS = 5 * 60_000;+/** How long after a sign-in `session/new` is retried while Codex's account does not show it yet, and how often. */+const SIGN_IN_SETTLE_MS = 10_000;+const SIGN_IN_RETRY_MS = 500;+/*** The settings the adapter merges into every session, as `CODEX_CONFIG`.* Codex runs a hook only once the user has trusted it, which no one can do in@@ -173,6 +177,10 @@ export class CodexAgentProvider extends AcpAgentProvider {* ChatGPT sign-in page in a browser on the device running Trilium and* answers `authenticate` once the user has finished there; it keeps the* sign-in under `CODEX_HOME`, so later sessions need none.+ *+ * Codex reports the sign-in complete before its account shows it, so the+ * first `session/new` after it can still find no account; it is retried+ * for a few seconds.*/protected async createSession(client: AcpClient, params: AcpNewSessionParams, interactive: boolean, timeoutMs: number) {let created: Awaited<ReturnType<AcpAgentProvider["createSession"]>>;@@ -183,7 +191,7 @@ export class CodexAgentProvider extends AcpAgentProvider {throw err;}await client.request("authenticate", { methodId: SIGN_IN_METHOD }, SIGN_IN_TIMEOUT_MS);- created = await super.createSession(client, params, interactive, timeoutMs);+ created = await this.createSessionAfterSignIn(client, params, timeoutMs);}if (created.models) {recordCatalog(created.models);@@ -191,6 +199,21 @@ export class CodexAgentProvider extends AcpAgentProvider {return created;}+ /** `session/new` once a sign-in has completed, retried while Codex's account does not show it yet. */+ private async createSessionAfterSignIn(client: AcpClient, params: AcpNewSessionParams, timeoutMs: number) {+ const giveUpAt = Date.now() + SIGN_IN_SETTLE_MS;+ for (;;) {+ try {+ return await super.createSession(client, params, true, timeoutMs);+ } catch (err) {+ if (!isSignInRequired(err) || Date.now() >= giveUpAt) {+ throw err;+ }+ await new Promise(resolve => setTimeout(resolve, SIGN_IN_RETRY_MS));+ }+ }+ }+/** The turn, with the citation markers Codex writes into its reply taken out (see {@link CitationStripper}). */async *chatChunks(messages: LlmMessage[], config: LlmProviderConfig, signal?: AbortSignal): AsyncIterable<LlmStreamChunk> {const citations = new CitationStripper();