Skip to content

Commit 22c42b6

Browse files
committed
fix(github-copilot): reuse existing auth profiles
1 parent d4e52f4 commit 22c42b6

4 files changed

Lines changed: 186 additions & 31 deletions

File tree

extensions/github-copilot/index.test.ts

Lines changed: 140 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -4,16 +4,20 @@ import path from "node:path";
44
import {
55
clearRuntimeAuthProfileStoreSnapshots,
66
ensureAuthProfileStore,
7+
upsertAuthProfile,
78
} from "openclaw/plugin-sdk/agent-runtime";
89
import { createTestPluginApi } from "openclaw/plugin-sdk/plugin-test-api";
910
import { afterEach, describe, expect, it, vi } from "vitest";
1011

11-
const resolveCopilotApiTokenMock = vi.hoisted(() => vi.fn());
12+
const mocks = vi.hoisted(() => ({
13+
githubCopilotLoginCommand: vi.fn(),
14+
resolveCopilotApiToken: vi.fn(),
15+
}));
1216

1317
vi.mock("./register.runtime.js", () => ({
1418
DEFAULT_COPILOT_API_BASE_URL: "https://api.githubcopilot.test",
15-
resolveCopilotApiToken: resolveCopilotApiTokenMock,
16-
githubCopilotLoginCommand: vi.fn(),
19+
resolveCopilotApiToken: mocks.resolveCopilotApiToken,
20+
githubCopilotLoginCommand: mocks.githubCopilotLoginCommand,
1721
fetchCopilotUsage: vi.fn(),
1822
}));
1923

@@ -22,6 +26,7 @@ import plugin from "./index.js";
2226
const tempDirs: string[] = [];
2327

2428
afterEach(async () => {
29+
vi.clearAllMocks();
2530
clearRuntimeAuthProfileStoreSnapshots();
2631
await Promise.all(tempDirs.splice(0).map((dir) => fs.rm(dir, { recursive: true, force: true })));
2732
});
@@ -98,11 +103,11 @@ describe("github-copilot plugin", () => {
98103
} as never);
99104

100105
expect(result).toBeNull();
101-
expect(resolveCopilotApiTokenMock).not.toHaveBeenCalled();
106+
expect(mocks.resolveCopilotApiToken).not.toHaveBeenCalled();
102107
});
103108

104109
it("uses live plugin config to re-enable discovery after startup disable", async () => {
105-
resolveCopilotApiTokenMock.mockResolvedValueOnce({
110+
mocks.resolveCopilotApiToken.mockResolvedValueOnce({
106111
token: "copilot_api_token",
107112
baseUrl: "https://api.githubcopilot.live",
108113
});
@@ -125,7 +130,7 @@ describe("github-copilot plugin", () => {
125130
resolveProviderApiKey: () => ({ apiKey: "gh_test_token" }),
126131
} as never);
127132

128-
expect(resolveCopilotApiTokenMock).toHaveBeenCalledWith({
133+
expect(mocks.resolveCopilotApiToken).toHaveBeenCalledWith({
129134
githubToken: "gh_test_token",
130135
env: { GH_TOKEN: "gh_test_token" },
131136
});
@@ -137,6 +142,135 @@ describe("github-copilot plugin", () => {
137142
});
138143
});
139144

145+
it("offers to reuse an existing token profile during interactive onboarding", async () => {
146+
const provider = registerProviderWithPluginConfig({});
147+
const method = provider.auth[0];
148+
const agentDir = await createAgentDir();
149+
await fs.writeFile(
150+
path.join(agentDir, "auth-profiles.json"),
151+
JSON.stringify({
152+
version: 1,
153+
profiles: {
154+
"github-copilot:github": {
155+
type: "token",
156+
provider: "github-copilot",
157+
token: "existing-token",
158+
},
159+
},
160+
}),
161+
);
162+
const prompter = {
163+
confirm: vi.fn(async () => false),
164+
note: vi.fn(),
165+
};
166+
167+
const result = await method.run({
168+
config: {},
169+
env: {},
170+
agentDir,
171+
workspaceDir: "/tmp/workspace",
172+
prompter,
173+
runtime: { log: vi.fn(), error: vi.fn(), exit: vi.fn() },
174+
opts: {},
175+
secretInputMode: "plaintext",
176+
allowSecretRefPrompt: false,
177+
isRemote: false,
178+
openUrl: vi.fn(),
179+
oauth: { createVpsAwareHandlers: vi.fn() },
180+
} as never);
181+
182+
expect(prompter.confirm).toHaveBeenCalledWith({
183+
message: "GitHub Copilot auth already exists. Re-run login?",
184+
initialValue: false,
185+
});
186+
expect(mocks.githubCopilotLoginCommand).not.toHaveBeenCalled();
187+
expect(result).toEqual({
188+
profiles: [
189+
{
190+
profileId: "github-copilot:github",
191+
credential: {
192+
type: "token",
193+
provider: "github-copilot",
194+
token: "existing-token",
195+
},
196+
},
197+
],
198+
defaultModel: "github-copilot/claude-opus-4.7",
199+
});
200+
});
201+
202+
it("can refresh an existing token profile during interactive onboarding", async () => {
203+
const provider = registerProviderWithPluginConfig({});
204+
const method = provider.auth[0];
205+
const agentDir = await createAgentDir();
206+
await fs.writeFile(
207+
path.join(agentDir, "auth-profiles.json"),
208+
JSON.stringify({
209+
version: 1,
210+
profiles: {
211+
"github-copilot:github": {
212+
type: "token",
213+
provider: "github-copilot",
214+
token: "existing-token",
215+
},
216+
},
217+
}),
218+
);
219+
mocks.githubCopilotLoginCommand.mockImplementationOnce(async (opts: { agentDir?: string }) => {
220+
upsertAuthProfile({
221+
profileId: "github-copilot:github",
222+
credential: {
223+
type: "token",
224+
provider: "github-copilot",
225+
token: "refreshed-token",
226+
},
227+
agentDir: opts.agentDir,
228+
});
229+
});
230+
const prompter = {
231+
confirm: vi.fn(async () => true),
232+
note: vi.fn(),
233+
};
234+
const isTtyDescriptor = Object.getOwnPropertyDescriptor(process.stdin, "isTTY");
235+
Object.defineProperty(process.stdin, "isTTY", {
236+
configurable: true,
237+
value: true,
238+
});
239+
240+
try {
241+
const result = await method.run({
242+
config: {},
243+
env: {},
244+
agentDir,
245+
workspaceDir: "/tmp/workspace",
246+
prompter,
247+
runtime: { log: vi.fn(), error: vi.fn(), exit: vi.fn() },
248+
opts: {},
249+
secretInputMode: "plaintext",
250+
allowSecretRefPrompt: false,
251+
isRemote: false,
252+
openUrl: vi.fn(),
253+
oauth: { createVpsAwareHandlers: vi.fn() },
254+
} as never);
255+
256+
expect(mocks.githubCopilotLoginCommand).toHaveBeenCalledWith(
257+
{ yes: true, profileId: "github-copilot:github", agentDir },
258+
expect.any(Object),
259+
);
260+
expect(result.profiles[0]?.credential).toEqual({
261+
type: "token",
262+
provider: "github-copilot",
263+
token: "refreshed-token",
264+
});
265+
} finally {
266+
if (isTtyDescriptor) {
267+
Object.defineProperty(process.stdin, "isTTY", isTtyDescriptor);
268+
} else {
269+
delete (process.stdin as { isTTY?: boolean }).isTTY;
270+
}
271+
}
272+
});
273+
140274
it("stores GitHub Copilot token from non-interactive onboarding", async () => {
141275
const provider = registerProviderWithPluginConfig({});
142276
const method = provider.auth[0];

extensions/github-copilot/index.ts

Lines changed: 41 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@ import { resolvePluginConfigObject } from "openclaw/plugin-sdk/plugin-config-run
33
import {
44
definePluginEntry,
55
type ProviderAuthContext,
6+
type ProviderAuthResult,
67
type ProviderAuthMethodNonInteractiveContext,
78
} from "openclaw/plugin-sdk/plugin-entry";
89
import {
@@ -86,6 +87,29 @@ function resolveExistingCopilotTokenProfileId(agentDir?: string): string | undef
8687
});
8788
}
8889

90+
function resolveExistingCopilotAuthResult(agentDir?: string): ProviderAuthResult | null {
91+
const profileId = resolveExistingCopilotTokenProfileId(agentDir);
92+
if (!profileId) {
93+
return null;
94+
}
95+
const authStore = ensureAuthProfileStore(agentDir, {
96+
allowKeychainPrompt: false,
97+
});
98+
const credential = authStore.profiles[profileId];
99+
if (!credential || credential.type !== "token") {
100+
return null;
101+
}
102+
return {
103+
profiles: [
104+
{
105+
profileId,
106+
credential,
107+
},
108+
],
109+
defaultModel: DEFAULT_COPILOT_MODEL,
110+
};
111+
}
112+
89113
async function resolveCopilotNonInteractiveToken(
90114
ctx: ProviderAuthMethodNonInteractiveContext,
91115
flagValue: string | undefined,
@@ -233,6 +257,17 @@ export default definePluginEntry({
233257

234258
async function runGitHubCopilotAuth(ctx: ProviderAuthContext) {
235259
const { githubCopilotLoginCommand } = await loadGithubCopilotRuntime();
260+
let authResult = resolveExistingCopilotAuthResult(ctx.agentDir);
261+
if (authResult) {
262+
const runLogin = await ctx.prompter.confirm({
263+
message: "GitHub Copilot auth already exists. Re-run login?",
264+
initialValue: false,
265+
});
266+
if (!runLogin) {
267+
return authResult;
268+
}
269+
}
270+
236271
await ctx.prompter.note(
237272
[
238273
"This will open a GitHub device login to authorize Copilot.",
@@ -251,31 +286,16 @@ export default definePluginEntry({
251286

252287
try {
253288
await githubCopilotLoginCommand(
254-
{ yes: true, profileId: "github-copilot:github" },
289+
{ yes: true, profileId: "github-copilot:github", agentDir: ctx.agentDir },
255290
ctx.runtime,
256291
);
257292
} catch (err) {
258293
await ctx.prompter.note(`GitHub Copilot login failed: ${String(err)}`, "GitHub Copilot");
259294
return { profiles: [] };
260295
}
261296

262-
const authStore = ensureAuthProfileStore(undefined, {
263-
allowKeychainPrompt: false,
264-
});
265-
const credential = authStore.profiles["github-copilot:github"];
266-
if (!credential || credential.type !== "token") {
267-
return { profiles: [] };
268-
}
269-
270-
return {
271-
profiles: [
272-
{
273-
profileId: DEFAULT_COPILOT_PROFILE_ID,
274-
credential,
275-
},
276-
],
277-
defaultModel: DEFAULT_COPILOT_MODEL,
278-
};
297+
authResult = resolveExistingCopilotAuthResult(ctx.agentDir);
298+
return authResult ?? { profiles: [] };
279299
}
280300

281301
api.registerMemoryEmbeddingProvider(githubCopilotMemoryEmbeddingProviderAdapter);
@@ -301,6 +321,9 @@ export default definePluginEntry({
301321
choiceLabel: "GitHub Copilot",
302322
choiceHint: "Device login with your GitHub account",
303323
methodId: "device",
324+
modelAllowlist: {
325+
loadCatalog: true,
326+
},
304327
},
305328
},
306329
catalog: {

extensions/github-copilot/login.ts

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -117,7 +117,7 @@ async function pollForAccessToken(params: {
117117
}
118118

119119
export async function githubCopilotLoginCommand(
120-
opts: { profileId?: string; yes?: boolean },
120+
opts: { profileId?: string; yes?: boolean; agentDir?: string },
121121
runtime: RuntimeEnv,
122122
) {
123123
if (!process.stdin.isTTY) {
@@ -127,7 +127,7 @@ export async function githubCopilotLoginCommand(
127127
intro(stylePromptTitle("GitHub Copilot login"));
128128

129129
const profileId = opts.profileId?.trim() || "github-copilot:github";
130-
const store = ensureAuthProfileStore(undefined, {
130+
const store = ensureAuthProfileStore(opts.agentDir, {
131131
allowKeychainPrompt: false,
132132
});
133133

@@ -169,6 +169,7 @@ export async function githubCopilotLoginCommand(
169169
// GitHub device flow token doesn't reliably include expiry here.
170170
// Leave expires unset; we'll exchange into Copilot token plus expiry later.
171171
},
172+
agentDir: opts.agentDir,
172173
});
173174

174175
await updateConfig((cfg) =>

src/plugin-sdk/test-helpers/provider-auth-contract.ts

Lines changed: 2 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -308,7 +308,7 @@ export function describeGithubCopilotProviderAuthContract(load: ProviderAuthCont
308308
return requireProvider(await registerProviders(githubCopilotPlugin), "github-copilot");
309309
}
310310

311-
it("keeps device auth results provider-owned", async () => {
311+
it("keeps existing device auth results provider-owned", async () => {
312312
const provider = await getProvider();
313313
state.authStore.profiles["github-copilot:github"] = {
314314
type: "token",
@@ -327,10 +327,7 @@ export function describeGithubCopilotProviderAuthContract(load: ProviderAuthCont
327327

328328
try {
329329
const result = await provider.auth[0]?.run(buildAuthContext() as never);
330-
expect(githubCopilotLoginCommandMock).toHaveBeenCalledWith(
331-
{ yes: true, profileId: "github-copilot:github" },
332-
expect.any(Object),
333-
);
330+
expect(githubCopilotLoginCommandMock).not.toHaveBeenCalled();
334331
expect(result).toEqual({
335332
profiles: [
336333
{

0 commit comments

Comments
 (0)