mirror of
https://github.com/MoonshotAI/kimi-code.git
synced 2026-12-05 22:04:38 +00:00
feat(vscode): wire the extension into the shared telemetry pipeline (#3852)
This commit is contained in:
parent
1b89e4b039
commit
bbcdde0b13
14 changed files with 505 additions and 25 deletions
5
.changeset/telemetry-set-enabled.md
Normal file
5
.changeset/telemetry-set-enabled.md
Normal file
|
|
@ -0,0 +1,5 @@
|
|||
---
|
||||
"@moonshot-ai/kimi-telemetry": minor
|
||||
---
|
||||
|
||||
Add `setTelemetryEnabled` and an `initiallyEnabled` bootstrap option so hosts can pause and resume telemetry without re-initialization.
|
||||
5
.changeset/vscode-usage-telemetry.md
Normal file
5
.changeset/vscode-usage-telemetry.md
Normal file
|
|
@ -0,0 +1,5 @@
|
|||
---
|
||||
"kimi-code": minor
|
||||
---
|
||||
|
||||
Add anonymous usage telemetry to the VS Code extension, following the VS Code telemetry setting.
|
||||
|
|
@ -290,6 +290,7 @@
|
|||
"@fontsource-variable/inter": "5.2.8",
|
||||
"@moonshot-ai/kimi-code-oauth": "workspace:^",
|
||||
"@moonshot-ai/kimi-code-sdk": "workspace:^",
|
||||
"@moonshot-ai/kimi-telemetry": "workspace:^",
|
||||
"@moonshot-ai/migration-legacy": "workspace:^",
|
||||
"@radix-ui/react-accordion": "^1.2.12",
|
||||
"@tabler/icons-react": "^3.36.0",
|
||||
|
|
|
|||
|
|
@ -9,6 +9,7 @@ import {
|
|||
type LegacyMigrationRunResult,
|
||||
} from "./migration";
|
||||
import { updateLoginContext } from "./utils/context";
|
||||
import { activateExtensionTelemetry, deactivateExtensionTelemetry } from "./telemetry";
|
||||
|
||||
let outputChannel: vscode.OutputChannel | undefined;
|
||||
let provider: KimiWebviewProvider | undefined;
|
||||
|
|
@ -19,7 +20,9 @@ const LEGACY_WARNING_NOTICE_KEY = "kimi.legacyMigration.warningNotice.v1";
|
|||
export async function activate(context: vscode.ExtensionContext): Promise<void> {
|
||||
outputChannel = vscode.window.createOutputChannel("Kimi Code");
|
||||
const remoteInfo = vscode.env.remoteName ? ` (remote: ${vscode.env.remoteName})` : "";
|
||||
log(`Kimi Code ${VSCodeSettings.getExtensionConfig().version} activating${remoteInfo}`);
|
||||
const version = VSCodeSettings.getExtensionConfig().version;
|
||||
log(`Kimi Code ${version} activating${remoteInfo}`);
|
||||
context.subscriptions.push(activateExtensionTelemetry({ version, log }));
|
||||
|
||||
provider = new KimiWebviewProvider(
|
||||
context.extensionUri,
|
||||
|
|
@ -143,8 +146,12 @@ export async function activate(context: vscode.ExtensionContext): Promise<void>
|
|||
|
||||
export async function deactivate(): Promise<void> {
|
||||
log("Kimi Code deactivating");
|
||||
await provider?.shutdown();
|
||||
provider = undefined;
|
||||
try {
|
||||
await provider?.shutdown();
|
||||
} finally {
|
||||
provider = undefined;
|
||||
await deactivateExtensionTelemetry();
|
||||
}
|
||||
}
|
||||
|
||||
function log(message: string): void {
|
||||
|
|
|
|||
|
|
@ -5,6 +5,7 @@ import {
|
|||
type SessionSummary,
|
||||
type ThinkingEffort,
|
||||
} from "@moonshot-ai/kimi-code-sdk";
|
||||
import { setTelemetryContext, track, withTelemetryContext } from "@moonshot-ai/kimi-telemetry";
|
||||
|
||||
import type { RuntimeBroadcast } from "./session-runtime";
|
||||
import {
|
||||
|
|
@ -66,6 +67,11 @@ export class KimiRuntime {
|
|||
platform: "kimi_code_vscode",
|
||||
},
|
||||
uiMode: "vscode",
|
||||
telemetry: {
|
||||
track,
|
||||
withContext: withTelemetryContext,
|
||||
setContext: setTelemetryContext,
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
|
|
|
|||
92
apps/vscode/src/telemetry.ts
Normal file
92
apps/vscode/src/telemetry.ts
Normal file
|
|
@ -0,0 +1,92 @@
|
|||
import * as vscode from "vscode";
|
||||
|
||||
import {
|
||||
createKimiDeviceId,
|
||||
KIMI_CODE_PROVIDER_NAME,
|
||||
KIMI_REGION_PROFILES,
|
||||
resolveKimiRegion,
|
||||
} from "@moonshot-ai/kimi-code-oauth";
|
||||
import {
|
||||
KimiAuthFacade,
|
||||
loadRuntimeConfigSafe,
|
||||
resolveConfigPath,
|
||||
resolveKimiHome,
|
||||
type KimiConfig,
|
||||
} from "@moonshot-ai/kimi-code-sdk";
|
||||
import {
|
||||
initializeTelemetry,
|
||||
setTelemetryEnabled,
|
||||
shouldEnableTelemetry,
|
||||
shutdownTelemetry,
|
||||
track,
|
||||
} from "@moonshot-ai/kimi-telemetry";
|
||||
|
||||
const SHUTDOWN_TIMEOUT_MS = 2000;
|
||||
|
||||
export interface ExtensionTelemetryOptions {
|
||||
readonly version: string;
|
||||
readonly log: (message: string) => void;
|
||||
}
|
||||
|
||||
export function activateExtensionTelemetry(options: ExtensionTelemetryOptions): vscode.Disposable {
|
||||
const homeDir = resolveKimiHome();
|
||||
let firstLaunch = false;
|
||||
const deviceId = createKimiDeviceId(homeDir, {
|
||||
onFirstLaunch: () => {
|
||||
firstLaunch = true;
|
||||
},
|
||||
});
|
||||
const configPath = resolveConfigPath({ homeDir });
|
||||
const config = readTelemetryConfig(configPath);
|
||||
const auth = new KimiAuthFacade({ homeDir, configPath });
|
||||
|
||||
initializeTelemetry({
|
||||
homeDir,
|
||||
deviceId,
|
||||
enabled: config.telemetry !== false,
|
||||
initiallyEnabled: vscode.env.isTelemetryEnabled,
|
||||
appName: "kimi-code-vscode",
|
||||
version: options.version,
|
||||
uiMode: "vscode",
|
||||
model: config.defaultModel,
|
||||
endpoint: () => telemetryEndpoint(homeDir),
|
||||
getAccessToken: async () => (await auth.getCachedAccessToken(KIMI_CODE_PROVIDER_NAME)) ?? null,
|
||||
onUnexpectedError: (error) => options.log(`Telemetry dropped a property: ${error.message}`),
|
||||
});
|
||||
|
||||
const staticallyEnabled = shouldEnableTelemetry({ enabled: config.telemetry !== false });
|
||||
if (firstLaunch) track("first_launch");
|
||||
|
||||
return vscode.env.onDidChangeTelemetryEnabled((enabled) => {
|
||||
if (staticallyEnabled) setTelemetryEnabled(enabled);
|
||||
});
|
||||
}
|
||||
|
||||
export async function deactivateExtensionTelemetry(): Promise<void> {
|
||||
await shutdownTelemetry({ timeoutMs: SHUTDOWN_TIMEOUT_MS });
|
||||
}
|
||||
|
||||
function readTelemetryConfig(
|
||||
configPath: string,
|
||||
): Pick<KimiConfig, "telemetry" | "defaultModel"> {
|
||||
try {
|
||||
const { config, fileError } = loadRuntimeConfigSafe(configPath);
|
||||
if (fileError !== undefined) return {};
|
||||
return config;
|
||||
} catch {
|
||||
return {};
|
||||
}
|
||||
}
|
||||
|
||||
function telemetryEndpoint(homeDir: string): string {
|
||||
const oauth = loadRuntimeConfigSafe(resolveConfigPath({ homeDir })).config.providers?.[
|
||||
KIMI_CODE_PROVIDER_NAME
|
||||
]?.oauth;
|
||||
const region = resolveKimiRegion({
|
||||
configuredOAuthHost: oauth?.oauthHost,
|
||||
configuredOAuthKey: oauth?.key,
|
||||
homeDir,
|
||||
readMarker: process.env["KIMI_CODE_REGION_MARKER"] !== "off",
|
||||
});
|
||||
return KIMI_REGION_PROFILES[region].telemetryEndpoint;
|
||||
}
|
||||
|
|
@ -20,6 +20,7 @@ import type {
|
|||
SessionSummary,
|
||||
ThinkingEffort,
|
||||
} from "@moonshot-ai/kimi-code-sdk";
|
||||
import { setTelemetryContext, track, withTelemetryContext } from "@moonshot-ai/kimi-telemetry";
|
||||
import { describe, expect, it, vi } from "vitest";
|
||||
|
||||
import { Events } from "../shared/bridge";
|
||||
|
|
@ -278,6 +279,11 @@ describe("Kimi runtime (owns shared SDK sessions for Webviews)", () => {
|
|||
platform: "kimi_code_vscode",
|
||||
},
|
||||
uiMode: "vscode",
|
||||
telemetry: {
|
||||
track,
|
||||
withContext: withTelemetryContext,
|
||||
setContext: setTelemetryContext,
|
||||
},
|
||||
});
|
||||
expect(runtime.harness).toBe(sdkFactories.harness as unknown as KimiHarness);
|
||||
await runtime.dispose();
|
||||
|
|
|
|||
212
apps/vscode/test/telemetry.test.ts
Normal file
212
apps/vscode/test/telemetry.test.ts
Normal file
|
|
@ -0,0 +1,212 @@
|
|||
/**
|
||||
* Scenario: the extension host joins the shared v1 telemetry pipeline under a three-layer consent gate.
|
||||
* Responsibilities: initialize the shared client with extension identity, apply the VS Code global
|
||||
* telemetry switch dynamically, emit first_launch on device-id minting, and shut down with a short timeout.
|
||||
* Wiring: the real composition root; VS Code, kimi-telemetry, oauth, and SDK config/auth boundaries are mocked.
|
||||
* Run: pnpm exec vitest run --config apps/vscode/vitest.config.ts test/telemetry.test.ts
|
||||
*/
|
||||
import { beforeEach, describe, expect, it, vi } from "vitest";
|
||||
|
||||
const host = vi.hoisted(() => {
|
||||
const state = {
|
||||
isTelemetryEnabled: true,
|
||||
telemetryListener: undefined as ((enabled: boolean) => void) | undefined,
|
||||
deviceIdFirstLaunch: false,
|
||||
configTelemetry: undefined as boolean | undefined,
|
||||
configModel: "kimi-k2",
|
||||
accessToken: "token-1" as string | null,
|
||||
staticallyEnabled: true,
|
||||
};
|
||||
return {
|
||||
state,
|
||||
createKimiDeviceId: vi.fn((_homeDir: string, options?: { onFirstLaunch?: () => void }) => {
|
||||
if (state.deviceIdFirstLaunch) options?.onFirstLaunch?.();
|
||||
return "device-1";
|
||||
}),
|
||||
initializeTelemetry: vi.fn(),
|
||||
setTelemetryEnabled: vi.fn(),
|
||||
shouldEnableTelemetry: vi.fn(() => host.state.staticallyEnabled),
|
||||
track: vi.fn(),
|
||||
shutdownTelemetry: vi.fn(async () => undefined),
|
||||
installCrashHandlers: vi.fn(),
|
||||
resolveKimiRegion: vi.fn(() => "global" as const),
|
||||
loadRuntimeConfigSafe: vi.fn(() => ({
|
||||
config: {
|
||||
telemetry: host.state.configTelemetry,
|
||||
defaultModel: host.state.configModel,
|
||||
providers: {
|
||||
"managed:kimi-code": { oauth: { key: "oauth/kimi-code-global", oauthHost: "https://auth.kimi.ai" } },
|
||||
},
|
||||
},
|
||||
})),
|
||||
resolveConfigPath: vi.fn(() => "/kimi-home/config.toml"),
|
||||
resolveKimiHome: vi.fn(() => "/kimi-home"),
|
||||
getCachedAccessToken: vi.fn(async () => host.state.accessToken),
|
||||
};
|
||||
});
|
||||
|
||||
vi.mock("vscode", () => ({
|
||||
env: {
|
||||
get isTelemetryEnabled() {
|
||||
return host.state.isTelemetryEnabled;
|
||||
},
|
||||
onDidChangeTelemetryEnabled: vi.fn((listener: (enabled: boolean) => void) => {
|
||||
host.state.telemetryListener = listener;
|
||||
return { dispose: vi.fn() };
|
||||
}),
|
||||
},
|
||||
}));
|
||||
|
||||
vi.mock("@moonshot-ai/kimi-telemetry", () => ({
|
||||
initializeTelemetry: host.initializeTelemetry,
|
||||
setTelemetryEnabled: host.setTelemetryEnabled,
|
||||
shouldEnableTelemetry: host.shouldEnableTelemetry,
|
||||
shutdownTelemetry: host.shutdownTelemetry,
|
||||
track: host.track,
|
||||
installCrashHandlers: host.installCrashHandlers,
|
||||
}));
|
||||
|
||||
vi.mock("@moonshot-ai/kimi-code-oauth", () => ({
|
||||
createKimiDeviceId: host.createKimiDeviceId,
|
||||
KIMI_CODE_PROVIDER_NAME: "managed:kimi-code",
|
||||
KIMI_REGION_PROFILES: {
|
||||
"mainland-cn": { telemetryEndpoint: "https://telemetry-logs.example.com/v1/event" },
|
||||
global: { telemetryEndpoint: "https://telemetry-logs.example.net/v1/event" },
|
||||
},
|
||||
resolveKimiRegion: host.resolveKimiRegion,
|
||||
}));
|
||||
|
||||
vi.mock("@moonshot-ai/kimi-code-sdk", () => ({
|
||||
KimiAuthFacade: class {
|
||||
getCachedAccessToken = host.getCachedAccessToken;
|
||||
},
|
||||
loadRuntimeConfigSafe: host.loadRuntimeConfigSafe,
|
||||
resolveConfigPath: host.resolveConfigPath,
|
||||
resolveKimiHome: host.resolveKimiHome,
|
||||
}));
|
||||
|
||||
import {
|
||||
activateExtensionTelemetry,
|
||||
deactivateExtensionTelemetry,
|
||||
} from "../src/telemetry";
|
||||
|
||||
function activate() {
|
||||
return activateExtensionTelemetry({ version: "1.2.3", log: vi.fn() });
|
||||
}
|
||||
|
||||
function initializeOptions() {
|
||||
const call = host.initializeTelemetry.mock.calls[0]?.[0] as Record<string, unknown> | undefined;
|
||||
if (call === undefined) throw new Error("initializeTelemetry was not called");
|
||||
return call;
|
||||
}
|
||||
|
||||
describe("extension telemetry composition root", () => {
|
||||
beforeEach(() => {
|
||||
host.state.isTelemetryEnabled = true;
|
||||
host.state.telemetryListener = undefined;
|
||||
host.state.deviceIdFirstLaunch = false;
|
||||
host.state.configTelemetry = undefined;
|
||||
host.state.configModel = "kimi-k2";
|
||||
host.state.accessToken = "token-1";
|
||||
host.state.staticallyEnabled = true;
|
||||
vi.clearAllMocks();
|
||||
});
|
||||
|
||||
it("initializes the shared stack with extension identity and the config gate", async () => {
|
||||
activate();
|
||||
|
||||
const options = initializeOptions();
|
||||
expect(options).toMatchObject({
|
||||
homeDir: "/kimi-home",
|
||||
deviceId: "device-1",
|
||||
enabled: true,
|
||||
initiallyEnabled: true,
|
||||
appName: "kimi-code-vscode",
|
||||
version: "1.2.3",
|
||||
uiMode: "vscode",
|
||||
model: "kimi-k2",
|
||||
});
|
||||
expect(options["endpoint"]).toBeTypeOf("function");
|
||||
expect(options["getAccessToken"]).toBeTypeOf("function");
|
||||
await expect((options["getAccessToken"] as () => Promise<string | null>)()).resolves.toBe("token-1");
|
||||
expect(host.shouldEnableTelemetry).toHaveBeenCalledWith({ enabled: true });
|
||||
});
|
||||
|
||||
it("maps config telemetry=false to the static gate", () => {
|
||||
host.state.configTelemetry = false;
|
||||
|
||||
activate();
|
||||
|
||||
expect(initializeOptions()["enabled"]).toBe(false);
|
||||
expect(host.shouldEnableTelemetry).toHaveBeenCalledWith({ enabled: false });
|
||||
});
|
||||
|
||||
it("resolves the endpoint through the region resolver per flush", () => {
|
||||
activate();
|
||||
|
||||
const endpoint = initializeOptions()["endpoint"] as () => string;
|
||||
expect(endpoint()).toBe("https://telemetry-logs.example.net/v1/event");
|
||||
expect(host.resolveKimiRegion).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
configuredOAuthHost: "https://auth.kimi.ai",
|
||||
configuredOAuthKey: "oauth/kimi-code-global",
|
||||
homeDir: "/kimi-home",
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
it("passes the VS Code global switch as the initial intake state", () => {
|
||||
host.state.isTelemetryEnabled = false;
|
||||
|
||||
activate();
|
||||
|
||||
expect(initializeOptions()["initiallyEnabled"]).toBe(false);
|
||||
expect(host.setTelemetryEnabled).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("follows live changes of the VS Code global switch", () => {
|
||||
activate();
|
||||
const listener = host.state.telemetryListener;
|
||||
if (listener === undefined) throw new Error("no telemetry listener registered");
|
||||
|
||||
listener(false);
|
||||
expect(host.setTelemetryEnabled).toHaveBeenLastCalledWith(false);
|
||||
listener(true);
|
||||
expect(host.setTelemetryEnabled).toHaveBeenLastCalledWith(true);
|
||||
});
|
||||
|
||||
it("ignores live changes when the static gates are closed", () => {
|
||||
host.state.staticallyEnabled = false;
|
||||
|
||||
activate();
|
||||
host.state.telemetryListener?.(true);
|
||||
|
||||
expect(host.setTelemetryEnabled).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("emits first_launch when the device id is minted", () => {
|
||||
host.state.deviceIdFirstLaunch = true;
|
||||
|
||||
activate();
|
||||
|
||||
expect(host.track).toHaveBeenCalledWith("first_launch");
|
||||
});
|
||||
|
||||
it("does not emit first_launch for an existing device id", () => {
|
||||
activate();
|
||||
|
||||
expect(host.track).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("never installs crash handlers in the shared extension host", () => {
|
||||
activate();
|
||||
|
||||
expect(host.installCrashHandlers).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("shuts down with a short timeout on deactivate", async () => {
|
||||
await deactivateExtensionTelemetry();
|
||||
|
||||
expect(host.shutdownTelemetry).toHaveBeenCalledWith({ timeoutMs: 2000 });
|
||||
});
|
||||
});
|
||||
|
|
@ -20,6 +20,7 @@ export default defineConfig({
|
|||
plugins: [rawTextPlugin()],
|
||||
alias: {
|
||||
'@moonshot-ai/kimi-code-sdk': resolve(root, '../../packages/node-sdk/src/index.ts'),
|
||||
'@moonshot-ai/kimi-telemetry': resolve(root, '../../packages/telemetry/src/index.ts'),
|
||||
'@moonshot-ai/migration-legacy': resolve(root, '../../packages/migration-legacy/src/index.ts'),
|
||||
'@moonshot-ai/kaos': resolve(root, '../../packages/kaos/src/index.ts'),
|
||||
'@moonshot-ai/kimi-code-oauth': resolve(root, '../../packages/oauth/src/index.ts'),
|
||||
|
|
|
|||
|
|
@ -9,6 +9,7 @@ const TRUE_ENV_VALUES = new Set(['1', 'true', 't', 'yes', 'y']);
|
|||
|
||||
export interface TelemetryBootstrapOptions {
|
||||
readonly enabled?: boolean;
|
||||
readonly initiallyEnabled?: boolean;
|
||||
readonly homeDir: string;
|
||||
readonly deviceId: string;
|
||||
readonly sessionId?: string;
|
||||
|
|
@ -49,11 +50,12 @@ export function initializeTelemetry(options: TelemetryBootstrapOptions): void {
|
|||
const client = getDefaultTelemetryClient();
|
||||
client.setUnexpectedErrorHandler(options.onUnexpectedError ?? null);
|
||||
if (!shouldEnableTelemetry({ enabled: options.enabled })) {
|
||||
client.disable();
|
||||
client.teardown();
|
||||
return;
|
||||
}
|
||||
|
||||
client.enable();
|
||||
const intakeEnabled = options.initiallyEnabled !== false;
|
||||
client.setEnabled(intakeEnabled);
|
||||
client.setContext({
|
||||
deviceId: options.deviceId,
|
||||
sessionId: options.sessionId,
|
||||
|
|
@ -85,5 +87,5 @@ export function initializeTelemetry(options: TelemetryBootstrapOptions): void {
|
|||
client.setSystemMetricsCollector(systemMetricsCollector);
|
||||
systemMetricsCollector.start();
|
||||
|
||||
void sink.retryDiskEvents().catch(() => {});
|
||||
if (intakeEnabled) void sink.retryDiskEvents().catch(() => {});
|
||||
}
|
||||
|
|
|
|||
|
|
@ -76,7 +76,7 @@ export class TelemetryClient {
|
|||
this.queue = [];
|
||||
}
|
||||
|
||||
disable(): void {
|
||||
teardown(): void {
|
||||
this.disabled = true;
|
||||
this.queue = [];
|
||||
this.systemMetricsCollector?.stop();
|
||||
|
|
@ -88,8 +88,12 @@ export class TelemetryClient {
|
|||
}
|
||||
}
|
||||
|
||||
enable(): void {
|
||||
this.disabled = false;
|
||||
setEnabled(enabled: boolean): void {
|
||||
this.disabled = !enabled;
|
||||
if (!enabled) {
|
||||
this.queue = [];
|
||||
this.sink?.clearBuffer();
|
||||
}
|
||||
}
|
||||
|
||||
track(event: string, properties: TelemetryProperties = {}): void {
|
||||
|
|
@ -204,12 +208,12 @@ class ScopedTelemetryClient extends TelemetryClient {
|
|||
this.parent.attachSink(sink);
|
||||
}
|
||||
|
||||
override disable(): void {
|
||||
this.parent.disable();
|
||||
override teardown(): void {
|
||||
this.parent.teardown();
|
||||
}
|
||||
|
||||
override enable(): void {
|
||||
this.parent.enable();
|
||||
override setEnabled(enabled: boolean): void {
|
||||
this.parent.setEnabled(enabled);
|
||||
}
|
||||
|
||||
override track(event: string, properties: TelemetryProperties = {}): void {
|
||||
|
|
@ -251,12 +255,8 @@ export function attachSink(sink: EventSink): void {
|
|||
defaultClient.attachSink(sink);
|
||||
}
|
||||
|
||||
export function disable(): void {
|
||||
defaultClient.disable();
|
||||
}
|
||||
|
||||
export function enable(): void {
|
||||
defaultClient.enable();
|
||||
export function setEnabled(enabled: boolean): void {
|
||||
defaultClient.setEnabled(enabled);
|
||||
}
|
||||
|
||||
export function track(event: string, properties: TelemetryProperties = {}): void {
|
||||
|
|
|
|||
|
|
@ -2,6 +2,7 @@ import {
|
|||
flushSync,
|
||||
getSink,
|
||||
setContext,
|
||||
setEnabled,
|
||||
shutdown,
|
||||
track as trackEvent,
|
||||
withContext,
|
||||
|
|
@ -28,6 +29,10 @@ export function setTelemetryModel(model: string | undefined): void {
|
|||
getSink()?.setModel(model);
|
||||
}
|
||||
|
||||
export function setTelemetryEnabled(enabled: boolean): void {
|
||||
setEnabled(enabled);
|
||||
}
|
||||
|
||||
export function withTelemetryContext(patch: TelemetryContextIds): TelemetryClient {
|
||||
return withContext(patch);
|
||||
}
|
||||
|
|
|
|||
|
|
@ -10,12 +10,17 @@ import { afterEach, describe, expect, it, vi } from 'vitest';
|
|||
import {
|
||||
flushTelemetrySync,
|
||||
initializeTelemetry,
|
||||
setTelemetryEnabled,
|
||||
setTelemetryModel,
|
||||
shutdownTelemetry,
|
||||
track,
|
||||
} from '../src';
|
||||
import { isTelemetryDisabledByEnv } from '../src/bootstrap';
|
||||
import { TelemetryClient, resetDefaultTelemetryClientForTests } from '../src/client';
|
||||
import {
|
||||
getDefaultTelemetryClient,
|
||||
TelemetryClient,
|
||||
resetDefaultTelemetryClientForTests,
|
||||
} from '../src/client';
|
||||
import { installCrashHandlersForClient, setCrashPhase, uninstallCrashHandlers } from '../src/crash';
|
||||
import { EventSink } from '../src/sink';
|
||||
import { SystemMetricsCollector } from '../src/systemMetrics';
|
||||
|
|
@ -158,14 +163,14 @@ describe('TelemetryClient', () => {
|
|||
});
|
||||
});
|
||||
|
||||
it('forwards directly to the attached sink and can be disabled', async () => {
|
||||
it('forwards directly to the attached sink and stops after teardown', async () => {
|
||||
const client = new TelemetryClient();
|
||||
const transport = new RecordingTransport();
|
||||
client.attachSink(makeSink(transport));
|
||||
|
||||
client.track('before_disable');
|
||||
client.disable();
|
||||
client.track('after_disable');
|
||||
client.track('before_teardown');
|
||||
client.teardown();
|
||||
client.track('after_teardown');
|
||||
await client.flush();
|
||||
|
||||
expect(transport.sent).toHaveLength(0);
|
||||
|
|
@ -249,7 +254,7 @@ describe('TelemetryClient', () => {
|
|||
|
||||
client.setSystemMetricsCollector(first);
|
||||
client.setSystemMetricsCollector(second);
|
||||
client.disable();
|
||||
client.teardown();
|
||||
|
||||
expect(first.stop).toHaveBeenCalledTimes(1);
|
||||
expect(second.stop).toHaveBeenCalledTimes(1);
|
||||
|
|
@ -299,6 +304,51 @@ describe('TelemetryClient', () => {
|
|||
expect(event?.timestamp).toBeLessThanOrEqual(Date.now() / 1000);
|
||||
expect(event?.properties).toEqual({});
|
||||
});
|
||||
|
||||
it('drops buffered and incoming events while disabled, then resumes after re-enable', async () => {
|
||||
const client = new TelemetryClient();
|
||||
const transport = new RecordingTransport();
|
||||
client.attachSink(makeSink(transport));
|
||||
client.track('buffered');
|
||||
|
||||
client.setEnabled(false);
|
||||
client.track('during');
|
||||
client.setEnabled(true);
|
||||
client.track('after');
|
||||
await client.flush();
|
||||
|
||||
expect(transport.sent.flat().map((event) => event.event)).toEqual(['after']);
|
||||
});
|
||||
|
||||
it('tolerates repeated enable and disable calls', async () => {
|
||||
const client = new TelemetryClient();
|
||||
const transport = new RecordingTransport();
|
||||
client.attachSink(makeSink(transport));
|
||||
|
||||
client.setEnabled(false);
|
||||
client.setEnabled(false);
|
||||
client.track('during');
|
||||
client.setEnabled(true);
|
||||
client.setEnabled(true);
|
||||
client.track('after');
|
||||
await client.flush();
|
||||
|
||||
expect(transport.sent.flat().map((event) => event.event)).toEqual(['after']);
|
||||
});
|
||||
|
||||
it('toggles the default client through the module-level setter', async () => {
|
||||
const client = getDefaultTelemetryClient();
|
||||
const transport = new RecordingTransport();
|
||||
client.attachSink(makeSink(transport));
|
||||
|
||||
setTelemetryEnabled(false);
|
||||
track('during');
|
||||
setTelemetryEnabled(true);
|
||||
track('after');
|
||||
await client.flush();
|
||||
|
||||
expect(transport.sent.flat().map((event) => event.event)).toEqual(['after']);
|
||||
});
|
||||
});
|
||||
|
||||
describe('SystemMetricsCollector', () => {
|
||||
|
|
@ -944,6 +994,91 @@ describe('telemetry bootstrap', () => {
|
|||
expect(fetchImpl).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('starts paused and skips the disk replay when initiallyEnabled is false', async () => {
|
||||
const homeDir = await tempHome();
|
||||
const telemetryDir = join(homeDir, 'telemetry');
|
||||
mkdirSync(telemetryDir, { recursive: true });
|
||||
const spool = join(telemetryDir, 'failed_retry.jsonl');
|
||||
writeFileSync(spool, `${JSON.stringify(sampleEvent('from_disk'))}\n`);
|
||||
const fetchImpl = vi.fn(async () => new Response('', { status: 200 }));
|
||||
vi.stubGlobal('fetch', fetchImpl);
|
||||
|
||||
initializeTelemetry({
|
||||
homeDir,
|
||||
deviceId: 'dev',
|
||||
appName: 'kimi-code-cli',
|
||||
version: '1.2.3',
|
||||
initiallyEnabled: false,
|
||||
});
|
||||
track('dropped_while_paused');
|
||||
await shutdownTelemetry();
|
||||
|
||||
expect(fetchImpl).not.toHaveBeenCalled();
|
||||
expect(statSync(spool).isFile()).toBe(true);
|
||||
});
|
||||
|
||||
it('drops events queued before initialization when bootstrap starts paused', async () => {
|
||||
const fetchImpl = vi.fn(async () => new Response('', { status: 200 }));
|
||||
vi.stubGlobal('fetch', fetchImpl);
|
||||
|
||||
track('queued_before_init');
|
||||
initializeTelemetry({
|
||||
homeDir: await tempHome(),
|
||||
deviceId: 'dev',
|
||||
appName: 'kimi-code-cli',
|
||||
version: '1.2.3',
|
||||
initiallyEnabled: false,
|
||||
});
|
||||
await shutdownTelemetry();
|
||||
|
||||
expect(fetchImpl).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('resumes intake after a paused start without re-initialization', async () => {
|
||||
const fetchImpl = vi.fn(async () => new Response('', { status: 200 }));
|
||||
vi.stubGlobal('fetch', fetchImpl);
|
||||
|
||||
initializeTelemetry({
|
||||
homeDir: await tempHome(),
|
||||
deviceId: 'dev',
|
||||
appName: 'kimi-code-cli',
|
||||
version: '1.2.3',
|
||||
initiallyEnabled: false,
|
||||
});
|
||||
track('dropped');
|
||||
setTelemetryEnabled(true);
|
||||
track('sent');
|
||||
await shutdownTelemetry();
|
||||
|
||||
expect(fetchImpl).toHaveBeenCalledTimes(1);
|
||||
const init = requestInitFrom(fetchImpl);
|
||||
const payload = JSON.parse(init.body as string) as { events: Array<{ event: string }> };
|
||||
expect(payload.events[0]?.['event']).toBe('kfc_sent');
|
||||
});
|
||||
|
||||
it('replays disk events on bootstrap by default', async () => {
|
||||
const homeDir = await tempHome();
|
||||
const telemetryDir = join(homeDir, 'telemetry');
|
||||
mkdirSync(telemetryDir, { recursive: true });
|
||||
const spool = join(telemetryDir, 'failed_default.jsonl');
|
||||
writeFileSync(spool, `${JSON.stringify(sampleEvent('from_disk'))}\n`);
|
||||
const fetchImpl = vi.fn(async () => new Response('', { status: 200 }));
|
||||
vi.stubGlobal('fetch', fetchImpl);
|
||||
|
||||
initializeTelemetry({
|
||||
homeDir,
|
||||
deviceId: 'dev',
|
||||
appName: 'kimi-code-cli',
|
||||
version: '1.2.3',
|
||||
});
|
||||
await vi.waitFor(() => {
|
||||
expect(fetchImpl).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
await shutdownTelemetry();
|
||||
|
||||
expect(() => statSync(spool)).toThrow();
|
||||
});
|
||||
|
||||
it('queues singleton track calls before initialization, then flushes after bootstrap', async () => {
|
||||
const fetchImpl = vi.fn(async () => new Response('', { status: 200 }));
|
||||
vi.stubGlobal('fetch', fetchImpl);
|
||||
|
|
|
|||
3
pnpm-lock.yaml
generated
3
pnpm-lock.yaml
generated
|
|
@ -313,6 +313,9 @@ importers:
|
|||
'@moonshot-ai/kimi-code-sdk':
|
||||
specifier: workspace:^
|
||||
version: link:../../packages/node-sdk
|
||||
'@moonshot-ai/kimi-telemetry':
|
||||
specifier: workspace:^
|
||||
version: link:../../packages/telemetry
|
||||
'@moonshot-ai/migration-legacy':
|
||||
specifier: workspace:^
|
||||
version: link:../../packages/migration-legacy
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue