diff --git a/package-lock.json b/package-lock.json index 0e65af766..65348ad4a 100644 --- a/package-lock.json +++ b/package-lock.json @@ -38,6 +38,7 @@ "minimatch": "^10.0.3", "node-fetch": "^3.3.2", "open": "^10.1.0", + "posthog-node": "^5.6.0", "react": "^19.1.0", "readline-sync": "^1.4.10", "turndown": "^7.2.0", @@ -14123,6 +14124,15 @@ "node": ">=4" } }, + "node_modules/posthog-node": { + "version": "5.6.0", + "resolved": "https://registry.npmjs.org/posthog-node/-/posthog-node-5.6.0.tgz", + "integrity": "sha512-MVXxKmqAYp2cPBrN1YMhnhYsJYIu6yc6wumbHz1dbo67wZBf2WtMm67Uh+4VCrp07049qierWlxQqz1W5zGDeg==", + "license": "MIT", + "engines": { + "node": ">=20" + } + }, "node_modules/pretty-format": { "version": "29.7.0", "resolved": "https://registry.npmjs.org/pretty-format/-/pretty-format-29.7.0.tgz", diff --git a/package.json b/package.json index c94b0338b..1c29f9e77 100644 --- a/package.json +++ b/package.json @@ -60,6 +60,7 @@ "minimatch": "^10.0.3", "node-fetch": "^3.3.2", "open": "^10.1.0", + "posthog-node": "^5.6.0", "react": "^19.1.0", "readline-sync": "^1.4.10", "turndown": "^7.2.0", diff --git a/src/commands/chat.ts b/src/commands/chat.ts index 51dd1ed46..30d6075c3 100644 --- a/src/commands/chat.ts +++ b/src/commands/chat.ts @@ -18,6 +18,7 @@ import { safeStdout } from "../util/consoleOverride.js"; import { formatError } from "../util/formatError.js"; import logger from "../util/logger.js"; import { BaseCommandOptions } from "./BaseCommandOptions.js"; +import { posthogService } from "../telemetry/posthogService.js"; export interface ChatOptions extends BaseCommandOptions { headless?: boolean; @@ -153,6 +154,7 @@ export async function chat(prompt?: string, options: ChatOptions = {}) { try { // Record session start telemetryService.recordSessionStart(); + await posthogService.capture("sessionStart", {}); // Start active time tracking telemetryService.startActiveTime(); diff --git a/src/slashCommands.ts b/src/slashCommands.ts index e9e121c11..c2bbc44a5 100644 --- a/src/slashCommands.ts +++ b/src/slashCommands.ts @@ -7,6 +7,7 @@ import { } from "./auth/workos.js"; import { getAllSlashCommands } from "./commands/commands.js"; import { reloadService, SERVICE_NAMES, services } from "./services/index.js"; +import { posthogService } from "./telemetry/posthogService.js"; export async function handleSlashCommands( input: string, @@ -30,14 +31,29 @@ export async function handleSlashCommands( "Available commands:", ...allCommands.map((cmd) => `/${cmd.name} - ${cmd.description}`), ].join("\n"); + posthogService.capture("useSlashCommand", { + name: "help", + }); return { output: helpMessage }; case "clear": + posthogService.capture("useSlashCommand", { + name: "clear", + }); return { clear: true, output: "Chat history cleared" }; case "exit": + posthogService.capture("useSlashCommand", { + name: "exit", + }); return { exit: true, output: "Goodbye!" }; case "config": + posthogService.capture("useSlashCommand", { + name: "config", + }); return { openConfigSelector: true }; case "login": + posthogService.capture("useSlashCommand", { + name: "login", + }); try { const newAuthState = await services.auth.login(); @@ -67,6 +83,9 @@ export async function handleSlashCommands( } case "logout": + posthogService.capture("useSlashCommand", { + name: "logout", + }); try { await services.auth.logout(); @@ -83,6 +102,9 @@ export async function handleSlashCommands( } case "whoami": + posthogService.capture("useSlashCommand", { + name: "whoami", + }); if (isAuthenticated()) { const config = loadAuthConfig(); if (config && isAuthenticatedConfig(config)) { @@ -108,6 +130,9 @@ export async function handleSlashCommands( return { openModelSelector: true }; case "org": + posthogService.capture("useSlashCommand", { + name: "org", + }); // Organization switching command if (args.length === 0) { return { @@ -161,7 +186,6 @@ export async function handleSlashCommands( }; } } - default: const assistantPrompt = assistant.prompts?.find( (prompt) => prompt?.name === command @@ -174,4 +198,4 @@ export async function handleSlashCommands( } } return null; -} \ No newline at end of file +} diff --git a/src/telemetry/posthogService.ts b/src/telemetry/posthogService.ts new file mode 100644 index 000000000..8ea9484f7 --- /dev/null +++ b/src/telemetry/posthogService.ts @@ -0,0 +1,69 @@ +import os from "node:os"; + +import type { PostHog as PostHogType } from "posthog-node"; + +export class PosthogService { + private os: string | undefined; + private uniqueId: string; + + constructor() { + this.os = os.platform(); + this.uniqueId = "NOT_UNIQUE"; + } + + get isEnabled() { + return process.env.CONTINUE_CLI_ENABLE_TELEMETRY !== "0"; + } + + private _client: PostHogType | undefined; + private async getClient() { + if (this.isEnabled) { + if (!this._client) { + const { PostHog } = await import("posthog-node"); + this._client = new PostHog( + "phc_JS6XFROuNbhJtVCEdTSYk6gl5ArRrTNMpCcguAXlSPs", + { + host: "https://app.posthog.com", + } + ); + } + } else { + this._client = undefined; + } + return this._client; + } + + async capture(event: string, properties: { [key: string]: any }) { + const client = await this.getClient(); + if (!client) { + return; + } + + try { + const augmentedProperties = { + ...properties, + os: this.os, + extensionVersion: "", // TODO cn version + ideName: "cn", + ideType: "cli", + }; + const payload = { + distinctId: this.uniqueId, + event, + properties: augmentedProperties, + sendFeatureFlags: true, + }; + + client?.capture(payload); + } catch (e) { + console.error(`Failed to capture event: ${e}`); + } + } + + async shutdown() { + const client = await this.getClient(); + client?.shutdown(); + } +} + +export const posthogService = new PosthogService(); diff --git a/src/ui/TUIChat.tsx b/src/ui/TUIChat.tsx index 749cfaa2c..84eaeecc2 100644 --- a/src/ui/TUIChat.tsx +++ b/src/ui/TUIChat.tsx @@ -1,5 +1,5 @@ -import { Box, Text } from "ink"; -import React, { useEffect, useState } from "react"; +import { Box, Text, useApp, useStdout } from "ink"; +import React, { useEffect, useMemo, useState } from "react"; import { useServices } from "../hooks/useService.js"; import { ApiClientServiceState, @@ -25,6 +25,8 @@ import OrganizationSelector from "./OrganizationSelector.js"; import Timer from "./Timer.js"; import UpdateNotification from "./UpdateNotification.js"; import UserInput from "./UserInput.js"; +import { getGitRemoteUrl, getRepoUrl, isGitRepo } from "../util/git.js"; +import useTerminalSize from "./hooks/useTerminalSize.js"; interface TUIChatProps { // Remote mode props @@ -45,7 +47,29 @@ const TUIChat: React.FC = ({ additionalRules, }) => { // Check if we're in remote mode - const isRemoteMode = !!remoteUrl; + const isRemoteMode = useMemo(() => { + return !!remoteUrl; + }, [remoteUrl]); + + const repoURlText = useMemo(() => { + let url = remoteUrl ?? ""; + if (!url) { + const isGit = isGitRepo(); + if (isGit) { + const gitUrl = getGitRemoteUrl(); + if (gitUrl) { + url = gitUrl; + } + } + } + if (!url) { + url = process.cwd(); + } + + url = url.replace(/\.git$/, ""); + url = url.replace(/^(https|http):\/\/.*?\//, ""); + return url; + }, [remoteUrl]); // Get all services reactively - only in normal mode const { @@ -360,6 +384,11 @@ const TUIChat: React.FC = ({ justifyContent="space-between" alignItems="center" > + + + {repoURlText} + + {!isRemoteMode && services.model?.model && ( = ({ /> )} - + diff --git a/src/ui/UpdateNotification.tsx b/src/ui/UpdateNotification.tsx index 8612b1f14..ffd5669fb 100644 --- a/src/ui/UpdateNotification.tsx +++ b/src/ui/UpdateNotification.tsx @@ -1,24 +1,28 @@ -import { Text } from "ink"; -import React, { useEffect, useState } from "react"; +import { Text, useStdout } from "ink"; +import React, { useEffect, useMemo, useState } from "react"; import { compareVersions, getLatestVersion, getVersion } from "../version.js"; +import useTerminalSize from "./hooks/useTerminalSize.js"; interface UpdateNotificationProps { isRemoteMode?: boolean; } -const UpdateNotification: React.FC = ({ isRemoteMode = false }) => { +const UpdateNotification: React.FC = ({ + isRemoteMode = false, +}) => { const [updateAvailable, setUpdateAvailable] = useState(false); const [latestVersion, setLatestVersion] = useState(""); const [currentVersion] = useState(getVersion()); + const { columns } = useTerminalSize(); useEffect(() => { // Skip update check in test environment - if (process.env.NODE_ENV === 'test') { + if (process.env.NODE_ENV === "test") { return; } - + const abortController = new AbortController(); - + const checkForUpdate = async () => { try { const latest = await getLatestVersion(abortController.signal); @@ -29,7 +33,7 @@ const UpdateNotification: React.FC = ({ isRemoteMode = } } catch (error) { // Silently fail - we don't want to interrupt the user experience - if (error instanceof Error && error.name !== 'AbortError') { + if (error instanceof Error && error.name !== "AbortError") { console.debug("Failed to check for updates:", error); } } @@ -37,13 +41,20 @@ const UpdateNotification: React.FC = ({ isRemoteMode = // Check for updates but don't block checkForUpdate(); - + // Cleanup function to abort the request when component unmounts return () => { abortController.abort(); }; }, [currentVersion]); + const text = useMemo(() => { + if (columns < 75) { + return `v${latestVersion} available`; + } + return `Update available: v${latestVersion} (npm i -g @continuedev/cli)`; + }, [columns, latestVersion]); + if (!updateAvailable) { if (isRemoteMode) { return ◉ Remote Mode; @@ -51,11 +62,7 @@ const UpdateNotification: React.FC = ({ isRemoteMode = return ● Continue CLI; } - return ( - - Update available: v{latestVersion} (npm i -g @continuedev/cli) - - ); + return {text}; }; export default UpdateNotification; diff --git a/src/ui/hooks/useChat.ts b/src/ui/hooks/useChat.ts index 443396b7e..f78d9ed56 100644 --- a/src/ui/hooks/useChat.ts +++ b/src/ui/hooks/useChat.ts @@ -17,6 +17,7 @@ import { formatError } from "../../util/formatError.js"; import logger from "../../util/logger.js"; import { DisplayMessage } from "../types.js"; +import { posthogService } from "../../telemetry/posthogService.js"; interface UseChatProps { assistant?: AssistantUnrolled; @@ -264,18 +265,27 @@ export function useChat({ const handleUserMessage = async (message: string) => { // Special handling for /org command in TUI if (message.trim() === "/org") { + posthogService.capture("useSlashCommand", { + name: "org", + }); onShowOrgSelector(); return; } // Special handling for /config command in TUI if (message.trim() === "/config") { + posthogService.capture("useSlashCommand", { + name: "config", + }); onShowConfigSelector(); return; } // Handle /exit command in remote mode if (isRemoteMode && remoteUrl && message.trim() === "/exit") { + posthogService.capture("useSlashCommand", { + name: "exit", + }); try { // Send POST request to /exit endpoint const response = await fetch(`${remoteUrl}/exit`, { @@ -391,6 +401,10 @@ export function useChat({ // Track user prompt telemetryService.logUserPrompt(message.length, message); + posthogService.capture("chat", { + model: model?.name, + provider: model?.provider, + }); // Add user message to history and display let messageContent = message; diff --git a/src/ui/hooks/useTerminalSize.ts b/src/ui/hooks/useTerminalSize.ts new file mode 100644 index 000000000..41bcbcfd3 --- /dev/null +++ b/src/ui/hooks/useTerminalSize.ts @@ -0,0 +1,46 @@ +import { useEffect, useState } from "react"; +import { useStdout } from "ink"; + +const DEFAULT_ROWS = 24; +const DEFAULT_COLS = 80; + +const useTerminalSize = (debounce = 100) => { + const { stdout } = useStdout(); + const [dimensions, setDimensions] = useState({ + columns: stdout.columns || DEFAULT_COLS, + rows: stdout.rows || DEFAULT_ROWS, + }); + const [isResizing, setIsResizing] = useState(false); + + useEffect(() => { + let debounceTimer: NodeJS.Timeout | null = null; + + const handleResize = () => { + setIsResizing(true); + + if (debounceTimer) { + clearTimeout(debounceTimer); + } + + debounceTimer = setTimeout(() => { + setDimensions({ + columns: stdout.columns || DEFAULT_COLS, + rows: stdout.rows || DEFAULT_ROWS, + }); + setIsResizing(false); + }, debounce); + }; + + stdout.on("resize", handleResize); + return () => { + stdout.removeListener("resize", handleResize); + if (debounceTimer) { + clearTimeout(debounceTimer); + } + }; + }, [stdout, debounce]); + + return { ...dimensions, isResizing }; +}; + +export default useTerminalSize;