Skip to content

Commit c801579

Browse files
authored
fix(onboard): keep provider credentials with named first agents (#127572)
* fix(onboard): keep provider credentials with named first agents * fix(onboard): preserve workspace in provider choice normalization
1 parent 9903e40 commit c801579

12 files changed

Lines changed: 301 additions & 42 deletions

‎src/commands/auth-choice.apply.api-providers.test.ts‎

Lines changed: 111 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,17 +1,35 @@
11
// API-provider auth-choice tests cover built-in provider config, API keys, and provider plugin setup.
22
import { afterEach, describe, expect, it, vi } from "vitest";
3+
import * as providerAuthChoices from "../plugins/provider-auth-choices.js";
34
import type { ProviderPlugin } from "../plugins/types.js";
45
import { normalizeApiKeyTokenProviderAuthChoice } from "./auth-choice.apply.api-providers.js";
6+
import { prepareAuthChoice } from "./auth-choice.apply.js";
57

68
const resolvePluginProviders = vi.hoisted(() =>
79
vi.fn<typeof import("../plugins/provider-auth-choice.runtime.js").resolvePluginProviders>(),
810
);
911
const resolvePluginSetupProvider = vi.hoisted(() => vi.fn(() => undefined));
12+
const prepareAuthChoiceLoadedPluginProvider = vi.hoisted(() =>
13+
vi.fn<
14+
typeof import("../plugins/provider-auth-choice.js").prepareAuthChoiceLoadedPluginProvider
15+
>(),
16+
);
17+
const resolveDeprecatedProviderInstallCatalogEntry = vi.hoisted(() =>
18+
vi.fn<
19+
typeof import("../plugins/provider-install-catalog.js").resolveDeprecatedProviderInstallCatalogEntry
20+
>(),
21+
);
1022

1123
vi.mock("../plugins/provider-auth-choice.runtime.js", () => ({
1224
resolvePluginProviders,
1325
resolvePluginSetupProvider,
1426
}));
27+
vi.mock("../plugins/provider-auth-choice.js", () => ({
28+
prepareAuthChoiceLoadedPluginProvider,
29+
}));
30+
vi.mock("../plugins/provider-install-catalog.js", () => ({
31+
resolveDeprecatedProviderInstallCatalogEntry,
32+
}));
1533

1634
function createProvider(params: {
1735
id: string;
@@ -39,6 +57,9 @@ function createProvider(params: {
3957
describe("normalizeApiKeyTokenProviderAuthChoice", () => {
4058
afterEach(() => {
4159
resolvePluginProviders.mockReset();
60+
prepareAuthChoiceLoadedPluginProvider.mockReset();
61+
resolveDeprecatedProviderInstallCatalogEntry.mockReset();
62+
vi.restoreAllMocks();
4263
});
4364

4465
it("maps token provider auth through plugin token methods", () => {
@@ -89,4 +110,94 @@ describe("normalizeApiKeyTokenProviderAuthChoice", () => {
89110
}),
90111
).toBe("token");
91112
});
113+
114+
it.each([
115+
{ authChoice: "apiKey", kind: "api_key" },
116+
{ authChoice: "token", kind: "token" },
117+
{ authChoice: "setup-token", kind: "token" },
118+
] as const)(
119+
"resolves workspace-only $authChoice providers through interactive setup",
120+
async (choice) => {
121+
const workspaceDir = "/tmp/selected-agent-workspace";
122+
const provider = createProvider({
123+
id: "workspace-provider",
124+
auth: [{ id: "workspace-auth", kind: choice.kind, choiceId: "workspace-provider-auth" }],
125+
});
126+
resolvePluginProviders.mockImplementation((params) =>
127+
params?.workspaceDir === workspaceDir ? [provider] : [],
128+
);
129+
prepareAuthChoiceLoadedPluginProvider.mockImplementation(async (params) =>
130+
params.authChoice === "workspace-provider-auth"
131+
? {
132+
config: params.config,
133+
authProfiles: [
134+
{
135+
profileId: "workspace-provider:default",
136+
credential: {
137+
type: "api_key",
138+
provider: "workspace-provider",
139+
key: "fixture-workspace-key",
140+
},
141+
},
142+
],
143+
persistAuthProfiles: async () => {},
144+
}
145+
: null,
146+
);
147+
148+
const prepared = await prepareAuthChoice({
149+
authChoice: choice.authChoice,
150+
config: {},
151+
workspaceDir,
152+
prompter: {} as never,
153+
runtime: {} as never,
154+
setDefaultModel: false,
155+
opts: { tokenProvider: provider.id },
156+
});
157+
158+
expect(prepared.authProfiles).toEqual([
159+
{
160+
profileId: "workspace-provider:default",
161+
credential: {
162+
type: "api_key",
163+
provider: "workspace-provider",
164+
key: "fixture-workspace-key",
165+
},
166+
},
167+
]);
168+
},
169+
);
170+
171+
it.each(["manifest", "install catalog"] as const)(
172+
"resolves workspace-only deprecated auth choices from the %s",
173+
async (source) => {
174+
const workspaceDir = "/tmp/selected-agent-workspace";
175+
vi.spyOn(
176+
providerAuthChoices,
177+
"resolveManifestDeprecatedProviderAuthChoice",
178+
).mockImplementation((_choice, params) =>
179+
source === "manifest" && params?.workspaceDir === workspaceDir
180+
? ({ choiceId: "workspace-modern-auth" } as never)
181+
: undefined,
182+
);
183+
resolveDeprecatedProviderInstallCatalogEntry.mockImplementation((_choice, params) =>
184+
source === "install catalog" &&
185+
params?.workspaceDir === workspaceDir &&
186+
params.includeUntrustedWorkspacePlugins === false
187+
? ({ choiceId: "workspace-modern-auth" } as never)
188+
: undefined,
189+
);
190+
191+
await expect(
192+
prepareAuthChoice({
193+
authChoice: "workspace-legacy-auth",
194+
config: {},
195+
workspaceDir,
196+
prompter: {} as never,
197+
runtime: {} as never,
198+
setDefaultModel: false,
199+
}),
200+
).rejects.toThrow('Use "workspace-modern-auth" instead');
201+
},
202+
);
92203
});

‎src/commands/auth-choice.apply.ts‎

Lines changed: 7 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,7 @@ import type { AuthChoice } from "./onboard-types.js";
1010

1111
async function normalizeLegacyChoice(
1212
authChoice: AuthChoice | undefined,
13-
params: Pick<ApplyAuthChoiceParams, "config" | "env">,
13+
params: Pick<ApplyAuthChoiceParams, "config" | "env" | "workspaceDir">,
1414
): Promise<AuthChoice | undefined> {
1515
if (authChoice === "oauth") {
1616
return "setup-token";
@@ -42,31 +42,28 @@ async function normalizeTokenProviderChoice(params: {
4242
authChoice: params.authChoice,
4343
tokenProvider: params.source.opts.tokenProvider,
4444
config: params.source.config,
45+
workspaceDir: params.source.workspaceDir,
4546
env: params.source.env,
4647
});
4748
}
4849

4950
async function formatDeprecatedProviderChoiceError(
5051
authChoice: AuthChoice | undefined,
51-
params: Pick<ApplyAuthChoiceParams, "config" | "env">,
52+
params: Pick<ApplyAuthChoiceParams, "config" | "env" | "workspaceDir">,
5253
): Promise<string | undefined> {
5354
if (typeof authChoice !== "string") {
5455
return undefined;
5556
}
5657
const { resolveManifestDeprecatedProviderAuthChoice } =
5758
await import("../plugins/provider-auth-choices.js");
58-
const deprecatedChoice = resolveManifestDeprecatedProviderAuthChoice(authChoice, {
59-
config: params.config,
60-
env: params.env,
61-
});
59+
const deprecatedChoice = resolveManifestDeprecatedProviderAuthChoice(authChoice, params);
6260
if (deprecatedChoice) {
6361
return `Auth choice ${JSON.stringify(authChoice)} is no longer supported. Use ${JSON.stringify(deprecatedChoice.choiceId)} instead, or run ${formatCliCommand("openclaw onboard")} to choose interactively.`;
6462
}
6563
const { resolveDeprecatedProviderInstallCatalogEntry } =
6664
await import("../plugins/provider-install-catalog.js");
6765
const externalDeprecatedChoice = resolveDeprecatedProviderInstallCatalogEntry(authChoice, {
68-
config: params.config,
69-
env: params.env,
66+
...params,
7067
includeUntrustedWorkspacePlugins: false,
7168
});
7269
if (!externalDeprecatedChoice) {
@@ -80,10 +77,7 @@ export async function prepareAuthChoice(
8077
params: ApplyAuthChoiceParams,
8178
): Promise<PreparedAuthChoiceResult> {
8279
const normalizedAuthChoice =
83-
(await normalizeLegacyChoice(params.authChoice, {
84-
config: params.config,
85-
env: params.env,
86-
})) ?? params.authChoice;
80+
(await normalizeLegacyChoice(params.authChoice, params)) ?? params.authChoice;
8781
const normalizedProviderAuthChoice = await normalizeTokenProviderChoice({
8882
authChoice: normalizedAuthChoice,
8983
source: params,
@@ -99,10 +93,7 @@ export async function prepareAuthChoice(
9993

10094
const deprecatedProviderChoiceError = await formatDeprecatedProviderChoiceError(
10195
normalizedParams.authChoice,
102-
{
103-
config: normalizedParams.config,
104-
env: normalizedParams.env,
105-
},
96+
normalizedParams,
10697
);
10798
if (deprecatedProviderChoiceError) {
10899
throw new Error(deprecatedProviderChoiceError);

‎src/commands/auth-choice.apply.types.ts‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,7 @@ export type ApplyAuthChoiceParams = {
1212
prompter: WizardPrompter;
1313
runtime: RuntimeEnv;
1414
agentDir?: string;
15+
workspaceDir?: string;
1516
setDefaultModel: boolean;
1617
preserveExistingDefaultModel?: boolean;
1718
agentId?: string;

‎src/commands/onboard-agent-target.test.ts‎

Lines changed: 55 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -78,22 +78,71 @@ describe("onboarding agent target", () => {
7878
main: { workspace: "/srv/main" },
7979
ops: { default: true, workspace: "/srv/ops" },
8080
};
81+
const pendingAgent = { name: "robby", workspaceDir: "/srv/robby" };
8182

8283
expect(
83-
resolveOnboardingSetupTarget({
84-
agents: {
85-
ownership: "explicit",
86-
defaults: { systemAgent: { agentId: "main" } },
87-
entries,
84+
resolveOnboardingSetupTarget(
85+
{
86+
agents: {
87+
ownership: "explicit",
88+
defaults: { systemAgent: { agentId: "main" } },
89+
entries,
90+
},
8891
},
89-
}),
92+
pendingAgent,
93+
),
9094
).toMatchObject({ agentId: "main", workspaceDir: "/srv/main" });
95+
expect(
96+
resolveOnboardingSetupTarget(
97+
{
98+
agents: {
99+
ownership: "explicit",
100+
defaults: { systemAgent: { agentId: "main" } },
101+
entries: { main: { default: true } },
102+
},
103+
},
104+
pendingAgent,
105+
),
106+
).toMatchObject({ agentId: "main" });
91107
expect(resolveOnboardingSetupTarget({ agents: { entries } })).toMatchObject({
92108
agentId: "ops",
93109
workspaceDir: "/srv/ops",
94110
});
95111
});
96112

113+
it("resolves a pending first agent without nesting the selected workspace", async () => {
114+
const stateDir = tempDirs.make("openclaw-pending-onboard-target-");
115+
const workspaceDir = path.join(stateDir, "requested-workspace");
116+
117+
await withEnvAsync({ OPENCLAW_STATE_DIR: stateDir }, async () => {
118+
for (const entries of [undefined, { main: {} }, { main: { default: true } }] as const) {
119+
const config = {
120+
agents: { defaults: { workspace: workspaceDir }, ...(entries ? { entries } : {}) },
121+
};
122+
123+
expect(resolveOnboardingSetupTarget(config, { name: " Robby! ", workspaceDir })).toEqual({
124+
agentId: "robby",
125+
agentDir: path.join(stateDir, "agents", "robby", "agent"),
126+
workspaceDir,
127+
});
128+
expect(resolveOnboardingSetupTarget(config)).toMatchObject({
129+
agentId: "main",
130+
workspaceDir,
131+
});
132+
}
133+
expect(
134+
resolveOnboardingSetupTarget({
135+
agents: {
136+
entries: { main: { default: true, name: "Authored main", workspace: "/srv/main" } },
137+
},
138+
}),
139+
).toMatchObject({ agentId: "main", workspaceDir: "/srv/main" });
140+
expect(
141+
resolveOnboardingSetupTarget({ agents: { entries: { main: { default: false } } } }),
142+
).toMatchObject({ agentId: "main" });
143+
});
144+
});
145+
97146
it("keeps explicit agent model mutations on the system-agent entry", () => {
98147
const config = {
99148
agents: {

‎src/commands/onboard-agent-target.ts‎

Lines changed: 15 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -48,11 +48,21 @@ export function resolveSystemAgentOnboardingTarget(config: OpenClawConfig): Onbo
4848
return resolveOnboardingAgentTarget(config, config.agents?.defaults?.systemAgent?.agentId);
4949
}
5050

51-
/** Resolve onboarding setup to the system agent only for explicitly owned fleets. */
52-
export function resolveOnboardingSetupTarget(config: OpenClawConfig): OnboardingAgentTarget {
53-
return config.agents?.ownership === "explicit"
54-
? resolveSystemAgentOnboardingTarget(config)
55-
: resolveOnboardingAgentTarget(config);
51+
/** Resolve onboarding setup to its existing or pending first-agent owner. */
52+
export function resolveOnboardingSetupTarget(
53+
config: OpenClawConfig,
54+
pendingAgent?: { name: string; workspaceDir: string },
55+
): OnboardingAgentTarget {
56+
if (config.agents?.ownership === "explicit") {
57+
return resolveSystemAgentOnboardingTarget(config);
58+
}
59+
if (pendingAgent) {
60+
return {
61+
...resolveOnboardingAgentTarget(config, pendingAgent.name),
62+
workspaceDir: pendingAgent.workspaceDir,
63+
};
64+
}
65+
return resolveOnboardingAgentTarget(config);
5666
}
5767

5868
export async function ensureOnboardingAgentWorkspace(

‎src/commands/onboard-non-interactive/local.default-agent.test.ts‎

Lines changed: 24 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -198,7 +198,6 @@ describe("runNonInteractiveLocalSetup default-agent ownership", () => {
198198
robby: {
199199
name: "robby",
200200
workspace,
201-
agentDir: "/tmp/robby-agent",
202201
},
203202
},
204203
},
@@ -215,7 +214,7 @@ describe("runNonInteractiveLocalSetup default-agent ownership", () => {
215214
mode: "local",
216215
agentName: "robby",
217216
workspace,
218-
authChoice: "skip",
217+
authChoice: "demo-api-key",
219218
skipHooks: true,
220219
skipSkills: true,
221220
skipHealth: true,
@@ -225,6 +224,18 @@ describe("runNonInteractiveLocalSetup default-agent ownership", () => {
225224
baseConfig: {},
226225
});
227226

227+
expect(mocks.applyAuthChoice).toHaveBeenCalledWith(
228+
expect.objectContaining({
229+
target: expect.objectContaining({
230+
agentId: "robby",
231+
agentDir: expect.stringMatching(/[/\\]agents[/\\]robby[/\\]agent$/),
232+
workspaceDir: workspace,
233+
}),
234+
}),
235+
);
236+
expect(mocks.applyAuthChoice.mock.invocationCallOrder[0]).toBeLessThan(
237+
mocks.ensureOnboardingAgent.mock.invocationCallOrder[0]!,
238+
);
228239
expect(mocks.ensureOnboardingAgent).toHaveBeenCalledOnce();
229240
expect(mocks.ensureOnboardingAgent).toHaveBeenCalledWith(
230241
expect.objectContaining({ firstAgent: { name: "robby" } }),
@@ -306,8 +317,9 @@ describe("runNonInteractiveLocalSetup default-agent ownership", () => {
306317
opts: {
307318
nonInteractive: true,
308319
mode: "local",
320+
agentName: "robby",
309321
workspace: "/tmp/global-workspace",
310-
authChoice: "skip",
322+
authChoice: "demo-api-key",
311323
skipHooks: true,
312324
skipSkills: true,
313325
skipHealth: true,
@@ -318,6 +330,15 @@ describe("runNonInteractiveLocalSetup default-agent ownership", () => {
318330
baseConfig,
319331
});
320332

333+
expect(mocks.applyAuthChoice).toHaveBeenCalledWith(
334+
expect.objectContaining({
335+
target: expect.objectContaining({
336+
agentId: "ops",
337+
agentDir: "/tmp/ops-agent",
338+
workspaceDir: "/tmp/ops-workspace",
339+
}),
340+
}),
341+
);
321342
expect(mocks.commitConfig).toHaveBeenCalledWith(
322343
expect.objectContaining({
323344
nextConfig: expect.objectContaining({

0 commit comments

Comments
 (0)