chore: default to org agent when onboarding (#7793)
* chore: default to org agent when onboarding * tests * remove console logs
This commit is contained in:
parent
059c901bdb
commit
39efd1e562
8 changed files with 412 additions and 67 deletions
233
extensions/cli/src/auth/orgSelection.test.ts
Normal file
233
extensions/cli/src/auth/orgSelection.test.ts
Normal file
|
|
@ -0,0 +1,233 @@
|
|||
import * as fs from "fs";
|
||||
|
||||
import { beforeEach, describe, expect, it, vi } from "vitest";
|
||||
|
||||
import {
|
||||
autoSelectOrganizationAndConfig,
|
||||
createUpdatedAuthConfig,
|
||||
} from "./orgSelection.js";
|
||||
import type { AuthenticatedConfig } from "./workos.js";
|
||||
|
||||
// Mock dependencies
|
||||
vi.mock("fs");
|
||||
vi.mock("../config.js");
|
||||
vi.mock("../env.js");
|
||||
vi.mock("./workos.js");
|
||||
|
||||
const mockApiClient = {
|
||||
listOrganizations: vi.fn(),
|
||||
listAssistants: vi.fn(),
|
||||
} as any; // Mock API client for testing
|
||||
|
||||
describe("orgSelection", () => {
|
||||
const mockConfig: AuthenticatedConfig = {
|
||||
userId: "user123",
|
||||
userEmail: "user@example.com",
|
||||
accessToken: "token123",
|
||||
refreshToken: "refresh123",
|
||||
expiresAt: Date.now() + 3600000,
|
||||
organizationId: undefined,
|
||||
configUri: undefined,
|
||||
modelName: undefined,
|
||||
};
|
||||
|
||||
beforeEach(async () => {
|
||||
vi.clearAllMocks();
|
||||
|
||||
// Mock modules using vi.mocked
|
||||
const configMod = await import("../config.js");
|
||||
const envMod = await import("../env.js");
|
||||
const workosMod = await import("./workos.js");
|
||||
|
||||
vi.mocked(configMod.getApiClient).mockReturnValue(mockApiClient);
|
||||
vi.mocked(envMod.env).continueHome = "/mock/home";
|
||||
vi.mocked(workosMod.saveAuthConfig).mockImplementation(() => {});
|
||||
|
||||
// Default: no local config
|
||||
vi.mocked(fs.existsSync).mockReturnValue(false);
|
||||
});
|
||||
|
||||
describe("createUpdatedAuthConfig", () => {
|
||||
it("should update organization ID", () => {
|
||||
const result = createUpdatedAuthConfig(mockConfig, "org123");
|
||||
expect(result.organizationId).toBe("org123");
|
||||
});
|
||||
|
||||
it("should update organization ID and config URI", () => {
|
||||
const result = createUpdatedAuthConfig(
|
||||
mockConfig,
|
||||
"org123",
|
||||
"slug://owner/assistant",
|
||||
);
|
||||
expect(result.organizationId).toBe("org123");
|
||||
expect(result!.configUri).toBe("slug://owner/assistant");
|
||||
});
|
||||
|
||||
it("should set personal organization", () => {
|
||||
const result = createUpdatedAuthConfig(mockConfig, null);
|
||||
expect(result.organizationId).toBe(null);
|
||||
});
|
||||
});
|
||||
|
||||
describe("autoSelectOrganizationAndConfig scenarios", () => {
|
||||
it("Priority 1: Org with assistants → select first assistant", async () => {
|
||||
mockApiClient.listOrganizations.mockResolvedValue({
|
||||
organizations: [
|
||||
{ id: "org1", name: "Org 1" },
|
||||
{ id: "org2", name: "Org 2" },
|
||||
],
|
||||
});
|
||||
|
||||
// Mock API calls in order: org1 assistants, org2 assistants
|
||||
mockApiClient.listAssistants.mockImplementation(
|
||||
({ organizationId }: { organizationId?: string }) => {
|
||||
if (organizationId === "org1") return Promise.resolve([]);
|
||||
if (organizationId === "org2")
|
||||
return Promise.resolve([
|
||||
{ ownerSlug: "owner", packageSlug: "assistant1" },
|
||||
]);
|
||||
return Promise.resolve([]);
|
||||
},
|
||||
);
|
||||
|
||||
const result = await autoSelectOrganizationAndConfig(mockConfig);
|
||||
|
||||
expect(result!.organizationId).toBe("org2");
|
||||
expect(result!.configUri).toBe("slug://owner/assistant1");
|
||||
});
|
||||
|
||||
it("Priority 2: No org assistants → personal assistants exist", async () => {
|
||||
mockApiClient.listOrganizations.mockResolvedValue({
|
||||
organizations: [{ id: "org1", name: "Org 1" }],
|
||||
});
|
||||
|
||||
mockApiClient.listAssistants.mockImplementation(
|
||||
({ organizationId }: { organizationId?: string }) => {
|
||||
if (organizationId === "org1") return Promise.resolve([]);
|
||||
if (organizationId === undefined)
|
||||
return Promise.resolve([
|
||||
{ ownerSlug: "personal", packageSlug: "my-assistant" },
|
||||
]);
|
||||
return Promise.resolve([]);
|
||||
},
|
||||
);
|
||||
|
||||
const result = await autoSelectOrganizationAndConfig(mockConfig);
|
||||
|
||||
expect(result!.organizationId).toBe(null); // personal org
|
||||
expect(result!.configUri).toBe("slug://personal/my-assistant");
|
||||
expect(mockApiClient.listAssistants).toHaveBeenCalledWith({
|
||||
organizationId: undefined,
|
||||
});
|
||||
});
|
||||
|
||||
it("Priority 3: No assistants anywhere → local config.yaml exists", async () => {
|
||||
mockApiClient.listOrganizations.mockResolvedValue({
|
||||
organizations: [{ id: "org1", name: "Org 1" }],
|
||||
});
|
||||
|
||||
mockApiClient.listAssistants.mockResolvedValue([]); // No assistants anywhere
|
||||
vi.mocked(fs.existsSync).mockReturnValue(true); // config.yaml exists
|
||||
|
||||
const result = await autoSelectOrganizationAndConfig(mockConfig);
|
||||
|
||||
expect(result!.organizationId).toBe(null);
|
||||
expect(result!.configUri).toContain("config.yaml");
|
||||
});
|
||||
|
||||
it("Priority 4: No assistants, no config.yaml → fallback", async () => {
|
||||
mockApiClient.listOrganizations.mockResolvedValue({
|
||||
organizations: [{ id: "org1", name: "Org 1" }],
|
||||
});
|
||||
|
||||
mockApiClient.listAssistants.mockResolvedValue([]); // No assistants anywhere
|
||||
vi.mocked(fs.existsSync).mockReturnValue(false); // No config.yaml
|
||||
|
||||
const result = await autoSelectOrganizationAndConfig(mockConfig);
|
||||
|
||||
expect(result!.organizationId).toBe(null);
|
||||
expect(result!.configUri).toBeUndefined();
|
||||
});
|
||||
|
||||
it("Multiple orgs with assistants → pick first one", async () => {
|
||||
mockApiClient.listOrganizations.mockResolvedValue({
|
||||
organizations: [
|
||||
{ id: "org1", name: "Org 1" },
|
||||
{ id: "org2", name: "Org 2" },
|
||||
],
|
||||
});
|
||||
|
||||
mockApiClient.listAssistants.mockImplementation(
|
||||
({ organizationId }: { organizationId?: string }) => {
|
||||
if (organizationId === "org1")
|
||||
return Promise.resolve([
|
||||
{ ownerSlug: "owner1", packageSlug: "assistant1" },
|
||||
]);
|
||||
if (organizationId === "org2")
|
||||
return Promise.resolve([
|
||||
{ ownerSlug: "owner2", packageSlug: "assistant2" },
|
||||
]);
|
||||
return Promise.resolve([]);
|
||||
},
|
||||
);
|
||||
|
||||
const result = await autoSelectOrganizationAndConfig(mockConfig);
|
||||
|
||||
expect(result!.organizationId).toBe("org1"); // First org wins
|
||||
expect(result!.configUri).toBe("slug://owner1/assistant1");
|
||||
});
|
||||
|
||||
it("Personal assistants API fails → fallback to config.yaml", async () => {
|
||||
mockApiClient.listOrganizations.mockResolvedValue({
|
||||
organizations: [{ id: "org1", name: "Org 1" }],
|
||||
});
|
||||
|
||||
mockApiClient.listAssistants
|
||||
.mockResolvedValueOnce([]) // org1: no assistants
|
||||
.mockRejectedValueOnce(new Error("Personal API failed")); // personal: API error
|
||||
|
||||
vi.mocked(fs.existsSync).mockReturnValue(true); // config.yaml exists
|
||||
|
||||
const result = await autoSelectOrganizationAndConfig(mockConfig);
|
||||
|
||||
expect(result!.organizationId).toBe(null);
|
||||
expect(result!.configUri).toContain("config.yaml");
|
||||
});
|
||||
|
||||
it("Empty organizations list → check personal assistants", async () => {
|
||||
mockApiClient.listOrganizations.mockResolvedValue({
|
||||
organizations: [], // No orgs
|
||||
});
|
||||
|
||||
mockApiClient.listAssistants.mockResolvedValue([
|
||||
{ ownerSlug: "personal", packageSlug: "my-assistant" },
|
||||
]);
|
||||
|
||||
const result = await autoSelectOrganizationAndConfig(mockConfig);
|
||||
|
||||
expect(result!.organizationId).toBe(null);
|
||||
expect(result!.configUri).toBe("slug://personal/my-assistant");
|
||||
});
|
||||
|
||||
it("API error → fallback with error message", async () => {
|
||||
mockApiClient.listOrganizations.mockRejectedValue(
|
||||
new Error("Network error"),
|
||||
);
|
||||
|
||||
const consoleSpy = vi
|
||||
.spyOn(console, "error")
|
||||
.mockImplementation(() => {});
|
||||
|
||||
const result = await autoSelectOrganizationAndConfig(mockConfig);
|
||||
|
||||
expect(result!.organizationId).toBe(null);
|
||||
expect(result!.configUri).toBeUndefined();
|
||||
expect(consoleSpy).toHaveBeenCalledWith(
|
||||
expect.stringContaining("Error fetching organizations:"),
|
||||
"Network error",
|
||||
);
|
||||
|
||||
consoleSpy.mockRestore();
|
||||
});
|
||||
});
|
||||
});
|
||||
155
extensions/cli/src/auth/orgSelection.ts
Normal file
155
extensions/cli/src/auth/orgSelection.ts
Normal file
|
|
@ -0,0 +1,155 @@
|
|||
import * as fs from "fs";
|
||||
import * as path from "path";
|
||||
|
||||
import chalk from "chalk";
|
||||
|
||||
import type { AuthConfig, AuthenticatedConfig } from "../auth/workos.js";
|
||||
import { saveAuthConfig } from "../auth/workos.js";
|
||||
import { getApiClient } from "../config.js";
|
||||
import { env } from "../env.js";
|
||||
|
||||
/**
|
||||
* Creates an updated AuthenticatedConfig with a new organization ID and optional config URI
|
||||
*/
|
||||
export function createUpdatedAuthConfig(
|
||||
config: AuthenticatedConfig,
|
||||
organizationId: string | null | undefined,
|
||||
configUri?: string | null,
|
||||
): AuthenticatedConfig {
|
||||
return {
|
||||
userId: config.userId,
|
||||
userEmail: config.userEmail,
|
||||
accessToken: config.accessToken,
|
||||
refreshToken: config.refreshToken,
|
||||
expiresAt: config.expiresAt,
|
||||
organizationId,
|
||||
configUri: configUri ?? config.configUri,
|
||||
modelName: config.modelName,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if an organization has available assistants
|
||||
*/
|
||||
async function hasOrgAssistants(
|
||||
apiClient: ReturnType<typeof getApiClient>,
|
||||
organizationId: string,
|
||||
): Promise<boolean> {
|
||||
try {
|
||||
const assistants = await apiClient.listAssistants({ organizationId });
|
||||
return assistants.length > 0;
|
||||
} catch {
|
||||
// If we can't check, assume no assistants
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the first available assistant from an organization
|
||||
*/
|
||||
async function getFirstAssistant(
|
||||
apiClient: ReturnType<typeof getApiClient>,
|
||||
organizationId: string,
|
||||
): Promise<string | null> {
|
||||
try {
|
||||
const assistants = await apiClient.listAssistants({ organizationId });
|
||||
if (assistants.length > 0) {
|
||||
const first = assistants[0];
|
||||
return `${first.ownerSlug}/${first.packageSlug}`;
|
||||
}
|
||||
return null;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if personal local config.yaml exists
|
||||
*/
|
||||
function hasPersonalLocalConfig(): boolean {
|
||||
const defaultConfigPath = path.join(env.continueHome, "config.yaml");
|
||||
return fs.existsSync(defaultConfigPath);
|
||||
}
|
||||
|
||||
/**
|
||||
* Automatically select organization and configuration for authenticated config
|
||||
* Priority: 1) Org with assistants (+ first assistant), 2) Personal with local config.yaml, 3) Personal fallback
|
||||
*/
|
||||
export async function autoSelectOrganizationAndConfig(
|
||||
authenticatedConfig: AuthenticatedConfig,
|
||||
): Promise<AuthConfig> {
|
||||
const apiClient = getApiClient(authenticatedConfig.accessToken);
|
||||
|
||||
try {
|
||||
const resp = await apiClient.listOrganizations();
|
||||
const organizations = resp.organizations;
|
||||
|
||||
// Priority 1: Find any organization that has assistants - use first assistant
|
||||
for (const org of organizations) {
|
||||
const hasAssistants = await hasOrgAssistants(apiClient, org.id);
|
||||
if (hasAssistants) {
|
||||
// Get the first assistant from this org
|
||||
const firstAssistantSlug = await getFirstAssistant(apiClient, org.id);
|
||||
const configUri = firstAssistantSlug
|
||||
? `slug://${firstAssistantSlug}`
|
||||
: undefined;
|
||||
|
||||
const updatedConfig = createUpdatedAuthConfig(
|
||||
authenticatedConfig,
|
||||
org.id,
|
||||
configUri,
|
||||
);
|
||||
saveAuthConfig(updatedConfig);
|
||||
return updatedConfig;
|
||||
}
|
||||
}
|
||||
|
||||
// Priority 2: Check if personal organization has assistants
|
||||
try {
|
||||
const personalAssistants = await apiClient.listAssistants({
|
||||
organizationId: undefined,
|
||||
});
|
||||
if (personalAssistants.length > 0) {
|
||||
const firstAssistant = personalAssistants[0];
|
||||
const firstAssistantSlug = `${firstAssistant.ownerSlug}/${firstAssistant.packageSlug}`;
|
||||
const configUri = `slug://${firstAssistantSlug}`;
|
||||
|
||||
const updatedConfig = createUpdatedAuthConfig(
|
||||
authenticatedConfig,
|
||||
null,
|
||||
configUri,
|
||||
);
|
||||
saveAuthConfig(updatedConfig);
|
||||
console.log(chalk.green("✓ Automatically selected personal assistant"));
|
||||
return updatedConfig;
|
||||
}
|
||||
} catch {
|
||||
// If personal assistants can't be fetched, continue to next priority
|
||||
}
|
||||
|
||||
// Priority 3: If no assistants anywhere, use local config.yaml
|
||||
if (hasPersonalLocalConfig()) {
|
||||
const updatedConfig = createUpdatedAuthConfig(
|
||||
authenticatedConfig,
|
||||
null,
|
||||
`file://${path.join(env.continueHome, "config.yaml")}`,
|
||||
);
|
||||
saveAuthConfig(updatedConfig);
|
||||
console.log(chalk.green("✓ Using local config.yaml"));
|
||||
return updatedConfig;
|
||||
}
|
||||
|
||||
// no org assistants or config.yaml
|
||||
const updatedConfig = createUpdatedAuthConfig(authenticatedConfig, null);
|
||||
saveAuthConfig(updatedConfig);
|
||||
return updatedConfig;
|
||||
} catch (error: any) {
|
||||
console.error(
|
||||
chalk.red("Error fetching organizations:"),
|
||||
error.response?.data?.message || error.message || error,
|
||||
);
|
||||
const updatedConfig = createUpdatedAuthConfig(authenticatedConfig, null);
|
||||
saveAuthConfig(updatedConfig);
|
||||
return updatedConfig;
|
||||
}
|
||||
}
|
||||
|
|
@ -16,7 +16,7 @@ import { saveAuthConfig } from "./workos.js";
|
|||
*/
|
||||
export function createUpdatedAuthConfig(
|
||||
config: AuthenticatedConfig,
|
||||
organizationId: string | null,
|
||||
organizationId: string | null | undefined,
|
||||
): AuthenticatedConfig {
|
||||
return {
|
||||
userId: config.userId,
|
||||
|
|
@ -124,43 +124,3 @@ export async function handleCliOrgForAuthenticatedConfig(
|
|||
saveAuthConfig(updatedConfig);
|
||||
return updatedConfig;
|
||||
}
|
||||
|
||||
/**
|
||||
* Automatically select organization for authenticated config
|
||||
*/
|
||||
export async function autoSelectOrganization(
|
||||
authenticatedConfig: AuthenticatedConfig,
|
||||
): Promise<AuthConfig> {
|
||||
const apiClient = getApiClient(authenticatedConfig.accessToken);
|
||||
|
||||
try {
|
||||
const resp = await apiClient.listOrganizations();
|
||||
const organizations = resp.organizations;
|
||||
|
||||
if (organizations.length === 0) {
|
||||
const updatedConfig = createUpdatedAuthConfig(authenticatedConfig, null);
|
||||
saveAuthConfig(updatedConfig);
|
||||
return updatedConfig;
|
||||
}
|
||||
|
||||
// Automatically select the first organization if available
|
||||
const selectedOrg = organizations[0];
|
||||
const selectedOrgId = selectedOrg.id;
|
||||
|
||||
const updatedConfig = createUpdatedAuthConfig(
|
||||
authenticatedConfig,
|
||||
selectedOrgId,
|
||||
);
|
||||
saveAuthConfig(updatedConfig);
|
||||
return updatedConfig;
|
||||
} catch (error: any) {
|
||||
console.error(
|
||||
chalk.red("Error fetching organizations:"),
|
||||
error.response?.data?.message || error.message || error,
|
||||
);
|
||||
console.info(chalk.yellow("Continuing without organization selection."));
|
||||
const updatedConfig = createUpdatedAuthConfig(authenticatedConfig, null);
|
||||
saveAuthConfig(updatedConfig);
|
||||
return updatedConfig;
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -22,7 +22,7 @@ export interface AuthenticatedConfig {
|
|||
accessToken: string;
|
||||
refreshToken: string;
|
||||
expiresAt: number;
|
||||
organizationId: string | null; // null means personal organization
|
||||
organizationId: string | null | undefined; // null means personal organization, undefined triggers auto-selection
|
||||
configUri?: string; // Optional config URI (file:// or slug://owner/slug)
|
||||
modelName?: string; // Name of the selected model
|
||||
}
|
||||
|
|
@ -74,7 +74,9 @@ export function getAccessToken(config: AuthConfig): string | null {
|
|||
/**
|
||||
* Gets the organization ID from any auth config type
|
||||
*/
|
||||
export function getOrganizationId(config: AuthConfig): string | null {
|
||||
export function getOrganizationId(
|
||||
config: AuthConfig,
|
||||
): string | null | undefined {
|
||||
if (config === null) return null;
|
||||
return config.organizationId;
|
||||
}
|
||||
|
|
@ -96,10 +98,9 @@ export function getModelName(config: AuthConfig): string | null {
|
|||
}
|
||||
|
||||
// URI utility functions have been moved to ./uriUtils.ts
|
||||
import { autoSelectOrganizationAndConfig } from "./orgSelection.js";
|
||||
import { pathToUri, slugToUri, uriToPath, uriToSlug } from "./uriUtils.js";
|
||||
import {
|
||||
autoSelectOrganization,
|
||||
createUpdatedAuthConfig,
|
||||
handleCliOrgForAuthenticatedConfig,
|
||||
handleCliOrgForEnvironmentAuth,
|
||||
} from "./workos.helpers.js";
|
||||
|
|
@ -360,7 +361,7 @@ async function pollForDeviceToken(
|
|||
accessToken: access_token,
|
||||
refreshToken: refresh_token,
|
||||
expiresAt: tokenExpiresAt,
|
||||
organizationId: null,
|
||||
organizationId: undefined, // undefined triggers auto-selection, null means personal org selected
|
||||
};
|
||||
|
||||
// Save the config
|
||||
|
|
@ -563,20 +564,18 @@ export async function ensureOrganization(
|
|||
);
|
||||
}
|
||||
|
||||
// If already have organization ID (including null for personal), return as-is
|
||||
if (authenticatedConfig.organizationId !== undefined) {
|
||||
return authenticatedConfig;
|
||||
// Only auto-select if user hasn't made any previous selections
|
||||
// - organizationId === undefined means first-time setup
|
||||
// - configUri being set means they've chosen a specific assistant/config
|
||||
if (
|
||||
authenticatedConfig.organizationId === undefined &&
|
||||
!authenticatedConfig.configUri
|
||||
) {
|
||||
return autoSelectOrganizationAndConfig(authenticatedConfig);
|
||||
}
|
||||
|
||||
// In headless mode, default to personal organization if none saved
|
||||
if (isHeadless) {
|
||||
const updatedConfig = createUpdatedAuthConfig(authenticatedConfig, null);
|
||||
saveAuthConfig(updatedConfig);
|
||||
return updatedConfig;
|
||||
}
|
||||
|
||||
// Need to select organization
|
||||
return autoSelectOrganization(authenticatedConfig);
|
||||
// User already has made a selection (org or config) - respect their choice
|
||||
return authenticatedConfig;
|
||||
}
|
||||
|
||||
/**
|
||||
|
|
|
|||
|
|
@ -498,17 +498,12 @@ export async function chat(prompt?: string, options: ChatOptions = {}) {
|
|||
const { permissionOverrides } = processCommandFlags(options);
|
||||
|
||||
// Initialize services with onboarding handled internally
|
||||
const initResult = await initializeServices({
|
||||
await initializeServices({
|
||||
options,
|
||||
headless: false,
|
||||
toolPermissionOverrides: permissionOverrides,
|
||||
});
|
||||
|
||||
// If onboarding was completed, show success message
|
||||
if (initResult.wasOnboarded) {
|
||||
console.log(chalk.green("✓ Setup complete! Starting chat..."));
|
||||
}
|
||||
|
||||
// Start TUI with skipOnboarding since we already handled it
|
||||
const tuiOptions: any = {
|
||||
initialPrompt: prompt,
|
||||
|
|
|
|||
|
|
@ -39,7 +39,7 @@ export function createLlmApi(
|
|||
apiKey: accessToken ?? undefined,
|
||||
env: {
|
||||
apiKeyLocation: (model as any).apiKeyLocation,
|
||||
orgScopeId: organizationId,
|
||||
orgScopeId: organizationId ?? null,
|
||||
proxyUrl:
|
||||
(model as { onPremProxyUrl: string | undefined })
|
||||
.onPremProxyUrl ?? undefined,
|
||||
|
|
|
|||
|
|
@ -55,7 +55,7 @@ export async function loadConfiguration(
|
|||
const config = await loadFromSource(
|
||||
configSource,
|
||||
accessToken,
|
||||
organizationId,
|
||||
organizationId ?? null,
|
||||
apiClient,
|
||||
);
|
||||
|
||||
|
|
|
|||
|
|
@ -105,7 +105,10 @@ async function runOnboardingFlow(
|
|||
if (choice === "1" || choice === "") {
|
||||
const newAuthConfig = await login();
|
||||
|
||||
const result = await initialize(newAuthConfig, undefined);
|
||||
const { ensureOrganization } = await import("./auth/workos.js");
|
||||
const finalAuthConfig = await ensureOrganization(newAuthConfig);
|
||||
|
||||
const result = await initialize(finalAuthConfig, undefined);
|
||||
return { ...result, wasOnboarded: true };
|
||||
} else if (choice === "2") {
|
||||
const apiKey = readlineSync.question(
|
||||
|
|
|
|||
Loading…
Add table
Reference in a new issue