diff --git a/src/common.ts b/src/common.ts index 101fa4c0..d6e0a816 100644 --- a/src/common.ts +++ b/src/common.ts @@ -14,6 +14,7 @@ import { HostProvider } from "@/hosts/host-provider" import { FileContextTracker } from "./core/context/context-tracking/FileContextTracker" import { StateManager } from "./core/storage/StateManager" import { ExtensionRegistryInfo } from "./registry" +import { BannerService } from "./services/banner/BannerService" import { audioRecordingService } from "./services/dictation/AudioRecordingService" import { ErrorService } from "./services/error" import { featureFlagsService } from "./services/feature-flags" @@ -71,6 +72,20 @@ export async function initialize(context: vscode.ExtensionContext): Promise { + if (banners.length > 0) { + Logger.log(`BannerService: ${banners.length} active banner(s) fetched.`) + // Banners are now cached and can be accessed by the frontend when needed + } + }) + .catch((error) => { + Logger.error("BannerService: Failed to fetch banners on startup", error) + }) + telemetryService.captureExtensionActivated() return webview diff --git a/src/services/auth/AuthService.ts b/src/services/auth/AuthService.ts index 184e96af..e28d0543 100644 --- a/src/services/auth/AuthService.ts +++ b/src/services/auth/AuthService.ts @@ -199,6 +199,14 @@ export class AuthService { } } + /** + * Gets the provider name for the current authentication + * @returns The provider name (e.g., "cline", "firebase"), or null if not authenticated + */ + getProviderName(): string | null { + return this._clineAuthInfo?.provider ?? null + } + getInfo(): AuthState { // TODO: this logic should be cleaner, but this will determine the authentication state for the webview -- if a user object is returned then the webview assumes authenticated, otherwise it assumes logged out (we previously returned a UserInfo object with empty fields, and this represented a broken logged in state) let user: any = null diff --git a/src/services/banner/BannerService.test.ts b/src/services/banner/BannerService.test.ts new file mode 100644 index 00000000..79fafc9c --- /dev/null +++ b/src/services/banner/BannerService.test.ts @@ -0,0 +1,652 @@ +/** + * Tests for BannerService + * Tests API fetching, caching, and rule evaluation logic + */ + +import type { BannerRules } from "@shared/ClineBanner" +import axios from "axios" +import { expect } from "chai" +import { afterEach, beforeEach, describe, it } from "mocha" +import * as sinon from "sinon" +import type { Controller } from "@/core/controller" +import { Logger } from "../logging/Logger" +import { BannerService } from "./BannerService" + +describe("BannerService", () => { + let sandbox: sinon.SinonSandbox + let bannerService: BannerService + let axiosGetStub: sinon.SinonStub + let mockController: Partial + + beforeEach(() => { + sandbox = sinon.createSandbox() + + sandbox.stub(Logger, "log") + sandbox.stub(Logger, "error") + + mockController = { + stateManager: { + getApiConfiguration: () => ({}), + getGlobalSettingsKey: () => undefined, + getGlobalStateKey: () => [], + } as any, + } + + // Reset singleton and initialize with mock controller + BannerService.reset() + bannerService = BannerService.initialize(mockController as Controller) + bannerService.clearCache() + + axiosGetStub = sandbox.stub(axios, "get") + }) + + afterEach(() => { + bannerService.clearCache() + BannerService.reset() + sandbox.restore() + }) + + describe("API Fetching", () => { + it("should fetch banners from API successfully", async () => { + const mockResponse = { + data: { + data: { + banners: [ + { + id: "bnr_test1", + titleMd: "Test Banner", + bodyMd: "This is a test", + severity: "info" as const, + placement: "top" as const, + rulesJson: "{}", + activeFrom: new Date(Date.now() - 86400000).toISOString(), + activeTo: new Date(Date.now() + 86400000).toISOString(), + }, + ], + }, + }, + } + + axiosGetStub.resolves(mockResponse) + const banners = await bannerService.fetchActiveBanners() + + expect(axiosGetStub.calledOnce).to.be.true + expect(banners).to.have.lengthOf(1) + expect(banners[0].id).to.equal("bnr_test1") + }) + + it("should handle API errors gracefully", async () => { + axiosGetStub.rejects(new Error("Network error")) + const banners = await bannerService.fetchActiveBanners() + expect(banners).to.have.lengthOf(0) + }) + + it("should cache banners for 5 minutes", async () => { + const clock = sandbox.useFakeTimers() + + const mockResponse = { + data: { + data: { + banners: [ + { + id: "bnr_cached", + titleMd: "Cached Banner", + bodyMd: "Test", + severity: "info" as const, + placement: "top" as const, + rulesJson: "{}", + }, + ], + }, + }, + } + + axiosGetStub.resolves(mockResponse) + + // First call fetches from API + await bannerService.fetchActiveBanners() + expect(axiosGetStub.callCount).to.equal(1) + + // Second call within cache window uses cache (no new API call) + await bannerService.fetchActiveBanners() + expect(axiosGetStub.callCount).to.equal(1) + + // After 4 minutes, still uses cache + clock.tick(4 * 60 * 1000) + await bannerService.fetchActiveBanners() + expect(axiosGetStub.callCount).to.equal(1) + + // After 6 minutes total, cache expired, makes new API call + clock.tick(2 * 60 * 1000) + await bannerService.fetchActiveBanners() + expect(axiosGetStub.callCount).to.equal(2) + + // Force refresh always bypasses cache + await bannerService.fetchActiveBanners(true) + expect(axiosGetStub.callCount).to.equal(3) + }) + }) + + describe("Date Range Filtering", () => { + it("should filter out expired banners", async () => { + const mockResponse = { + data: { + data: { + banners: [ + { + id: "bnr_expired", + titleMd: "Expired", + bodyMd: "Test", + severity: "info" as const, + placement: "top" as const, + rulesJson: "{}", + activeFrom: new Date(Date.now() - 172800000).toISOString(), + activeTo: new Date(Date.now() - 86400000).toISOString(), // activeTo is in the Past + }, + ], + }, + }, + } + + axiosGetStub.resolves(mockResponse) + const banners = await bannerService.fetchActiveBanners() + expect(banners).to.have.lengthOf(0) + }) + + it("should filter out future banners", async () => { + const mockResponse = { + data: { + data: { + banners: [ + { + id: "bnr_future", + titleMd: "Future", + bodyMd: "Test", + severity: "info" as const, + placement: "top" as const, + rulesJson: "{}", + activeFrom: new Date(Date.now() + 86400000).toISOString(), // activeFrom is in the Future + activeTo: new Date(Date.now() + 172800000).toISOString(), + }, + ], + }, + }, + } + + axiosGetStub.resolves(mockResponse) + const banners = await bannerService.fetchActiveBanners() + expect(banners).to.have.lengthOf(0) + }) + + it("should include currently active banners", async () => { + const mockResponse = { + data: { + data: { + banners: [ + { + id: "bnr_active", + titleMd: "Active", + bodyMd: "Test", + severity: "info" as const, + placement: "top" as const, + rulesJson: "{}", + activeFrom: new Date(Date.now() - 86400000).toISOString(), + activeTo: new Date(Date.now() + 86400000).toISOString(), + }, + ], + }, + }, + } + + axiosGetStub.resolves(mockResponse) + const banners = await bannerService.fetchActiveBanners() + expect(banners).to.have.lengthOf(1) + expect(banners[0].id).to.equal("bnr_active") + }) + }) + + describe("API Provider Rule Evaluation", () => { + it("should show banner when user has the required API provider configured", async () => { + const controllerWithOpenAI: Partial = { + stateManager: { + getApiConfiguration: () => ({ + openAiApiKey: "sk-test-key", + }), + getGlobalSettingsKey: () => undefined, + getGlobalStateKey: () => [], + } as any, + } + // Reinitialize with new controller + BannerService.reset() + bannerService = BannerService.initialize(controllerWithOpenAI as Controller) + + const mockResponse = { + data: { + data: { + banners: [ + { + id: "bnr_openai", + titleMd: "OpenAI Users", + bodyMd: "For OpenAI API", + severity: "info" as const, + placement: "top" as const, + rulesJson: JSON.stringify({ providers: ["openai"] } as BannerRules), + }, + ], + }, + }, + } + + axiosGetStub.resolves(mockResponse) + const banners = await bannerService.fetchActiveBanners() + + expect(banners).to.have.lengthOf(1) + expect(banners[0].id).to.equal("bnr_openai") + }) + + it("should NOT show banner when user doesn't have the required API provider", async () => { + const controllerWithoutOpenAI: Partial = { + stateManager: { + getApiConfiguration: () => ({ + apiKey: "sk-ant-test", // Has Anthropic key but not OpenAI + }), + getGlobalSettingsKey: () => undefined, + getGlobalStateKey: () => [], + } as any, + } + // Reinitialize with new controller + BannerService.reset() + bannerService = BannerService.initialize(controllerWithoutOpenAI as Controller) + + const mockResponse = { + data: { + data: { + banners: [ + { + id: "bnr_openai", + titleMd: "OpenAI Users", + bodyMd: "For OpenAI API", + severity: "info" as const, + placement: "top" as const, + rulesJson: JSON.stringify({ providers: ["openai"] } as BannerRules), + }, + ], + }, + }, + } + + axiosGetStub.resolves(mockResponse) + const banners = await bannerService.fetchActiveBanners() + + expect(banners).to.have.lengthOf(0) + }) + + it("should show banner if user has ANY of multiple specified providers", async () => { + const controllerWithAnthropic: Partial = { + stateManager: { + getApiConfiguration: () => ({ + apiKey: "sk-ant-test", // Has Anthropic key + }), + getGlobalSettingsKey: () => undefined, + getGlobalStateKey: () => [], + } as any, + } + // Reinitialize with new controller + BannerService.reset() + bannerService = BannerService.initialize(controllerWithAnthropic as Controller) + + const mockResponse = { + data: { + data: { + banners: [ + { + id: "bnr_multi", + titleMd: "Multiple Providers", + bodyMd: "For Anthropic or OpenAI users", + severity: "info" as const, + placement: "top" as const, + rulesJson: JSON.stringify({ providers: ["anthropic", "openai"] } as BannerRules), + }, + ], + }, + }, + } + + axiosGetStub.resolves(mockResponse) + const banners = await bannerService.fetchActiveBanners() + + expect(banners).to.have.lengthOf(1) + expect(banners[0].id).to.equal("bnr_multi") + }) + }) + + describe("Audience Targeting", () => { + it("should show banner targeting all users", async () => { + const mockResponse = { + data: { + data: { + banners: [ + { + id: "bnr_all", + titleMd: "All Users", + bodyMd: "For everyone", + severity: "info" as const, + placement: "top" as const, + rulesJson: JSON.stringify({ audience: "all" } as BannerRules), + }, + ], + }, + }, + } + + axiosGetStub.resolves(mockResponse) + const banners = await bannerService.fetchActiveBanners() + + expect(banners).to.have.lengthOf(1) + expect(banners[0].id).to.equal("bnr_all") + }) + + it("should show team admin banner to admin users", async () => { + const mockAuthService = { + getUserOrganizations: () => [{ id: "org1", name: "Test Org", roles: ["admin"] }], + getInfo: () => ({ user: { email: "test@example.com" } }), + } as any + + bannerService.setAuthService(mockAuthService) + + const mockResponse = { + data: { + data: { + banners: [ + { + id: "bnr_admin", + titleMd: "Team Admins", + bodyMd: "For team admins only", + severity: "info" as const, + placement: "top" as const, + rulesJson: JSON.stringify({ audience: "team admin only" } as BannerRules), + }, + ], + }, + }, + } + + axiosGetStub.resolves(mockResponse) + const banners = await bannerService.fetchActiveBanners() + + expect(banners).to.have.lengthOf(1) + expect(banners[0].id).to.equal("bnr_admin") + }) + + it("should show team admin banner to owner users", async () => { + const mockAuthService = { + getUserOrganizations: () => [{ id: "org1", name: "Test Org", roles: ["owner"] }], + getInfo: () => ({ user: { email: "test@example.com" } }), + } as any + + bannerService.setAuthService(mockAuthService) + + const mockResponse = { + data: { + data: { + banners: [ + { + id: "bnr_admin", + titleMd: "Team Admins", + bodyMd: "For team admins only", + severity: "info" as const, + placement: "top" as const, + rulesJson: JSON.stringify({ audience: "team admin only" } as BannerRules), + }, + ], + }, + }, + } + + axiosGetStub.resolves(mockResponse) + const banners = await bannerService.fetchActiveBanners() + + expect(banners).to.have.lengthOf(1) + expect(banners[0].id).to.equal("bnr_admin") + }) + + it("should NOT show team admin banner to non-admin users", async () => { + const mockAuthService = { + getUserOrganizations: () => [{ id: "org1", name: "Test Org", roles: ["member"] }], + getInfo: () => ({ user: { email: "test@example.com" } }), + } as any + + bannerService.setAuthService(mockAuthService) + + const mockResponse = { + data: { + data: { + banners: [ + { + id: "bnr_admin", + titleMd: "Team Admins", + bodyMd: "For team admins only", + severity: "info" as const, + placement: "top" as const, + rulesJson: JSON.stringify({ audience: "team admin only" } as BannerRules), + }, + ], + }, + }, + } + + axiosGetStub.resolves(mockResponse) + const banners = await bannerService.fetchActiveBanners() + + expect(banners).to.have.lengthOf(0) + }) + + it("should show team members banner to users in organizations", async () => { + const mockAuthService = { + getUserOrganizations: () => [{ id: "org1", name: "Test Org", roles: ["member"] }], + getInfo: () => ({ user: { email: "test@example.com" } }), + } as any + + bannerService.setAuthService(mockAuthService) + + const mockResponse = { + data: { + data: { + banners: [ + { + id: "bnr_team", + titleMd: "Team Members", + bodyMd: "For team members", + severity: "info" as const, + placement: "top" as const, + rulesJson: JSON.stringify({ audience: "team members" } as BannerRules), + }, + ], + }, + }, + } + + axiosGetStub.resolves(mockResponse) + const banners = await bannerService.fetchActiveBanners() + + expect(banners).to.have.lengthOf(1) + expect(banners[0].id).to.equal("bnr_team") + }) + + it("should NOT show team members banner to users without organizations", async () => { + const mockAuthService = { + getUserOrganizations: () => [], + getInfo: () => ({ user: { email: "test@example.com" } }), + } as any + + bannerService.setAuthService(mockAuthService) + + const mockResponse = { + data: { + data: { + banners: [ + { + id: "bnr_team", + titleMd: "Team Members", + bodyMd: "For team members", + severity: "info" as const, + placement: "top" as const, + rulesJson: JSON.stringify({ audience: "team members" } as BannerRules), + }, + ], + }, + }, + } + + axiosGetStub.resolves(mockResponse) + const banners = await bannerService.fetchActiveBanners() + + expect(banners).to.have.lengthOf(0) + }) + + it("should show personal banner to users without organizations", async () => { + const mockAuthService = { + getUserOrganizations: () => [], + getInfo: () => ({ user: { email: "test@example.com" } }), + } as any + + bannerService.setAuthService(mockAuthService) + + const mockResponse = { + data: { + data: { + banners: [ + { + id: "bnr_personal", + titleMd: "Personal Users", + bodyMd: "For personal users", + severity: "info" as const, + placement: "top" as const, + rulesJson: JSON.stringify({ audience: "personal only" } as BannerRules), + }, + ], + }, + }, + } + + axiosGetStub.resolves(mockResponse) + const banners = await bannerService.fetchActiveBanners() + + expect(banners).to.have.lengthOf(1) + expect(banners[0].id).to.equal("bnr_personal") + }) + + it("should NOT show personal banner to users with organizations", async () => { + const mockAuthService = { + getUserOrganizations: () => [{ id: "org1", name: "Test Org", roles: ["member"] }], + getInfo: () => ({ user: { email: "test@example.com" } }), + } as any + + bannerService.setAuthService(mockAuthService) + + const mockResponse = { + data: { + data: { + banners: [ + { + id: "bnr_personal", + titleMd: "Personal Users", + bodyMd: "For personal users", + severity: "info" as const, + placement: "top" as const, + rulesJson: JSON.stringify({ audience: "personal only" } as BannerRules), + }, + ], + }, + }, + } + + axiosGetStub.resolves(mockResponse) + const banners = await bannerService.fetchActiveBanners() + + expect(banners).to.have.lengthOf(0) + }) + }) + + describe("Invalid or No Banner Rules", () => { + it("should handle malformed rules gracefully (fail open)", async () => { + const mockResponse = { + data: { + data: { + banners: [ + { + id: "bnr_malformed", + titleMd: "Malformed", + bodyMd: "Test", + severity: "info" as const, + placement: "top" as const, + rulesJson: "{ invalid json", + }, + ], + }, + }, + } + + axiosGetStub.resolves(mockResponse) + const banners = await bannerService.fetchActiveBanners() + + expect(banners).to.have.lengthOf(1) + }) + + it("should handle banners with no rules", async () => { + const mockResponse = { + data: { + data: { + banners: [ + { + id: "bnr_norules", + titleMd: "No Rules", + bodyMd: "Test", + severity: "info" as const, + placement: "top" as const, + rulesJson: "{}", + }, + ], + }, + }, + } + + axiosGetStub.resolves(mockResponse) + const banners = await bannerService.fetchActiveBanners() + + expect(banners).to.have.lengthOf(1) + expect(banners[0].id).to.equal("bnr_norules") + }) + }) + + describe("Cache Management", () => { + it("should clear cache when requested", async () => { + const mockResponse = { + data: { + data: { + banners: [ + { + id: "bnr_test", + titleMd: "Test", + bodyMd: "Test", + severity: "info" as const, + placement: "top" as const, + rulesJson: "{}", + }, + ], + }, + }, + } + + axiosGetStub.resolves(mockResponse) + + await bannerService.fetchActiveBanners() + expect(axiosGetStub.calledOnce).to.be.true + + bannerService.clearCache() + + await bannerService.fetchActiveBanners() + expect(axiosGetStub.calledTwice).to.be.true + }) + }) +}) diff --git a/src/services/banner/BannerService.ts b/src/services/banner/BannerService.ts new file mode 100644 index 00000000..abd8a5d2 --- /dev/null +++ b/src/services/banner/BannerService.ts @@ -0,0 +1,448 @@ +import type { Banner, BannerRules, BannersResponse } from "@shared/ClineBanner" +import { isClineInternalTester } from "@shared/internal/account" +import axios from "axios" +import { ClineEnv } from "@/config" +import type { Controller } from "@/core/controller" +import { HostProvider } from "@/hosts/host-provider" +import { AuthService } from "../auth/AuthService" +import { Logger } from "../logging/Logger" + +/** + * Service for fetching and evaluating banner messages + */ +export class BannerService { + private static instance: BannerService | null = null + private readonly _baseUrl = ClineEnv.config().apiBaseUrl + private _cachedBanners: Banner[] = [] + private _lastFetchTime: number = 0 + private readonly CACHE_DURATION_MS = 5 * 60 * 1000 // 5 minutes + private _controller: Controller + private _authService?: AuthService + + private constructor(controller: Controller) { + this._controller = controller + } + + /** + * Initializes the BannerService singleton with required dependencies + * @param controller The controller instance for accessing state and services + * @returns The initialized BannerService instance + * @throws Error if already initialized + */ + public static initialize(controller: Controller): BannerService { + if (BannerService.instance) { + throw new Error("BannerService has already been initialized.") + } + BannerService.instance = new BannerService(controller) + return BannerService.instance + } + + /** + * Returns the singleton instance of BannerService + * @throws Error if not initialized + */ + public static get(): BannerService { + if (!BannerService.instance) { + throw new Error("BannerService not initialized. Call BannerService.initialize() first.") + } + return BannerService.instance + } + + /** + * Checks if BannerService has been initialized + */ + public static isInitialized(): boolean { + return !!BannerService.instance + } + + /** + * Resets the BannerService instance (primarily for testing) + */ + public static reset(): void { + BannerService.instance = null + } + + /** + * Sets the AuthService instance for testing purposes + * In production, AuthService is loaded dynamically when needed + */ + public setAuthService(authService: AuthService): void { + this._authService = authService + } + + /** + * Fetches active banners from the API + * @param forceRefresh If true, bypasses cache and fetches fresh data + * @returns Array of banners that match current environment + */ + public async fetchActiveBanners(forceRefresh = false): Promise { + try { + // Return cached banners if still valid + const now = Date.now() + if (!forceRefresh && this._cachedBanners.length > 0 && now - this._lastFetchTime < this.CACHE_DURATION_MS) { + Logger.log("BannerService: Returning cached banners") + return this._cachedBanners + } + + // Fetch from API + const url = new URL("/banners/v1/messages", this._baseUrl).toString() + Logger.log(`BannerService: Fetching banners from ${url}`) + + const response = await axios.get(url, { + timeout: 10000, // 10 second timeout + headers: { + "Content-Type": "application/json", + }, + }) + + if (!response.data?.data?.banners) { + Logger.log("BannerService: Invalid response format") + return [] + } + + const allBanners = response.data.data.banners + Logger.log(`BannerService: Received ${allBanners.length} banners from API`) + + // Filter banners based on rules evaluation + const matchingBanners = [] + for (const banner of allBanners) { + if (await this.evaluateBannerRules(banner)) { + matchingBanners.push(banner) + } + } + Logger.log(`BannerService: ${matchingBanners.length} banners match current environment`) + + // Update cache + this._cachedBanners = matchingBanners + this._lastFetchTime = now + + return matchingBanners + } catch (error) { + // Log error but don't throw - banner fetching shouldn't break the extension + Logger.error("BannerService: Error fetching banners", error) + return [] + } + } + + /** + * Evaluates banner rules against the current environment + * @param banner Banner to evaluate + * @returns true if banner should be displayed + */ + private async evaluateBannerRules(banner: Banner): Promise { + try { + // Check date range first (active_from and active_to) + // The API response should already check this and only + // return active time window banners, here is to ensure. + if (!this.isWithinActiveDateRange(banner)) { + Logger.log(`BannerService: Banner ${banner.id} filtered out - outside active date range`) + return false + } + + // Parse rules JSON + const rules: BannerRules = JSON.parse(banner.rulesJson || "{}") + + // Check IDE rule + if (rules.ide && rules.ide.length > 0) { + const currentIde = await this.getIdeType() + if (currentIde && !rules.ide.includes(currentIde)) { + Logger.log( + `BannerService: Banner ${banner.id} filtered out by IDE rule (requires: ${rules.ide.join(", ")}, current: ${currentIde})`, + ) + return false + } + } + + // Check auth provider rule + if (rules.auth && rules.auth.length > 0 && this._controller) { + const authProvider = this.getAuthProvider() + if (authProvider && !rules.auth.includes(authProvider)) { + Logger.log( + `BannerService: Banner ${banner.id} filtered out by auth rule (requires: ${rules.auth.join(", ")}, current: ${authProvider})`, + ) + return false + } + } + + // Check API providers rule - show banner if user has ANY of the specified providers configured + if (rules.providers && rules.providers.length > 0 && this._controller) { + const apiConfiguration = this._controller.stateManager.getApiConfiguration() + const hasAnyProvider = rules.providers.some((provider) => { + switch (provider) { + case "anthropic": + case "claude-code": + return !!apiConfiguration?.apiKey + case "openai": + case "openai-native": + return !!apiConfiguration?.openAiApiKey || !!apiConfiguration?.openAiNativeApiKey + case "openrouter": + return !!apiConfiguration?.openRouterApiKey + case "bedrock": + return !!apiConfiguration?.awsAccessKey || !!apiConfiguration?.awsBedrockApiKey + case "gemini": + return !!apiConfiguration?.geminiApiKey + case "deepseek": + return !!apiConfiguration?.deepSeekApiKey + case "qwen": + case "qwen-code": + return !!apiConfiguration?.qwenApiKey + case "mistral": + return !!apiConfiguration?.mistralApiKey + case "ollama": + return !!apiConfiguration?.ollamaApiKey + case "xai": + return !!apiConfiguration?.xaiApiKey + case "cerebras": + return !!apiConfiguration?.cerebrasApiKey + case "groq": + return !!apiConfiguration?.groqApiKey + default: + return false + } + }) + + if (!hasAnyProvider) { + Logger.log( + `BannerService: Banner ${banner.id} filtered out - user doesn't have any of these providers configured: ${rules.providers.join(", ")}`, + ) + return false + } + } + + // Check employee only rule + if (rules.employee_only && this._controller) { + const isEmployee = this.isEmployee() + if (!isEmployee) { + Logger.log(`BannerService: Banner ${banner.id} filtered out - employee only`) + return false + } + } + + // Check audience segment + if (rules.audience && this._controller) { + switch (rules.audience) { + case "all": + // Show to all users + Logger.log(`BannerService: Banner ${banner.id} targets all users`) + break + + case "team admin only": + // Show only to team admins + const isTeamAdmin = this.isUserTeamAdmin() + if (!isTeamAdmin) { + Logger.log(`BannerService: Banner ${banner.id} filtered out - user is not a team admin`) + return false + } + break + + case "team members": + // Show only to users who are part of a team (have organizations) + const hasOrganizations = this.hasOrganizations() + if (!hasOrganizations) { + Logger.log(`BannerService: Banner ${banner.id} filtered out - user is not a team member`) + return false + } + break + + case "personal only": + // Show only to users who have NO enterprise/organization account + // (Enterprise users also have a personal account by default, but this targets only non-enterprise users) + const hasOrgs = this.hasOrganizations() + if (hasOrgs) { + Logger.log(`BannerService: Banner ${banner.id} filtered out - user has enterprise account`) + return false + } + break + } + } + + Logger.log(`BannerService: Banner ${banner.id} passed all rules checks`) + return true + } catch (error) { + // If rules can't be parsed or evaluated, show the banner (fail open) + Logger.log( + `BannerService: Error evaluating rules for banner ${banner.id}: ${error instanceof Error ? error.message : String(error)}`, + ) + return true + } + } + + /** + * Checks if the banner is within its active date range + * @param banner Banner to check + * @returns true if current date is within activeFrom and activeTo range + */ + private isWithinActiveDateRange(banner: Banner): boolean { + const now = new Date() + + if (banner.activeFrom) { + const activeFrom = new Date(banner.activeFrom) + if (now < activeFrom) { + return false + } + } + + if (banner.activeTo) { + const activeTo = new Date(banner.activeTo) + if (now > activeTo) { + return false + } + } + + return true + } + + /** + * Gets the current IDE type + * @returns IDE type (vscode, jetbrains, or unknown) + */ + private async getIdeType(): Promise { + try { + const hostVersion = await HostProvider.env.getHostVersion({}) + + // Use clineType field which contains values like "VSCode Extension", "Cline for JetBrains", etc. + const clineType = hostVersion.clineType?.toLowerCase() || "" + + if (clineType.includes("vscode")) { + return "vscode" + } + if (clineType.includes("jetbrains")) { + return "jetbrains" + } + + return "unknown" + } catch (error) { + Logger.error("BannerService: Error getting IDE type", error) + return "unknown" + } + } + + /** + * Gets the current auth provider name + * @returns Auth provider name (firebase, workos, or unknown) + */ + private getAuthProvider(): string { + try { + // Get auth provider from AuthService + const authService = this.getAuthServiceInstance() + if (!authService) { + return "unknown" + } + const authInfo = authService.getInfo() + + // Check if user is authenticated + if (!authInfo.user) { + return "other" + } + + // Get provider name using public method + const providerName = authService.getProviderName() + if (providerName) { + // Map provider names to expected values + if (providerName === "cline") { + return "workos" + } + return providerName + } + + return "unknown" + } catch (error) { + Logger.error("BannerService: Error getting auth provider", error) + return "unknown" + } + } + + /** + * Checks if the current user is a Cline employee + * @returns true if user has a @cline.bot email or is a trusted tester + */ + private isEmployee(): boolean { + try { + const authService = this.getAuthServiceInstance() + if (!authService) { + return false + } + const authInfo = authService.getInfo() + + if (!authInfo.user || !authInfo.user.email) { + return false + } + + return isClineInternalTester(authInfo.user.email) + } catch (error) { + Logger.error("BannerService: Error checking employee status", error) + return false + } + } + + /** + * Checks if the current user is a team admin + * @returns true if user is an admin or owner of any organization + */ + private isUserTeamAdmin(): boolean { + try { + const authService = this.getAuthServiceInstance() + if (!authService) { + return false + } + const organizations = authService.getUserOrganizations() + + if (!organizations || organizations.length === 0) { + return false + } + + // Check if user has admin or owner role in any organization + // Admin and owner roles have the same permissions + return organizations.some((org: any) => org.roles && (org.roles.includes("admin") || org.roles.includes("owner"))) + } catch (error) { + Logger.error("BannerService: Error checking team admin status", error) + return false + } + } + + /** + * Checks if the current user is part of any organization + * @returns true if user has one or more organizations + */ + private hasOrganizations(): boolean { + try { + const authService = this.getAuthServiceInstance() + if (!authService) { + return false + } + const organizations = authService.getUserOrganizations() + + return !!(organizations && organizations.length > 0) + } catch (error) { + Logger.error("BannerService: Error checking organizations", error) + return false + } + } + + /** + * Gets the AuthService instance + * @returns AuthService instance or undefined if not available + */ + private getAuthServiceInstance(): AuthService | undefined { + // Use injected instance if available (for testing) + if (this._authService) { + return this._authService + } + + // Otherwise, get singleton instance + try { + return AuthService.getInstance(this._controller) + } catch { + return undefined + } + } + + /** + * Clears the banner cache + */ + public clearCache(): void { + this._cachedBanners = [] + this._lastFetchTime = 0 + Logger.log("BannerService: Cache cleared") + } +} diff --git a/src/shared/ClineBanner.ts b/src/shared/ClineBanner.ts new file mode 100644 index 00000000..9a718620 --- /dev/null +++ b/src/shared/ClineBanner.ts @@ -0,0 +1,44 @@ +/** + * Banner message types for Cline extension + */ + +export type BannerSeverity = "info" | "success" | "warning" +export type BannerPlacement = "top" | "bottom" + +export interface Banner { + id: string + titleMd: string + bodyMd: string + severity: BannerSeverity + placement: BannerPlacement + rulesJson: string + activeFrom?: string + activeTo?: string +} + +export interface BannersResponse { + data: { + banners: Banner[] + } +} + +/** + * Audience targeting options + */ +export type BannerAudience = "all" | "team admin only" | "team members" | "personal only" + +/** + * Rules that can be evaluated for banner targeting + */ +export interface BannerRules { + /** Target specific IDEs (e.g., "vscode", "jetbrains") */ + ide?: string[] + /** Target specific auth providers (e.g., "firebase", "workos") */ + auth?: string[] + /** Target employees only */ + employee_only?: boolean + /** Target users with specific API providers (e.g., "anthropic", "openai") */ + providers?: string[] + /** Target specific audience segment */ + audience?: BannerAudience +}