Skip to content

Commit dec41b6

Browse files
fix: automatically recover from corrupted auth.json (#173)
1 parent f3e8e83 commit dec41b6

2 files changed

Lines changed: 40 additions & 0 deletions

File tree

src/CodexAcpServer.ts

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -168,6 +168,23 @@ export class CodexAcpServer implements acp.Agent {
168168
}
169169

170170
async getOrCreateSession(request: acp.NewSessionRequest | acp.ResumeSessionRequest): Promise<[SessionId, SessionModelState, SessionModeState]> {
171+
try {
172+
return await this.tryCreateSession(request);
173+
} catch (e) {
174+
const error = e instanceof Error ? e : new Error(String(e));
175+
await this.handleError(error);
176+
throw e;
177+
}
178+
}
179+
180+
async handleError(e: Error){
181+
if (e.message.includes("log out")) {
182+
await this.runWithProcessCheck(() => this.codexAcpClient.logout());
183+
throw RequestError.internalError(`${(e.message)}\n\nYou have been logged out. Please try again.`);
184+
}
185+
}
186+
187+
async tryCreateSession(request: acp.NewSessionRequest | acp.ResumeSessionRequest): Promise<[SessionId, SessionModelState, SessionModeState]> {
171188
await this.checkAuthorization();
172189
const requestedMcpServers = request.mcpServers ?? [];
173190
const mcpServerStartupVersion = requestedMcpServers.length > 0
Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
import {describe, expect, it, vi} from "vitest";
2+
import {createCodexMockTestFixture} from "../acp-test-utils";
3+
4+
describe("New session logout handling", () => {
5+
it("logs out when newSession fails with an error containing log out", async () => {
6+
const fixture = createCodexMockTestFixture();
7+
const codexAcpAgent = fixture.getCodexAcpAgent();
8+
const codexAcpClient = fixture.getCodexAcpClient();
9+
const codexAppServerClient = fixture.getCodexAppServerClient();
10+
vi.spyOn(codexAcpClient, "authRequired").mockResolvedValue(false);
11+
12+
const errorMessage = `Internal error: "failed to reload config: Your access token could not be refreshed because your refresh token was already used. Please log out and sign in again."`;
13+
vi.spyOn(codexAppServerClient, "threadStart").mockRejectedValue(new Error(errorMessage));
14+
15+
const logoutSpy = vi.spyOn(codexAcpClient, "logout").mockResolvedValue();
16+
17+
await expect(codexAcpAgent.newSession({cwd: "", mcpServers: []}))
18+
.rejects.toMatchObject({
19+
data: expect.stringContaining("You have been logged out. Please try again."),
20+
});
21+
expect(logoutSpy).toHaveBeenCalledOnce();
22+
});
23+
});

0 commit comments

Comments
 (0)