Skip to content

armgit / Orkas

Public Imported from GitHub
0

Orkas is an open-source (MIT), local-first AI team for your desktop: a Commander turns your goal into to-dos and coordinates 16 built-in specialist agents plus Claude Code, Codex, OpenCode, OpenClaw and Hermes, with projects, scheduled automations and connectors. Free app for macOS & Windows; built-in models or your own keys.

Remove non-lifecycle analytics from open build

wyt0236b60bc424
diff --git a/src/main/features/connectors/oauth-events.ts b/src/main/features/connectors/oauth-events.ts
index 10189184..6339b2d8 100644
--- a/src/main/features/connectors/oauth-events.ts
+++ b/src/main/features/connectors/oauth-events.ts
@@ -6,10 +6,8 @@ export interface OAuthConnectOutcome {
duration_ms: number;
code?: string;
error?: string;
- /** Sanitized official CLI cause for the local UI only; excluded from logs and analytics. */
+ /** Sanitized official CLI cause for the local UI only; excluded from logs. */
authorization_detail?: string;
- /** Main already queued the canonical terminal with account ownership. */
- telemetry_reported?: boolean;
}
export interface OAuthConnectProgress {
diff --git a/src/main/features/edit_chat_runtime.ts b/src/main/features/edit_chat_runtime.ts
index 3736983a..1f3c3839 100644
--- a/src/main/features/edit_chat_runtime.ts
+++ b/src/main/features/edit_chat_runtime.ts
@@ -36,7 +36,7 @@ export function isEditChatWaitingForInputEvent(event: any): boolean {
}
export function normalizeEditChatRuntimeEvent(event: any): any {
- if (event?.type !== 'event' || event?.event?.stream !== 'agent_run_result') return event;
+ if (event?.type !== 'event' || event?.event?.stream !== 'agent_run_terminal') return event;
const data = event.event.data && typeof event.event.data === 'object'
? event.event.data as Record<string, unknown>
: {};
diff --git a/src/main/features/group_chat/bus.ts b/src/main/features/group_chat/bus.ts
index b7978a58..b54223c9 100644
--- a/src/main/features/group_chat/bus.ts
+++ b/src/main/features/group_chat/bus.ts
@@ -799,9 +799,6 @@ export type GroupEvent =
/** Streaming work belongs to the same numbered reasoning segment as the
* message that eventually persists that segment. */
| { type: 'process'; cid: string; actor: string; turn_id?: string; seg?: number; display_seq?: number; data: Record<string, unknown> }
- /** Low-volume model run telemetry. Emitted live for analytics only; never
- * persisted as process history and never rendered in the process rail. */
- | { type: 'agent_run_result'; cid: string; actor: string; actor_type: 'commander' | 'agent'; turn_id?: string; data: Record<string, unknown> }
/** A `create_artifact` tool call finished writing its bundle. The final
* end-of-turn message still carries `msg.artifacts` for persistence; this
* live event lets the renderer mount the iframe immediately instead of
@@ -825,7 +822,7 @@ export type GroupEvent =
/** Conversation task-board lifecycle (task_board.ts). `task_created` fires
* once when a row enters the board; `task_state` on every deterministic
* status transition (running / waiting_input / done / stopped / failed / cancelled).
- * Distinct from the privacy-safe `taskRun` terminal telemetry above — these
+ * Distinct from the privacy-safe `taskRun` terminal state above — these
* carry the task snapshot for the board UI. */
| { type: 'task_created'; cid: string; task: taskBoard.ConversationTask }
| { type: 'task_state'; cid: string; task: taskBoard.ConversationTask };
@@ -2116,7 +2113,7 @@ export interface EnqueueParams {
/** Renderer-generated id for a user send; persisted verbatim so the
* optimistic bubble can be claimed by identity. See GroupMessage. */
client_msg_id?: string;
- /** Structured source for a user-visible failure. This controls analytics
+ /** Structured source for a user-visible failure. This controls diagnostics
* taxonomy only; the rendered text still controls failure actions/UI. */
failure_kind?: GroupMessageFailureKind;
failure_code?: string;
@@ -2129,7 +2126,7 @@ export interface EnqueueParams {
failedTurnRetryMode?: 'resume' | 'restart';
retrySourceMessageId?: string;
/** Host-computed count of possibly non-idempotent operations whose outcome
- * is unknown. Telemetry-only; never persisted into message content. */
+ * is unknown. Diagnostic-only; never persisted into message content. */
retryUncertainOperationCount?: number;
attachments?: string[];
use_selections?: ChatUseSelection[];
@@ -6053,21 +6050,11 @@ async function runActorTurnWithDisplay(
);
}
log.warn('stream error', { cid, actor: actor.id, aborted, error: logErrorRef(errText) });
- } else if (ev.type === 'event' && (ev.event as { stream?: unknown } | undefined)?.stream === 'agent_run_result') {
+ } else if (ev.type === 'event' && (ev.event as { stream?: unknown } | undefined)?.stream === 'agent_run_terminal') {
const inner = (ev.event as { data?: unknown } | undefined)?.data;
agentRunTimingData = inner && typeof inner === 'object'
? inner as Record<string, unknown>
: undefined;
- if (actor.kind !== 'worker') {
- emit(state, {
- type: 'agent_run_result',
- cid,
- actor: actor.id,
- actor_type: actor.kind === 'commander' ? 'commander' : 'agent',
- turn_id: item.turnId,
- data: inner && typeof inner === 'object' ? (inner as Record<string, unknown>) : {},
- });
- }
} else if (ev.type !== 'done') {
activityEvents += 1;
void touchActivity(uid, cid);
diff --git a/src/main/features/preview_windows.ts b/src/main/features/preview_windows.ts
index af9be35e..7e031c3e 100644
--- a/src/main/features/preview_windows.ts
+++ b/src/main/features/preview_windows.ts
@@ -170,15 +170,9 @@ export function initializePreview(uid: string, sender: WebContents) {
export function closePreview(uid: string, sender: WebContents) { owned(uid, sender).win.destroy(); }
export function setPreviewDirty(uid: string, sender: WebContents, dirty: unknown) { owned(uid, sender).dirty = dirty === true; }
-export function reportPreview(uid: string, sender: WebContents, payload: any) {
+export function notifyPreviewFilesChanged(uid: string, sender: WebContents) {
const r = owned(uid, sender);
- if (payload?.kind === 'files-changed') r.owner.send('preview-windows:report', { kind: 'files-changed' });
- else {
- const report = z.object({ kind: z.literal('telemetry'), method: z.enum(['click', 'event', 'error']),
- action: z.string().min(1).max(128), data: z.record(z.string(), z.unknown()) }).strict().parse(payload);
- if (JSON.stringify(report).length > 16384) return;
- r.owner.send('preview-windows:report', report);
- }
+ r.owner.send('preview-windows:files-changed', {});
}
// Projection stays with the transcript renderer, which owns visibility,
diff --git a/src/main/features/web_assist.ts b/src/main/features/web_assist.ts
index a6f41bda..6628f685 100644
--- a/src/main/features/web_assist.ts
+++ b/src/main/features/web_assist.ts
@@ -32,7 +32,7 @@ import { logErrorRef } from '../util/log-redact';
import { prepareBrowserProxy } from '../util/browser-proxy';
import { withOperationTimeout } from '../util/operation-timeout';
import { prepareWebAssistSession } from './web_assist_session';
-import { reportWebAssistFailure } from './web_assist_diagnostics';
+import { logWebAssistFailure } from './web_assist_diagnostics';
import { registerUserSwitchHook } from './user-switch-hooks';
import {
registerBrowserTab, forgetBrowserTab, retainBrowserTab,
@@ -952,7 +952,7 @@ function ensureTabLoaded(record: WebAssistRecord, tab: WebAssistTabRecord, load
return true;
} catch {
tab.errorCode = 'page_load_failed';
- reportWebAssistFailure(record.owner.webContents, 'view_unavailable');
+ logWebAssistFailure(record.owner.webContents, 'view_unavailable');
emit(record);
return false;
}
@@ -1325,7 +1325,7 @@ function readWebAssistTextCondition(contents: WebContents, text: string, deadlin
function handleLoadFailure(record: WebAssistRecord, tab: WebAssistTabRecord, netCode: number): void {
tab.loading = false;
tab.errorCode = 'page_load_failed';
- reportWebAssistFailure(record.owner.webContents, 'page_load_failed', netCode);
+ logWebAssistFailure(record.owner.webContents, 'page_load_failed', netCode);
emit(record);
}
@@ -1593,14 +1593,14 @@ function mountTab(
contents.on('unresponsive', () => {
if (tab.view !== view) return;
tab.errorCode = 'page_unresponsive';
- reportWebAssistFailure(record.owner.webContents, 'page_unresponsive');
+ logWebAssistFailure(record.owner.webContents, 'page_unresponsive');
emit(record);
});
contents.on('render-process-gone', (_event, details) => {
if (tab.view !== view) return;
tab.loading = false;
tab.errorCode = 'page_load_failed';
- if (details?.reason !== 'clean-exit') reportWebAssistFailure(record.owner.webContents, 'renderer_gone');
+ if (details?.reason !== 'clean-exit') logWebAssistFailure(record.owner.webContents, 'renderer_gone');
emit(record);
});
contents.once('destroyed', () => {
@@ -1696,7 +1696,7 @@ export async function openWebAssist(
records.set(owner.id, record);
createdRecord = true;
} catch (error) {
- reportWebAssistFailure(sender, 'view_unavailable');
+ logWebAssistFailure(sender, 'view_unavailable');
return { ok: false, code: 'view_unavailable', error: 'Web Assist could not be opened.' };
}
}
@@ -1716,7 +1716,7 @@ export async function openWebAssist(
tab = created.tab;
closedTabIds = created.closedTabIds;
} catch (error) {
- reportWebAssistFailure(sender, 'view_unavailable');
+ logWebAssistFailure(sender, 'view_unavailable');
if (createdRecord && !record.tabs.size) closeRecord(record);
return { ok: false, code: 'view_unavailable', error: 'Web Assist could not be opened.' };
}
@@ -1771,7 +1771,7 @@ export function addWebAssistTab(
records.set(owner.id, record);
createdRecord = true;
} catch (error) {
- reportWebAssistFailure(sender, 'view_unavailable');
+ logWebAssistFailure(sender, 'view_unavailable');
return { ok: false, code: 'view_unavailable', error: 'Web Assist could not be opened.' };
}
}
@@ -1783,7 +1783,7 @@ export function addWebAssistTab(
if (!created) return tabLimitFailure();
tab = created.tab;
} catch (error) {
- reportWebAssistFailure(sender, 'view_unavailable');
+ logWebAssistFailure(sender, 'view_unavailable');
if (createdRecord && !record.tabs.size) closeRecord(record);
return { ok: false, code: 'view_unavailable', error: 'Web Assist could not be opened.' };
}
diff --git a/src/main/features/web_assist_diagnostics.ts b/src/main/features/web_assist_diagnostics.ts
index b7ae4a47..9babacf2 100644
--- a/src/main/features/web_assist_diagnostics.ts
+++ b/src/main/features/web_assist_diagnostics.ts
@@ -1,4 +1,4 @@
-/** Low-volume browser incident samples, never page/URL or exception telemetry. */
+/** Low-volume local browser diagnostics, never page/URL or raw exception text. */
import type { WebContents } from 'electron';
import { createLogger } from '../logger';
@@ -18,7 +18,7 @@ export function createWebAssistDiagnostics() {
const last = new Map<Failure, number>();
const suppressed = new Map<Failure, number>();
let emitted: number[] = [];
- return (sender: Pick<WebContents, 'isDestroyed' | 'send'>, failure: Failure, netCode?: unknown): void => {
+ return (sender: Pick<WebContents, 'isDestroyed'>, failure: Failure, netCode?: unknown): void => {
if (!Object.hasOwn(FAILURES, failure) || sender.isDestroyed()) return;
const now = Date.now();
emitted = emitted.filter(time => now - time < WINDOW_MS);
@@ -37,11 +37,10 @@ export function createWebAssistDiagnostics() {
? { net_error_code: netCode } : {}),
};
suppressed.delete(failure);
- // Best effort only: diagnostics must never change navigation or recovery.
+ // Best effort only: local diagnostics must never change navigation or recovery.
try { log.warn('browser failure', payload); } catch { /* no recursive logging */ }
- try { sender.send('web-assist:failure', payload); } catch { /* no queue/retry */ }
};
}
// Shared across tabs, tasks, accounts and windows for this main-process lifetime.
-export const reportWebAssistFailure = createWebAssistDiagnostics();
+export const logWebAssistFailure = createWebAssistDiagnostics();
diff --git a/src/main/index.ts b/src/main/index.ts
index 19bca970..dd935392 100644
--- a/src/main/index.ts
+++ b/src/main/index.ts
@@ -1478,7 +1478,7 @@ if (!gotLock) {
!win.isDestroyed() && win.isFocused()
)),
// Test and packaged-smoke launches use synthetic workspaces and must not
- // write production analytics. Normal source and packaged runs behave alike.
+ // write lifecycle reports. Normal source and packaged runs behave alike.
enabled: !E2E_USER_DATA_DIR && !IS_PACKAGED_LAUNCH_SMOKE,
});
app.once('will-quit', () => {
diff --git a/src/main/ipc/index.ts b/src/main/ipc/index.ts
index 8970ad88..2a5766c0 100644
--- a/src/main/ipc/index.ts
+++ b/src/main/ipc/index.ts
@@ -2207,7 +2207,7 @@ const invokeHandlers: Record<string, InvokeHandler> = {
'previewWindows.ready': async (_payload, ctx) => { previewWindows.readyPreview(ctx.userId, ctx.sender); return {}; },
'previewWindows.replace': async (payload, ctx) => { await previewWindows.replacePreview(ctx.userId, ctx.sender, payload.accepted); return {}; },
'previewWindows.setDirty': async (payload, ctx) => { previewWindows.setPreviewDirty(ctx.userId, ctx.sender, payload.dirty); return {}; },
- 'previewWindows.report': async (payload, ctx) => { previewWindows.reportPreview(ctx.userId, ctx.sender, payload); return {}; },
+ 'previewWindows.filesChanged': async (_payload, ctx) => { previewWindows.notifyPreviewFilesChanged(ctx.userId, ctx.sender); return {}; },
'previewWindows.close': async (_payload, ctx) => { previewWindows.closePreview(ctx.userId, ctx.sender); return {}; },
'previewWindows.requestOwner': async (payload, ctx) => previewWindows.requestPreviewOwner(ctx.userId, ctx.sender, payload),
'previewWindows.resolveOwner': async (payload, ctx) => { previewWindows.resolvePreviewOwner(ctx.sender, payload); return {}; },
@@ -3341,7 +3341,7 @@ const invokeHandlers: Record<string, InvokeHandler> = {
},
// Diagnose a failed <img>/<video> request without returning or reporting a
- // local path. Monitor uses the stable reason to distinguish missing/moved
+ // local path. The stable reason distinguishes missing/moved
// files from unsupported/oversized media and browser decode/stream errors.
'media.diagnose': async ({ url, diagnosticOnly }, ctx) => {
let parsed: URL;
diff --git a/src/main/model/core-agent/client.ts b/src/main/model/core-agent/client.ts
index 0dccd343..f51effbc 100644
--- a/src/main/model/core-agent/client.ts
+++ b/src/main/model/core-agent/client.ts
@@ -41,7 +41,6 @@ import type { ChatOptions, ChatResult, StreamEvent } from '../client';
import {
buildRunner,
type ToolDefSnapshot,
- type ToolSurfaceTelemetrySnapshot,
} from './runner';
import type { SkillSelectionInput } from './skill-registry';
import { mapCoreAgentEvents } from './event-mapper';
@@ -1375,89 +1374,9 @@ export function summarizeModelRunForLog(stats: ModelRunLogDiagnostics, nowMs = D
};
}
-function providerCategoryForTelemetry(providerId?: string): string {
- const text = String(providerId || '').trim().toLowerCase();
- if (!text) return 'unknown';
- const patterns: Array<[string, RegExp]> = [
- ['openai', /\b(openai|chatgpt|gpt)\b/],
- ['anthropic', /\b(anthropic|claude)\b/],
- ['google', /\b(google|gemini|vertex)\b/],
- ['xai', /\b(xai|grok)\b/],
- ['deepseek', /\bdeepseek\b/],
- ['qwen', /\b(qwen|dashscope|aliyun)\b/],
- ['doubao', /\b(doubao|volc|bytedance)\b/],
- ['moonshot', /\b(moonshot|kimi)\b/],
- ['zhipu', /\b(zhipu|glm|zai|z-ai)\b/],
- ['minimax', /\bminimax\b/],
- ['mistral', /\bmistral\b/],
- ['openrouter', /\bopenrouter\b/],
- ['azure', /\bazure\b/],
- ['bedrock', /\bbedrock\b/],
- ['ollama', /\bollama\b/],
- ['lmstudio', /\b(lmstudio|lm-studio)\b/],
- ['siliconflow', /\bsiliconflow\b/],
- ];
- for (const [category, pattern] of patterns) {
- if (pattern.test(text)) return category;
- }
- return 'custom';
-}
-
-function modelFamilyForTelemetry(modelId?: string, providerId?: string): string {
- const providerText = String(providerId || '').trim().toLowerCase();
- const modelText = String(modelId || '').trim().toLowerCase();
- if (!modelText && !providerText) return 'unknown';
- const text = `${providerText} ${modelText}`;
- const patterns: Array<[string, RegExp]> = [
- ['gpt', /\b(gpt|o[1-9]|chatgpt)\b/],
- ['claude', /\bclaude\b/],
- ['gemini', /\bgemini\b/],
- ['grok', /\bgrok\b/],
- ['deepseek', /\bdeepseek\b/],
- ['qwen', /\bqwen\b/],
- ['doubao', /\bdoubao\b/],
- ['kimi', /\b(kimi|moonshot)\b/],
- ['glm', /\b(glm|zhipu)\b/],
- ['minimax', /\bminimax\b/],
- ['mistral', /\bmistral\b/],
- ['mimo', /\bmimo\b/],
- ];
- for (const [family, pattern] of patterns) {
- if (pattern.test(text)) return family;
- }
- return 'other';
-}
-
-export function modelRunIdsForTelemetry(
- activeProviderId?: string,
- activeModelId?: string,
- responseProviderId?: string,
- responseModelId?: string,
-): { providerId: string; modelId: string } {
- const configuredProvider = String(activeProviderId || '').trim();
- const configuredModel = String(activeModelId || '').trim();
- return {
- providerId: String(responseProviderId || '').trim() || configuredProvider,
- modelId: String(responseModelId || '').trim() || configuredModel,
- };
-}
-
-function toolCountBucketForTelemetry(count: number): string {
- const n = Math.max(0, Math.floor(Number.isFinite(count) ? count : 0));
- if (n === 0) return '0';
- if (n <= 5) return '1-5';
- if (n <= 20) return '6-20';
- if (n <= 50) return '21-50';
- return '51+';
-}
-
-function agentRunResultEventForTelemetry(input: {
+function agentRunResultEvent(input: {
status: 'completed' | 'stopped' | 'waiting_input' | 'aborted' | 'idle_timeout' | 'error' | 'empty';
durationMs: number;
- providerId?: string;
- modelId?: string;
- toolCount: number;
- nested: boolean;
idleWindowSec?: number;
idleTimeoutSec?: number;
streamIdleTimeoutSec?: number;
@@ -1475,12 +1394,7 @@ function agentRunResultEventForTelemetry(input: {
const data: Record<string, unknown> = {
result,
terminal_status: input.status,
- provider: providerCategoryForTelemetry(input.providerId),
- model: modelFamilyForTelemetry(input.modelId, input.providerId),
duration_ms: Math.max(0, Math.round(input.durationMs)),
- run_kind: input.nested ? 'nested' : 'top_level',
- has_tools: input.toolCount > 0,
- tool_count_bucket: toolCountBucketForTelemetry(input.toolCount),
};
if (Number.isFinite(input.idleTimeoutSec)) data.idle_timeout_sec = Math.max(0, Math.round(input.idleTimeoutSec || 0));
if (Number.isFinite(input.streamIdleTimeoutSec)) data.stream_idle_timeout_sec = Math.max(0, Math.round(input.streamIdleTimeoutSec || 0));
@@ -1494,7 +1408,7 @@ function agentRunResultEventForTelemetry(input: {
data.other_ms = Math.max(0, Math.round(input.timings.otherMs));
}
if (errorCode) data.error_code = errorCode;
- return { type: 'event', event: { stream: 'agent_run_result', data } };
+ return { type: 'event', event: { stream: 'agent_run_terminal', data } };
}
export function modelTurnContextForLog(input: {
@@ -1860,9 +1774,6 @@ export async function* streamChatWithModel(opts: ChatOptions): AsyncGenerator<St
// produced by an attempted model run; do not replace it with text matching.
let modelRunStarted = false;
let runnerBuildStarted = false;
- let activeProviderId = '';
- let activeModelId = '';
- let activeToolCount = 0;
try {
log.info('model turn queued', turnLogContext);
const sessionLockWaitStartedAt = Date.now();
@@ -1995,7 +1906,6 @@ export async function* streamChatWithModel(opts: ChatOptions): AsyncGenerator<St
providerId,
modelId,
toolSurfaceMode,
- toolSurfaceTelemetry,
resolvedSystemPrompt,
turnEphemeral,
profileId,
@@ -2006,9 +1916,6 @@ export async function* streamChatWithModel(opts: ChatOptions): AsyncGenerator<St
agentDisplayNameById,
connectorDisplayNameById,
} = built;
- activeProviderId = providerId || '';
- activeModelId = modelId || '';
- activeToolCount = toolDefs.length;
turnLogContext = modelTurnContextForLog({
userId,
sessionId,
@@ -2393,19 +2300,9 @@ export async function* streamChatWithModel(opts: ChatOptions): AsyncGenerator<St
// A handed-off model invocation completed normally; task
// completion remains owned by the host's queued Agent run.
: (finalText || agentRunResult?.meta.termination?.status === 'handed_off' ? 'completed' : 'empty'))));
- const telemetryIds = modelRunIdsForTelemetry(
- activeProviderId,
- activeModelId,
- diagnostics.provider,
- diagnostics.model,
- );
- yield agentRunResultEventForTelemetry({
+ yield agentRunResultEvent({
status: terminalStatus,
durationMs: Date.now() - runStartedAt,
- providerId: telemetryIds.providerId,
- modelId: telemetryIds.modelId,
- toolCount: activeToolCount,
- nested,
idleWindowSec: idleHit ? idleHitWindow : undefined,
idleTimeoutSec: idleTimeout,
streamIdleTimeoutSec: streamIdleTimeout,
diff --git a/src/main/model/core-agent/runner.ts b/src/main/model/core-agent/runner.ts
index 64248c05..a08d2dc6 100644
--- a/src/main/model/core-agent/runner.ts
+++ b/src/main/model/core-agent/runner.ts
@@ -438,20 +438,6 @@ export interface ToolDefSnapshot {
source: 'core-agent' | 'orkas' | 'extra';
}
-/** Run-local tool-surface counters. Raw group ids remain inside main and are
- * reduced to bounded counts/buckets before analytics emission. */
-export interface ToolSurfaceTelemetrySnapshot {
- mode: 'scoped' | 'legacy_all' | 'unknown';
- peakToolCount: number;
- loadCallCount: number;
- loadedGroupCount: number;
- /** Provider-definition characters added specifically by model tool_load
- * calls. Host-granted runtime tools are excluded. */
- loadedSchemaChars: number;
- loadedUnusedGroupCount: number;
- webToolUsed: boolean;
-}
-
/** Exported for unit tests — see runner.test.ts. */
export const _splitCommanderOrchestrationBlock = splitCommanderOrchestrationBlock;
@@ -473,9 +459,6 @@ export async function buildRunner(params: BuildRunnerParams): Promise<{
modelId: string;
/** Actual activation mode after rollout, eligibility, and history-compat checks. */
toolSurfaceMode: 'scoped' | 'legacy_all';
- /** Snapshot current run-local loading/usage counters at the terminal
- * boundary. No tool/group names leave the main process. */
- toolSurfaceTelemetry(usedToolNames?: readonly string[]): ToolSurfaceTelemetrySnapshot;
/** Final tool set visible to the LLM (after last-write-wins merge of
* core-agent builtins + buildRunner-injected + caller-supplied extras).
* Used by the dev-only archiver. */
@@ -1662,7 +1645,7 @@ export async function buildRunner(params: BuildRunnerParams): Promise<{
// This is the same active-definition path used by AgentRunner immediately
// before an ordinary provider request. Reading it after construction keeps
- // diagnostics, the dev archive, tests, and telemetry aligned with late core
+ // diagnostics, the dev archive, and tests aligned with late core
// tools without serializing dormant schemas.
const snapshotToolDefinition = (definition: {
name: string;
@@ -1677,34 +1660,6 @@ export async function buildRunner(params: BuildRunnerParams): Promise<{
const toolDefs = runner.getActiveToolDefinitions()
.map(snapshotToolDefinition)
.sort((a, b) => a.name.localeCompare(b.name));
- const toolSurfaceTelemetry = (
- usedToolNames: readonly string[] = [],
- ): ToolSurfaceTelemetrySnapshot => {
- const used = new Set(usedToolNames);
- const currentToolDefs = runner.getActiveToolDefinitions();
- const stats = toolSurface.runtimeStats();
- const toolLoadActivatedNames = new Set(stats.newlyActivatedToolNames);
- const loadedToolDefs = currentToolDefs.filter((tool) => toolLoadActivatedNames.has(tool.name));
- return {
- mode: toolSurface.mode,
- peakToolCount: currentToolDefs.length,
- loadCallCount: stats.loadCalls,
- loadedGroupCount: stats.newlyLoadedGroups.length,
- loadedSchemaChars: loadedToolDefs.reduce(
- (total, tool) => total + JSON.stringify({
- name: tool.name,
- description: tool.description,
- inputSchema: tool.inputSchema,
- }).length,
- 0,
- ),
- loadedUnusedGroupCount: stats.newlyLoadedGroups.filter((group) => (
- !toolNamesForGroups([group]).some((name) => used.has(name))
- )).length,
- webToolUsed: used.has('web_search') || used.has('web_fetch') || used.has('inner_browser'),
- };
- };
-
return {
runner,
failureTrackingScope: session,
@@ -1715,7 +1670,6 @@ export async function buildRunner(params: BuildRunnerParams): Promise<{
providerId,
modelId,
toolSurfaceMode: toolSurface.mode,
- toolSurfaceTelemetry,
toolDefs,
skillDisplayNameById,
skillMetadataByReadRef,
diff --git a/src/main/preload.js b/src/main/preload.js
index 42b0520c..f9bcfcfe 100644
--- a/src/main/preload.js
+++ b/src/main/preload.js
@@ -113,7 +113,7 @@ function logRecord(record) {
// a known prefix list so the renderer can't tap into arbitrary internal IPC traffic.
const PUSH_EVENT_CHANNELS = new Set([
'preview-windows:owner-request',
- 'preview-windows:report',
+ 'preview-windows:files-changed',
'preview-windows:close-request',
'preview-windows:replace-request',
'preview-windows:gallery-refresh',
diff --git a/src/renderer/modules/agents.js b/src/renderer/modules/agents.js
index f437e849..31fb15b4 100644
--- a/src/renderer/modules/agents.js
+++ b/src/renderer/modules/agents.js
@@ -1,19 +1,4 @@
const _agentsLog = createLogger('agents');
-// ─── Agents (three-column: list / detail / inline edit chat) ───
-
-function _agentsTrackClick(action, data) {
- try { if (window.Monitor) (() => {})(action, data || {}); } catch (_) {}
-}
-
-function _agentsTrackEvent(action, data) {
- void action;
- void data;
-}
-
-function _agentsTrackError(action, data) {
- void action;
- void data;
-}
function _agentManageErrorCode(value, fallback = 'operation_failed') {
const message = String((value && value.message) || '').trim();
@@ -855,21 +840,17 @@ function renderAgentsGrid(agents) {
* success, refreshes the grid + detail page. */
async function _flipAgentEnabled(agentId, nextEnabled) {
if (_isCommanderAgent(agentId)) return false;
- const trackResult = _createAgentManageTracker('toggle');
let res;
try {
res = await window.orkas.invoke('agents.setEnabled', { agent_id: agentId, enabled: nextEnabled });
} catch (err) {
- trackResult('failure', 'invoke_failed');
await uiAlert(t('component.toggle_failed'));
return false;
}
if (!res || !res.ok) {
- trackResult('failure', 'update_failed');
await uiAlert(t('component.toggle_failed'));
return false;
}
- trackResult('success');
const cached = _agentsCache?.find((a) => a.agent_id === agentId);
if (cached) cached.enabled = nextEnabled;
try {
@@ -883,24 +864,6 @@ async function _flipAgentEnabled(agentId, nextEnabled) {
return true;
}
-function _createAgentManageTracker(action) {
- const startedAt = Date.now();
- let done = false;
- return (result, errorCode = '') => {
- if (done) return;
- done = true;
- const payload = {
- result,
- action,
- duration_ms: Math.max(0, Date.now() - startedAt),
- };
- if (result !== 'success') payload.error_code = errorCode || 'unknown';
- try {
- if (window.Monitor) Monitor.event('agent_manage_result', payload);
- } catch (_) {}
- };
-}
-
// ─── View switching: entry page ↔ detail ────────────────────────────────
function _normalizeAgentDetailReturnTarget(target) {
@@ -1332,24 +1295,20 @@ function _renderAgentHeaderCategory(agent) {
value: agent?.category || 'general',
readonly: isMock,
onChange: async (category, api) => {
- const trackResult = _createAgentManageTracker('edit');
try {
const res = await window.orkas.invoke('agents.update', {
agent_id: agentId,
updates: { category: category || 'general' },
});
if (!res || !res.ok) {
- trackResult('failure', _agentManageErrorCode(res, 'update_failed'));
api.setValue(agent?.category || 'general');
uiAlert((res && res.error) || t('agents.update_failed'));
return;
}
- trackResult('success');
agent.category = res.agent?.category || category || 'general';
await loadAgents(true);
if (_selectedAgent?.id === agentId && !_agentEditing) await selectAgent(agentId);
} catch (err) {
- trackResult('failure', _agentManageErrorCode(err, 'invoke_failed'));
api.setValue(agent?.category || 'general');
uiAlert((err && err.message) || t('agents.update_failed'));
}
@@ -1453,7 +1412,6 @@ function _canEnterAgentEditMode(agent) {
async function _saveAgentTextList(agent, key, values) {
if (!agent || !_canEditAgentDefinition(agent)) return false;
- const trackResult = _createAgentManageTracker('edit');
const clean = [];
const seen = new Set();
for (const raw of Array.isArray(values) ? values : []) {
@@ -1469,16 +1427,13 @@ async function _saveAgentTextList(agent, key, values) {
updates: { [key]: clean },
});
if (!res || !res.ok) {
- trackResult('failure', _agentManageErrorCode(res, 'update_failed'));
await uiAlert((res && res.error) || t('agents.update_failed'));
return false;
}
- trackResult('success');
await loadAgents(true);
await _refreshAgentDetail(agent.agent_id);
return true;
} catch (err) {
- trackResult('failure', _agentManageErrorCode(err, 'invoke_failed'));
await uiAlert((err && err.message) || t('agents.update_failed'));
return false;
}
@@ -1674,19 +1629,15 @@ function _wireAgentMemoryControls(host, agent) {
: window.prompt(label, '');
const text = (content || '').trim();
if (!text) return;
- const trackResult = _createAgentManageTracker('edit');
try {
const res = await _agentMemoryAdd(agent, text);
if (!res || res.ok === false) {
- trackResult('failure', _agentManageErrorCode(res, 'memory_add_failed'));
uiAlert((res && res.error) || _agentLabel('agents.memory_update_failed', '记忆更新失败', 'Memory update failed', 'メモリ更新に失敗しました'));
return;
}
- trackResult('success');
await loadAgents(true);
await _refreshAgentDetail(agent.agent_id);
} catch (err) {
- trackResult('failure', _agentManageErrorCode(err, 'memory_add_failed'));
uiAlert((err && err.message) || _agentLabel('agents.memory_update_failed', '记忆更新失败', 'Memory update failed', 'メモリ更新に失敗しました'));
}
});
@@ -1702,19 +1653,15 @@ function _wireAgentMemoryControls(host, agent) {
: window.prompt(label, oldText);
const text = (content || '').trim();
if (!text || text === oldText) return;
- const trackResult = _createAgentManageTracker('edit');
try {
const res = await _agentMemoryUpdate(agent, oldText, text);
if (!res || res.ok === false) {
- trackResult('failure', _agentManageErrorCode(res, 'memory_update_failed'));
uiAlert((res && res.error) || _agentLabel('agents.memory_update_failed', '记忆更新失败', 'Memory update failed', 'メモリ更新に失敗しました'));
return;
}
- trackResult('success');
await loadAgents(true);
await _refreshAgentDetail(agent.agent_id);
} catch (err) {
- trackResult('failure', _agentManageErrorCode(err, 'memory_update_failed'));
uiAlert((err && err.message) || _agentLabel('agents.memory_update_failed', '记忆更新失败', 'Memory update failed', 'メモリ更新に失敗しました'));
}
});
@@ -1733,19 +1680,15 @@ function _wireAgentMemoryControls(host, agent) {
})
: false;
if (!ok) return;
- const trackResult = _createAgentManageTracker('edit');
try {
const res = await _agentMemoryRemove(agent, text);
if (!res || res.ok === false) {
- trackResult('failure', _agentManageErrorCode(res, 'memory_remove_failed'));
uiAlert((res && res.error) || _agentLabel('agents.memory_update_failed', '记忆更新失败', 'Memory update failed', 'メモリ更新に失敗しました'));
return;
}
- trackResult('success');
await loadAgents(true);
await _refreshAgentDetail(agent.agent_id);
} catch (err) {
- trackResult('failure', _agentManageErrorCode(err, 'memory_remove_failed'));
uiAlert((err && err.message) || _agentLabel('agents.memory_update_failed', '记忆更新失败', 'Memory update failed', 'メモリ更新に失敗しました'));
}
});
@@ -1955,25 +1898,20 @@ function _renderAgentOutputFormatSection(agent, editing = false) {
options,
value: current,
onChange: async (val) => {
- const trackResult = _createAgentManageTracker('edit');
try {
const res = await window.orkas.invoke('agents.update', {
agent_id: agent.agent_id,
updates: { output_format: val },
});
if (!res || !res.ok) {
- trackResult('failure', _agentManageErrorCode(res, 'update_failed'));
api.setValue(current);
uiAlert((res && res.error) || t('agents.update_failed'));
} else if (res.agent) {
agent.output_format = res.agent.output_format;
current = val;
- trackResult('success');
} else {
- trackResult('failure', 'invalid_response');
}
} catch (err) {
- trackResult('failure', _agentManageErrorCode(err, 'invoke_failed'));
api.setValue(current);
uiAlert((err && err.message) || t('agents.update_failed'));
}
@@ -2119,13 +2057,11 @@ async function _renderAgentDetailRuntime(agent) {
updates.description_en = next2.description_en;
}
}
- const trackResult = _createAgentManageTracker('edit');
try {
const res = await window.orkas.invoke('agents.update', {
agent_id: agent.agent_id, updates,
});
if (res?.ok && res.agent) {
- trackResult('success');
_agentsCache = null;
const fetched = await apiFetch(`/api/agents/${encodeURIComponent(agent.agent_id)}`);
const data = await fetched.json();
@@ -2141,7 +2077,6 @@ async function _renderAgentDetailRuntime(agent) {
agent_id: agent.agent_id, updates: safeUpdates,
});
if (!fallback?.ok) throw new Error(fallback?.code || 'update_failed');
- trackResult('success');
_agentsCache = null;
const fetched = await apiFetch(`/api/agents/${encodeURIComponent(agent.agent_id)}`);
const data = await fetched.json();
@@ -2151,7 +2086,6 @@ async function _renderAgentDetailRuntime(agent) {
throw new Error(res?.code || 'update_failed');
}
} catch (err) {
- trackResult('failure', _agentManageErrorCode(err, 'update_failed'));
}
},
});
@@ -2429,7 +2363,6 @@ async function _renderAgentDetailCliSettings(agent, { refresh = false, cacheOnly
}
};
const saveRuntime = async (patch) => {
- const trackResult = _createAgentManageTracker('edit');
try {
const nextRuntime = { ...runtime, ...patch };
if (!nextRuntime.model_override) delete nextRuntime.model_override;
@@ -2440,7 +2373,6 @@ async function _renderAgentDetailCliSettings(agent, { refresh = false, cacheOnly
updates: { runtime: nextRuntime },
});
if (!saved?.agent) throw new Error(saved?.code || t('agents.update_failed'));
- trackResult('success');
if (!_mergeAgentIntoCache(saved.agent)) {
// Detail normally opens from the registry, so this is only a cold-cache
// fallback. Await it before returning control to the composer.
@@ -2448,7 +2380,6 @@ async function _renderAgentDetailCliSettings(agent, { refresh = false, cacheOnly
}
_renderAgentDetail(saved.agent, _agentEditing);
} catch (error) {
- trackResult('failure', _agentManageErrorCode(error, 'update_failed'));
throw error;
}
};
@@ -2596,26 +2527,21 @@ async function _renderAgentDetailProjectDir(agent) {
const resetBtn = slot.querySelector('[data-act="reset"]');
const pick = async () => {
if (!canEdit) return;
- let trackResult = null;
try {
const picked = await window.orkas.invoke('common.pickDirectory', {
title: t('agents.label_project_dir'),
});
if (!picked || picked.cancelled || !picked.path) return;
- trackResult = _createAgentManageTracker('edit');
const saved = await window.orkas.invoke('agents.cliProjectDir.set', {
agent_id: agent.agent_id,
path: picked.path,
});
if (!saved || !saved.ok) {
- trackResult('failure', _agentManageErrorCode(saved, 'project_dir_save_failed'));
await uiAlert((saved && saved.error) || t('agents.project_dir_save_failed'));
return;
}
renderInfo(saved.info);
- trackResult('success');
} catch (err) {
- if (trackResult) trackResult('failure', _agentManageErrorCode(err, 'project_dir_save_failed'));
await uiAlert((err && err.message) || t('agents.project_dir_save_failed'));
}
};
@@ -2623,21 +2549,17 @@ async function _renderAgentDetailProjectDir(agent) {
resetBtn?.addEventListener('click', async (e) => {
e.stopPropagation();
if (!canEdit) return;
- const trackResult = _createAgentManageTracker('edit');
try {
const saved = await window.orkas.invoke('agents.cliProjectDir.set', {
agent_id: agent.agent_id,
path: '',
});
if (!saved || !saved.ok) {
- trackResult('failure', _agentManageErrorCode(saved, 'project_dir_save_failed'));
await uiAlert((saved && saved.error) || t('agents.project_dir_save_failed'));
return;
}
renderInfo(saved.info);
- trackResult('success');
} catch (err) {
- trackResult('failure', _agentManageErrorCode(err, 'project_dir_save_failed'));
await uiAlert((err && err.message) || t('agents.project_dir_save_failed'));
}
});
@@ -2694,7 +2616,6 @@ function _renderAgentDetailAvatar(agent) {
agent.icon = nextIcon;
agent.color = next.color;
applyAvatarToElement(trigger, nextIcon, next.color, agent.agent_id);
- const trackResult = _createAgentManageTracker('edit');
try {
if (isCommander) {
const res = await window.orkas.invoke('prefs.setCommanderAvatar', { icon: nextIcon, color: next.color });
@@ -2716,9 +2637,7 @@ function _renderAgentDetailAvatar(agent) {
if (_agentsCache) renderAgentsList(_agentsCache);
} else throw new Error(res?.code || 'avatar_update_failed');
}
- trackResult('success');
} catch (err) {
- trackResult('failure', _agentManageErrorCode(err, 'avatar_update_failed'));
}
});
});
@@ -2985,7 +2904,7 @@ function _switchAgentTab(tab) {
// CLI discovery is process-heavy and belongs only to the External flow.
// Start it when that panel actually becomes visible, not whenever the
// default in-process create modal opens.
- if (tab === 'external') _trackExternalAgentFlowEnter();
+ if (tab === 'external')
if (tab === 'external' && typeof mountExternalCliSelect === 'function') {
mountExternalCliSelect((cli) => _applyExternalCliDefaults(cli)).catch(() => {});
}
@@ -3002,8 +2921,6 @@ let _agentModalEntryPoint = '';
let _agentModalSourceView = '';
let _agentModalReturnTarget = null;
let _agentModalOpenedAt = 0;
-let _agentModalHadExternalSubmitAttempt = false;
-let _agentModalExternalFlowEntered = false;
let _externalAgentCreateAvailable = false;
let _agentModalActiveTab = 'create';
@@ -3022,37 +2939,6 @@ function setExternalAgentCreateAvailability(available) {
}
window.setExternalAgentCreateAvailability = setExternalAgentCreateAvailability;
-function _trackExternalAgentFlowEnter() {
- if (_agentModalExternalFlowEntered) return;
- _agentModalExternalFlowEntered = true;
- try {
- if (window.Monitor) Monitor.event('agent_create_flow_enter', {
- agent_type: 'cli',
- entry_point: _agentModalEntryPoint,
- source_view: _agentModalSourceView,
- });
- } catch (_) {}
-}
-
-function _trackAgentCreateBlocked({
- agentType,
- startedAt,
- errorCode,
- cli = '',
-}) {
- if (!window.Monitor) return;
- const payload = {
- result: 'blocked',
- agent_type: agentType,
- duration_ms: Math.round(Math.max(0, performance.now() - startedAt)),
- error_code: errorCode,
- };
- if (cli) payload.cli = cli;
- try {
- Monitor.event('agent_create_result', payload);
- } catch (_) {}
-}
-
/** Decide whether a current `name` value still counts as "the default
* for `defaultName`" — meaning a CLI swap should overwrite it. We
* recognise the bare default plus the dedup-style suffixes a user
@@ -3127,8 +3013,6 @@ function openAgentModal(options = {}) {
: '';
_agentModalReturnTarget = _captureAgentDetailReturnTarget();
_agentModalOpenedAt = performance.now();
- _agentModalHadExternalSubmitAttempt = false;
- _agentModalExternalFlowEntered = false;
_externalAgentCreateAvailable = false;
const modal = document.getElementById('agent-modal');
const msgEl = document.getElementById('agent-form-msg');
@@ -3182,8 +3066,6 @@ function closeAgentModal(options = {}) {
_agentModalReturnFocusId = '';
document.getElementById('agent-modal').classList.remove('open');
_agentModalOpenedAt = 0;
- _agentModalHadExternalSubmitAttempt = false;
- _agentModalExternalFlowEntered = false;
_agentModalEntryPoint = '';
_agentModalSourceView = '';
_agentModalReturnTarget = null;
@@ -3194,13 +3076,9 @@ function closeAgentModal(options = {}) {
}
window.closeAgentModal = closeAgentModal;
-function _trackExternalAgentCreateCancel() {
- // Analytics is intentionally disabled in the open-source build.
-}
-
function cancelAgentModal() {
const activeTab = document.querySelector('#agent-modal-tabs .is-active')?.dataset.agentTab || 'create';
- if (activeTab === 'external') _trackExternalAgentCreateCancel();
+ if (activeTab === 'external')
closeAgentModal({ restoreFocus: true });
}
window.cancelAgentModal = cancelAgentModal;
@@ -3215,7 +3093,6 @@ window.saveAgentModal = saveAgentModal;
async function _saveCreateAgent({ msgEl }) {
const startedAt = performance.now();
- let terminalResultTracked = false;
const rawName = document.getElementById('agent-name-input').value;
const name = rawName.trim();
const description = document.getElementById('agent-desc-input').value.trim();
@@ -3223,11 +3100,6 @@ async function _saveCreateAgent({ msgEl }) {
msgEl.textContent = t('agents.input_name_needed');
msgEl.className = 'form-msg err';
document.getElementById('agent-name-input').focus();
- _trackAgentCreateBlocked({
- agentType: 'default',
- startedAt,
- errorCode: 'no_name',
- });
return;
}
const hasWhitespace = /\s/.test(rawName);
@@ -3236,33 +3108,18 @@ async function _saveCreateAgent({ msgEl }) {
msgEl.textContent = t('agents.name_invalid');
msgEl.className = 'form-msg err';
document.getElementById('agent-name-input').focus();
- _trackAgentCreateBlocked({
- agentType: 'default',
- startedAt,
- errorCode: 'name_invalid',
- });
return;
}
if (reserved) {
msgEl.textContent = t('agents.name_reserved');
msgEl.className = 'form-msg err';
document.getElementById('agent-name-input').focus();
- _trackAgentCreateBlocked({
- agentType: 'default',
- startedAt,
- errorCode: 'name_reserved',
- });
return;
}
if (!description) {
msgEl.textContent = t('agents.input_desc_needed');
msgEl.className = 'form-msg err';
document.getElementById('agent-desc-input').focus();
- _trackAgentCreateBlocked({
- agentType: 'default',
- startedAt,
- errorCode: 'no_desc',
- });
return;
}
@@ -3280,31 +3137,8 @@ async function _saveCreateAgent({ msgEl }) {
if (!data.ok || !data.agent) {
msgEl.textContent = _agentCreateErrorMessage(data) || t('agents.create_failed');
msgEl.className = 'form-msg err';
- terminalResultTracked = true;
- if (window.Monitor) {
- (() => {})('agent_create_result', {
- result: 'failure',
- agent_type: 'default',
- duration_ms: Math.round(performance.now() - startedAt),
- error_code: data.code || '',
- });
- (() => {})('agent_create', {
- agent_type: 'default',
- output_format: outputFormat,
- error_type: 'api',
- error_code: data.code || '',
- error_message: data.error || 'unknown',
- });
- }
return;
}
- terminalResultTracked = true;
- if (window.Monitor) (() => {})('agent_create_result', {
- result: 'success',
- agent_id: data.agent.agent_id,
- agent_type: 'default',
- duration_ms: Math.round(performance.now() - startedAt),
- });
const detailReturnTarget = _agentModalReturnTarget;
closeAgentModal();
await loadAgents(true);
@@ -3315,26 +3149,11 @@ async function _saveCreateAgent({ msgEl }) {
} catch (e) {
msgEl.textContent = t('agents.network_error', { reason: e.message || e });
msgEl.className = 'form-msg err';
- if (window.Monitor && !terminalResultTracked) {
- (() => {})('agent_create_result', {
- result: 'failure',
- agent_type: 'default',
- duration_ms: Math.round(performance.now() - startedAt),
- });
- (() => {})('agent_create', {
- agent_type: 'default',
- output_format: outputFormat,
- error_type: 'network',
- error_message: e.message || String(e),
- });
- }
}
}
async function _saveExternalAgent({ msgEl }) {
const startedAt = performance.now();
- _agentModalHadExternalSubmitAttempt = true;
- let terminalResultTracked = false;
const cli = (typeof getExternalCliValue === 'function') ? getExternalCliValue() : null;
const cliWarning = (typeof getExternalCliSelectionWarning === 'function')
? getExternalCliSelectionWarning()
@@ -3355,34 +3174,17 @@ async function _saveExternalAgent({ msgEl }) {
if (!cli) {
msgEl.textContent = t('agents.ext_cli_needed');
msgEl.className = 'form-msg err';
- _trackAgentCreateBlocked({
- agentType: 'cli',
- startedAt,
- errorCode: 'no_cli',
- });
return;
}
if (cliWarning) {
msgEl.textContent = cliWarning;
msgEl.className = 'form-msg err';
- _trackAgentCreateBlocked({
- agentType: 'cli',
- startedAt,
- errorCode: 'cli_version_too_old',
- cli,
- });
return;
}
if (!name) {
msgEl.textContent = t('agents.input_name_needed');
msgEl.className = 'form-msg err';
nameEl.focus();
- _trackAgentCreateBlocked({
- agentType: 'cli',
- startedAt,
- errorCode: 'no_name',
- cli,
- });
return;
}
const hasWhitespace = /\s/.test(rawName);
@@ -3391,36 +3193,18 @@ async function _saveExternalAgent({ msgEl }) {
msgEl.textContent = t('agents.name_invalid');
msgEl.className = 'form-msg err';
nameEl.focus();
- _trackAgentCreateBlocked({
- agentType: 'cli',
- startedAt,
- errorCode: 'name_invalid',
- cli,
- });
return;
}
if (reserved) {
msgEl.textContent = t('agents.name_reserved');
msgEl.className = 'form-msg err';
nameEl.focus();
- _trackAgentCreateBlocked({
- agentType: 'cli',
- startedAt,
- errorCode: 'name_reserved',
- cli,
- });
return;
}
if (!desc) {
msgEl.textContent = t('agents.input_desc_needed');
msgEl.className = 'form-msg err';
descEl.focus();
- _trackAgentCreateBlocked({
- agentType: 'cli',
- startedAt,
- errorCode: 'no_desc',
- cli,
- });
return;
}
@@ -3453,33 +3237,8 @@ async function _saveExternalAgent({ msgEl }) {
if (!data.ok || !data.agent) {
msgEl.textContent = _agentCreateErrorMessage(data) || t('agents.create_failed');
msgEl.className = 'form-msg err';
- terminalResultTracked = true;
- if (window.Monitor) {
- (() => {})('agent_create_result', {
- result: 'failure',
- agent_type: 'cli',
- cli,
- duration_ms: Math.round(performance.now() - startedAt),
- error_code: data.code || '',
- });
- (() => {})('agent_create', {
- agent_type: 'cli',
- cli,
- error_type: 'api',
- error_code: data.code || '',
- error_message: data.error || 'unknown',
- });
- }
return;
}
- terminalResultTracked = true;
- if (window.Monitor) (() => {})('agent_create_result', {
- result: 'success',
- agent_id: data.agent.agent_id,
- agent_type: 'cli',
- cli,
- duration_ms: Math.round(performance.now() - startedAt),
- });
const detailReturnTarget = _agentModalReturnTarget;
closeAgentModal();
await loadAgents(true);
@@ -3490,20 +3249,6 @@ async function _saveExternalAgent({ msgEl }) {
} catch (e) {
msgEl.textContent = t('agents.network_error', { reason: e.message || e });
msgEl.className = 'form-msg err';
- if (window.Monitor && !terminalResultTracked) {
- (() => {})('agent_create_result', {
- result: 'failure',
- agent_type: 'cli',
- cli,
- duration_ms: Math.round(performance.now() - startedAt),
- });
- (() => {})('agent_create', {
- agent_type: 'cli',
- cli,
- error_type: 'network',
- error_message: e.message || String(e),
- });
- }
}
}
@@ -3723,9 +3468,6 @@ async function useAgent(agentId) {
if (_isAgentProfileMock(agentId)) return;
if (_isCommanderAgent(agentId)) {
_agentsLog.info('use commander');
- _agentsTrackClick('agent_use', {
- agent_id: _COMMANDER_AGENT_ID,
- });
setView('new-chat');
if (typeof setChatRecipient === 'function') setChatRecipient('new-chat', { kind: 'commander' });
if (typeof setChatUseSelection === 'function') setChatUseSelection('new-chat', null, { focus: false });
@@ -3743,9 +3485,6 @@ async function useAgent(agentId) {
if (agent.enabled === false) return;
_agentsLog.info('use agent', { agent_id: agentId });
- _agentsTrackClick('agent_use', {
- agent_id: agentId,
- });
setView('new-chat');
setChatRecipient('new-chat', {
@@ -3772,9 +3511,6 @@ async function useSkill(skillId, skillName, skillSource) {
// Skill "use" flow: navigate to the new-chat page with the skill
// pre-selected and wait for user input.
_agentsLog.info('use skill', { skill_id: skillId, skill_name: skillName || skillId });
- _agentsTrackClick('skill_use', {
- skill_id: skillId,
- });
setView('new-chat');
if (typeof setChatRecipient === 'function') {
setChatRecipient('new-chat', { kind: 'commander' });
@@ -4098,11 +3834,6 @@ async function _openAgentPicker(anchorBtn, entryPoint = 'unknown') {
_closeOtherComposerPopovers('recipient');
}
if (anchorBtn.id === 'new-chat-recipient-chip') {
- _agentsTrackClick('new_chat_recipient_picker_open', {
- entry_point: entryPoint === 'recipient_chip' || entryPoint === 'at_key'
- ? entryPoint
- : 'unknown',
- });
}
const previousAnchorId = picker.dataset.anchorId || '';
if (previousAnchorId && previousAnchorId !== anchorBtn.id) {
@@ -4693,17 +4424,9 @@ function _targetFromPickerAnchor(anchorId) {
async function _triggerPickerItem(kind, itemId, itemName, anchorId, dataset, sourceType = 'unknown') {
const target = _targetFromPickerAnchor(anchorId);
if (target === 'new-chat') {
- _agentsTrackClick('new_chat_recipient_picker_select', {
- resource_kind: ['agent', 'skill', 'connector', 'library'].includes(kind) ? kind : 'unknown',
- source_type: sourceType === 'mouse' || sourceType === 'keyboard' ? sourceType : 'unknown',
- });
}
if (kind === 'skill') {
const skillId = String(itemId || itemName || '');
- _agentsTrackClick(target === 'auto' ? 'auto_skill_select' : 'chat_skill_select', {
- target,
- skill_id: skillId,
- });
_consumeAtKeyChar();
setChatSkill(target, itemId, itemName || itemId);
const inputId = target === 'new-chat'
@@ -4773,11 +4496,6 @@ async function _triggerLibraryFile(dataset, anchorId) {
? { projectId, name: rel }
: { relPath: rel };
const inputId = _libraryPickerInputIdForTarget(target);
- const telemetry = {
- target,
- scope,
- has_project: scope === 'project' && !!projectId,
- };
try {
await window.attachKbFileToDraft(
channel,
@@ -4788,7 +4506,6 @@ async function _triggerLibraryFile(dataset, anchorId) {
else if (target === 'project' && projectId && typeof setView === 'function') setView('project', projectId);
},
);
- _agentsTrackEvent('chat_library_attach_result', { ...telemetry, result: 'success' });
_consumeAtKeyChar();
_focusInput(document.getElementById(inputId));
} catch (err) {
@@ -4797,14 +4514,7 @@ async function _triggerLibraryFile(dataset, anchorId) {
? err.failure_stage : 'picker_finalize';
const failure_kind = ['not_found', 'permission_denied', 'disk_full'].includes(err && err.failure_kind)
? err.failure_kind : 'operation_failed';
- const diagnostic = { failure_stage, failure_kind, telemetry_version: 3 };
- _agentsTrackEvent('chat_library_attach_result', { ...telemetry, ...diagnostic, result: 'failure' });
- _agentsTrackError('chat_library_attach', {
- ...telemetry,
- error_type: 'operation',
- error_message: 'library_attach_failed',
- ...diagnostic,
- });
+ _agentsLog.warn('library attachment failed', { target, scope, failure_stage, failure_kind });
if (typeof uiAlert === 'function') await uiAlert(t('agent_picker.library_attach_failed', { reason }));
}
}
@@ -4822,11 +4532,6 @@ async function _triggerAgent(agentId, agentName, anchorId) {
? { kind: 'commander' }
: { kind: 'agent', id: agentId, name: agentName || agentId };
const resourceAgentId = rec.kind === 'commander' ? _COMMANDER_AGENT_ID : String(agentId || '');
- _agentsTrackClick('auto_agent_select', {
- target: 'auto',
- recipient_type: rec.kind,
- agent_id: rec.kind === 'agent' ? String(agentId || '') : '',
- });
if (typeof window !== 'undefined' && typeof window._autoOnRecipientPicked === 'function') {
window._autoOnRecipientPicked(rec);
}
@@ -5009,11 +4714,6 @@ function bindAgentPickers() {
e.stopPropagation();
const anchorId = document.getElementById('agent-picker')?.dataset.anchorId || '';
_closeAgentPicker();
- _agentsTrackClick('agent_create_open', {
- entry_point: 'agent_picker_connect_cli',
- source_view: typeof currentView === 'string' ? currentView : '',
- agent_type: 'cli',
- });
if (typeof openAgentModal !== 'function') return;
openAgentModal({
initialTab: 'external',
diff --git a/src/renderer/modules/auto-events.js b/src/renderer/modules/auto-events.js
index 54e179a9..429ea7ea 100644
--- a/src/renderer/modules/auto-events.js
+++ b/src/renderer/modules/auto-events.js
@@ -40,15 +40,12 @@ function _autoEventsOpenSubscription() {
const activeUserId = _autoEventsActiveUserId();
if (!activeUserId || inner.user_id !== activeUserId) return;
_autoEventsRetryAttempt = 0;
- if (inner.type === 'fire_failed') {
- // Main reports the reliable privacy-safe telemetry terminal. This
- // stream only refreshes visible state and must never duplicate it.
- } else if (inner.type === 'conv_created') {
+ if (inner.type === 'conv_created') {
if (typeof loadConversations === 'function') {
Promise.resolve(loadConversations())
.catch(() => _autoEventsLog.warn('reload after fire failed'));
}
- } else {
+ } else if (inner.type !== 'fire_failed') {
return;
}
if (typeof _autoLoadedOnce !== 'undefined' && _autoLoadedOnce && typeof loadAutoList === 'function') {
diff --git a/src/renderer/modules/auto.js b/src/renderer/modules/auto.js
index e7b898f2..e3f6641f 100644
--- a/src/renderer/modules/auto.js
+++ b/src/renderer/modules/auto.js
@@ -21,14 +21,6 @@ const _autoLog = (typeof createLogger === 'function')
? createLogger('auto')
: { info() {}, warn() {}, error() {} };
-function _autoTrackClick(action, data) {
- try { if (window.Monitor) (() => {})(action, data || {}); } catch (_) {}
-}
-
-function _autoTrackEvent(action, data) {
- try { if (window.Monitor) (() => {})(action, data || {}); } catch (_) {}
-}
-
function _autoLogFailure(action, data) {
_autoLog.warn('automation operation failed', { action, ...(data || {}) });
}
@@ -114,19 +106,6 @@ function _autoAttachmentPayload(files, source) {
};
}
-function _autoTrackAttachmentResult(payload, startedAt, result, counts, failure = null) {
- const eventPayload = {
- ...payload,
- result,
- ...counts,
- duration_ms: Math.max(0, Math.round(performance.now() - startedAt)),
- };
- if (failure && (result === 'failure' || result === 'partial_failure')) {
- Object.assign(eventPayload, failure);
- }
- _autoTrackEvent('auto_attachment_upload_result', eventPayload);
-}
-
const AUTO_ATTACH_ACCEPT = (typeof CHAT_ATTACH_ACCEPT !== 'undefined' && Array.isArray(CHAT_ATTACH_ACCEPT))
? CHAT_ATTACH_ACCEPT
: [
@@ -835,8 +814,7 @@ function _closeAutoRowMenu(restoreFocus = false) {
if (restoreFocus && anchor && anchor.isConnected) anchor.focus();
}
-function _autoCreateActionTracker(action) {
- const startedAt = Date.now();
+function _autoCreateActionLogger(action) {
let done = false;
return (result, errorCode = '') => {
if (done) return;
@@ -844,16 +822,12 @@ function _autoCreateActionTracker(action) {
const payload = {
result,
action,
- duration_ms: Math.max(0, Date.now() - startedAt),
};
if (result !== 'success') {
const failure = _autoResultFailure(errorCode, 'action_failed', 'ipc');
payload.error_code = failure.error_code;
payload.error_type = failure.error_type;
}
- try {
- if (window.Monitor) Monitor.event('auto_task_action_result', payload);
- } catch (_) {}
if (result === 'failure') {
_autoLogFailure('auto_task_action', {
action,
@@ -903,37 +877,37 @@ function _openAutoRowMenu(anchorBtn, task, opts) {
}
} else if (action === 'toggle-enabled') {
const next = !task.enabled;
- const trackResult = _autoCreateActionTracker('toggle');
+ const logResult = _autoCreateActionLogger('toggle');
try {
const res = await window.orkas.invoke('autoTasks.setEnabled', { taskId: task.id, enabled: next });
if (res && res.ok && res.task) {
- trackResult('success');
+ logResult('success');
Object.assign(task, res.task);
const row = document.querySelector(`.auto-row[data-task-id="${task.id}"]`);
if (row) row.classList.toggle('is-disabled', !next);
if (opts && typeof opts.afterChange === 'function') opts.afterChange();
} else {
- trackResult('failure', 'update_failed');
+ logResult('failure', 'update_failed');
}
} catch (err) {
- trackResult('failure', 'invoke_failed');
+ logResult('failure', 'invoke_failed');
_autoLog.warn('toggle failed', err);
}
} else if (action === 'edit') {
if (opts && typeof opts.onEdit === 'function') opts.onEdit(task);
} else if (action === 'delete') {
if (!(await uiConfirm(t('auto.delete_confirm')))) return;
- const trackResult = _autoCreateActionTracker('delete');
+ const logResult = _autoCreateActionLogger('delete');
try {
const res = await window.orkas.invoke('autoTasks.delete', { taskId: task.id });
if (res && res.deleted) {
- trackResult('success');
+ logResult('success');
if (opts && typeof opts.afterChange === 'function') opts.afterChange();
} else {
- trackResult('failure', 'delete_failed');
+ logResult('failure', 'delete_failed');
}
} catch (err) {
- trackResult('failure', 'invoke_failed');
+ logResult('failure', 'invoke_failed');
await uiAlert(t('auto.delete_failed', { reason: (err && err.message) || err }));
}
}
@@ -1863,30 +1837,15 @@ async function _autoPrepareUploadFiles(fileList) {
async function _autoUploadFiles(files, source = 'drop') {
const list = Array.from(files || []);
if (!list.length) return;
- const startedAt = performance.now();
const payload = _autoAttachmentPayload(list, source);
const taskId = await _ensureAutoDraftId();
if (!taskId) {
- _autoTrackAttachmentResult(payload, startedAt, 'failure', {
- uploaded_count: 0,
- failed_count: list.length,
- rejected_count: 0,
- }, _autoResultFailure('no_draft_id', 'upload_failed', 'ipc'));
await uiAlert(t('auto.save_failed', { reason: 'no_draft_id' }));
return;
}
const { prepared, rejected } = await _autoPrepareUploadFiles(list);
const rejectedCount = rejected.length;
if (!prepared.length) {
- _autoTrackAttachmentResult(payload, startedAt, 'failure', {
- uploaded_count: 0,
- failed_count: rejected.length || list.length,
- rejected_count: rejectedCount,
- }, _autoResultFailure(
- rejected.length ? 'file_prepare_failed' : 'no_valid_files',
- 'file_prepare_failed',
- 'operation',
- ));
if (rejected.length) await _autoAlertAttachmentFailures(rejected);
return;
}
@@ -1948,11 +1907,6 @@ async function _autoUploadFiles(files, source = 'drop') {
const uploadedCount = Math.max(0, placeholders.length - uploadFailed);
const failedCount = rejected.length;
const result = failedCount ? (uploadedCount ? 'partial_failure' : 'failure') : 'success';
- _autoTrackAttachmentResult(payload, startedAt, result, {
- uploaded_count: uploadedCount,
- failed_count: failedCount,
- rejected_count: rejectedCount,
- }, failedCount ? _autoResultFailure('upload_failed', 'upload_failed') : null);
if (rejected.length) await _autoAlertAttachmentFailures(rejected);
}
@@ -2001,11 +1955,6 @@ async function _autoImportPaths(entries, source = 'internal_drop') {
const payload = _autoAttachmentPayload(files, source);
const taskId = await _ensureAutoDraftId();
if (!taskId) {
- _autoTrackAttachmentResult(payload, startedAt, 'failure', {
- uploaded_count: 0,
- failed_count: files.length,
- rejected_count: 0,
- }, _autoResultFailure('no_draft_id', 'upload_failed', 'ipc'));
await uiAlert(t('auto.save_failed', { reason: 'no_draft_id' }));
return;
}
@@ -2063,11 +2012,6 @@ async function _autoImportPaths(entries, source = 'internal_drop') {
}));
const uploadedCount = Math.max(0, placeholders.length - uploadFailed);
const result = rejected.length ? (uploadedCount ? 'partial_failure' : 'failure') : 'success';
- _autoTrackAttachmentResult(payload, startedAt, result, {
- uploaded_count: uploadedCount,
- failed_count: rejected.length,
- rejected_count: rejectedCount,
- }, rejected.length ? _autoResultFailure('upload_failed', 'upload_failed') : null);
if (rejected.length) await _autoAlertAttachmentFailures(rejected);
}
@@ -2077,7 +2021,7 @@ async function _autoAttachLibraryFile(ref) {
const rel = String(ref && ref.rel || '');
const projectId = _autoValidProjectId(ref && ref.projectId || '');
if (!rel) return;
- const telemetry = {
+ const operationContext = {
scope,
mode: _autoEditingTaskId ? 'edit' : 'create',
has_project: !!projectId,
@@ -2115,22 +2059,10 @@ async function _autoAttachLibraryFile(ref) {
attachedName = name;
} catch (err) {
const failure = _autoResultFailure(err, 'library_attach_failed');
- _autoLogFailure('auto_library_attach', { ...telemetry, ...failure });
- _autoTrackEvent('auto_library_attach_result', {
- ...telemetry,
- result: 'failure',
- duration_ms: Math.max(0, Math.round(performance.now() - startedAt)),
- ...failure,
- });
+ _autoLogFailure('auto_library_attach', { ...operationContext, ...failure });
try { _autoReplaceAttachmentByTempId(tempId, null); } catch (_) {}
throw err;
}
-
- _autoTrackEvent('auto_library_attach_result', {
- ...telemetry,
- result: 'success',
- duration_ms: Math.max(0, Math.round(performance.now() - startedAt)),
- });
try {
_autoReplaceAttachmentByTempId(tempId, {
name: attachedName,
@@ -2149,12 +2081,6 @@ async function _autoPickAndUploadFiles() {
const payload = _autoAttachmentPayload([], 'picker');
const taskId = await _ensureAutoDraftId();
if (!taskId) {
- _autoTrackAttachmentResult(payload, startedAt, 'failure', {
- file_count: 0,
- uploaded_count: 0,
- failed_count: 1,
- rejected_count: 0,
- }, _autoResultFailure('no_draft_id', 'upload_failed', 'ipc'));
await uiAlert(t('auto.save_failed', { reason: 'no_draft_id' }));
return;
}
@@ -2163,12 +2089,6 @@ async function _autoPickAndUploadFiles() {
data = await window.orkas.invoke('autoTasks.attachments.pickAndUpload', { taskId });
} catch (err) {
_autoLog.warn('native picker upload failed', err);
- _autoTrackAttachmentResult(payload, startedAt, 'failure', {
- file_count: 0,
- uploaded_count: 0,
- failed_count: 1,
- rejected_count: 0,
- }, _autoResultFailure(err, 'upload_failed', 'ipc'));
await uiAlert(t('chat.attach_upload_fail', {
name: '',
reason: (err && err.message) || t('chat.attach_upload_generic_fail'),
@@ -2176,12 +2096,6 @@ async function _autoPickAndUploadFiles() {
return;
}
if (data && data.cancelled === true) {
- _autoTrackAttachmentResult(payload, startedAt, 'cancelled', {
- file_count: 0,
- uploaded_count: 0,
- failed_count: 0,
- rejected_count: 0,
- });
return;
}
const names = Array.isArray(data && data.items) ? data.items : [];
@@ -2193,12 +2107,6 @@ async function _autoPickAndUploadFiles() {
const failure = result === 'success'
? null
: _autoResultFailure(failed[0] && failed[0].error, 'upload_failed', 'operation');
- _autoTrackAttachmentResult(payload, startedAt, result, {
- uploaded_count: names.length,
- failed_count: failed.length,
- rejected_count: 0,
- file_count: fileCount,
- }, failure);
for (const name of names) {
_autoPushReadyAttachment(name, { displayName: name });
}
@@ -2557,35 +2465,10 @@ async function _autoSubmitForm() {
const isUpdate = !!_autoEditingTaskId;
const readyAttachments = _autoCurrentAttachments
.filter((a) => a && a.name && a.status !== 'error' && a.status !== 'uploading');
- const startedAt = performance.now();
- const resultContext = {
- schedule_type: type,
- recipient_type: _autoCurrentRecipient.kind === 'agent' ? 'agent' : 'commander',
- has_skill: !!skillField,
- has_connector: !!connectorField,
- has_project: !!projectId,
- attachment_count: readyAttachments.length,
- content_length: content.length,
- };
- const resultEventName = isUpdate ? 'auto_task_update_result' : 'auto_task_create_result';
- let terminalRecorded = false;
- const trackSaveResult = (result, failure = null) => {
- if (terminalRecorded) return;
- terminalRecorded = true;
- _autoTrackEvent(resultEventName, {
- result,
- ...resultContext,
- duration_ms: Math.max(0, Math.round(performance.now() - startedAt)),
- ...(failure || {}),
- });
- };
- const blockSave = async (errorCode, messageKey) => {
- trackSaveResult('blocked', _autoResultFailure(errorCode, errorCode, 'validation'));
+ let operationCompleted = false;
+ const blockSave = async (_errorCode, messageKey) => {
await uiAlert(t(messageKey));
};
- // Create remains the canonical funnel-intent click. Updates intentionally
- // use only their terminal result, including client-side validation blocks.
- if (!isUpdate) _autoTrackClick('auto_task_create_submit', resultContext);
if (!content) {
await blockSave('invalid_content', 'auto.invalid_content');
@@ -2714,7 +2597,6 @@ async function _autoSubmitForm() {
}
} catch (err) {
const failure = _autoResultFailure(err, 'invoke_failed', 'ipc');
- trackSaveResult('failure', failure);
_autoLogFailure(isUpdate ? 'auto_task_update' : 'auto_task_create', failure);
await uiAlert(t('auto.save_failed', { reason: (err && err.message) || err }));
return;
@@ -2722,13 +2604,12 @@ async function _autoSubmitForm() {
if (!res || !res.task) {
const fallback = isUpdate ? 'update_failed' : 'create_failed';
const failure = _autoResultFailure(res && res.error, fallback, 'api');
- trackSaveResult('failure', failure);
_autoLogFailure(isUpdate ? 'auto_task_update' : 'auto_task_create', failure);
await uiAlert(t('auto.save_failed', { reason: (res && res.error) || '' }));
return;
}
const savedTask = res.task;
- trackSaveResult('success');
+ operationCompleted = true;
const savedCb = _autoOnSaved;
try { _hideAutoDialog(); } catch (err) { _autoLog.warn('close after automation save failed', err); }
try { _autoResetForm(); } catch (err) { _autoLog.warn('reset after automation save failed', err); }
@@ -2743,10 +2624,9 @@ async function _autoSubmitForm() {
try { savedCb(savedTask); } catch (_) { /* ignore */ }
}
} catch (err) {
- if (!terminalRecorded) {
+ if (!operationCompleted) {
const fallback = isUpdate ? 'update_failed' : 'create_failed';
const failure = _autoResultFailure(err, fallback, 'operation');
- trackSaveResult('failure', failure);
_autoLogFailure(isUpdate ? 'auto_task_update' : 'auto_task_create', failure);
await uiAlert(t('auto.save_failed', { reason: (err && err.message) || err }));
} else {
diff --git a/src/renderer/modules/bash_permission.js b/src/renderer/modules/bash_permission.js
index 0b15c7c9..f1191bb8 100644
--- a/src/renderer/modules/bash_permission.js
+++ b/src/renderer/modules/bash_permission.js
@@ -22,96 +22,6 @@ const _CLI_PERMISSION_POLICIES = ['inherit', 'ask', 'full_access'];
const _BASH_PERMISSION_RISK_CATEGORIES = ['network_egress', 'destructive', 'priv_esc', 'sensitive_path', 'system_package_change', 'external_mutation'];
const _BASH_IRREVERSIBLE_ACTIONS = ['recursive_delete', 'untargeted_process_kill'];
-function _bashPermissionVisibilityState() {
- try {
- if (typeof document !== 'undefined' && typeof document.visibilityState === 'string') {
- if (document.visibilityState !== 'visible') return 'hidden';
- if (typeof document.hasFocus === 'function') {
- return document.hasFocus() ? 'visible_focused' : 'visible_unfocused';
- }
- return 'visible_unknown_focus';
- }
- } catch (_) { /* fall through */ }
- return 'unknown';
-}
-
-function _bashPermissionTelemetry(name, properties) {
- try {
- if (window.Monitor) Monitor.event(name, properties);
- } catch (_) { /* permission delivery must not depend on observability */ }
-}
-
-function _bashPermissionCategories(info) {
- const reasons = Array.isArray(info && info.reasons) ? info.reasons : [];
- return [...new Set(reasons.filter((reason) => _BASH_PERMISSION_RISK_CATEGORIES.includes(reason)))].join('|');
-}
-
-// Whether the new-in-auto-mode gate is doing useful work or only adding
-// clicks is only answerable if the verdict carries the finding that caused it.
-// Same closed-world/pipe-joined shape as `categories`; no path or command.
-function _bashPermissionIrreversible(info) {
- const list = Array.isArray(info && info.irreversible) ? info.irreversible : [];
- return [...new Set(list.filter((a) => _BASH_IRREVERSIBLE_ACTIONS.includes(a)))].join('|');
-}
-
-function _bashPermissionReceivedAt(info, fallback = Date.now()) {
- const value = Number(info && info._renderer_received_at_ms);
- return Number.isFinite(value) && value > 0 ? value : fallback;
-}
-
-function _bashTrackCancelledPermission(info, currentMode, errorCode = 'request_cancelled') {
- const approved = _bashPermTaskApproved.delete(info.request_id);
- _bashTrackPermissionResult(info, {
- result: approved ? 'success' : 'cancelled',
- decision: approved ? 'allow_run' : 'none',
- effective_decision: approved ? 'allow_run' : 'deny',
- ...(currentMode ? { mode: currentMode } : {}),
- mode_changed: false,
- categories: _bashPermissionCategories(info),
- ...(_bashPermissionIrreversible(info) ? { irreversible: _bashPermissionIrreversible(info) } : {}),
- duration_ms: Math.max(0, Date.now() - _bashPermissionReceivedAt(info)),
- ...(approved ? {} : { error_type: 'state', error_code: errorCode }),
- });
-}
-
-function _bashTrackPermissionResult(info, properties) {
- if (info._permission_kind === 'web-assist') {
- // Page origin and control label are user content: report the handback
- // reason and the verdict, which is what tells us whether this gate is
- // catching real intent or only adding clicks.
- _bashPermissionTelemetry('web_assist_action_confirmation_result', {
- reason: String(info.reason || ''),
- control_kind: String(info.control_kind || ''),
- decision: properties.effective_decision === 'deny' ? 'denied' : 'approved',
- ...(properties.decision ? { requested_decision: properties.decision } : {}),
- result: properties.result,
- duration_ms: properties.duration_ms,
- });
- return;
- }
- if (info._permission_kind === 'connector') {
- // Custom MCP ids derive from a user-authored display name and their tool
- // names are server-defined free text: report the stable `custom` bucket and
- // omit the tool name (same coarsening as connectors.js `_connectorTrackPayload`).
- const rawConnectorId = String(info.connector_id || '');
- const customConnector = rawConnectorId.startsWith('custom-');
- _bashPermissionTelemetry('connector_action_confirmation_result', {
- connector_id: customConnector ? 'custom' : rawConnectorId,
- ...(customConnector ? {} : { tool_name: String(info.tool_name || '') }),
- risk: info.risk || '',
- sensitive_operation: info.sensitive_operation || '',
- decision: properties.effective_decision === 'deny' ? 'denied' : 'approved',
- result: properties.result,
- duration_ms: properties.duration_ms,
- ...((typeof window.getOnboardingTelemetryContext === 'function')
- ? window.getOnboardingTelemetryContext(info.cid)
- : {}),
- });
- return;
- }
- _bashPermissionTelemetry('bash_risk_prompt_result', properties);
-}
-
function _bashIsMode(mode) {
return _BASH_PERMISSION_MODES.includes(mode);
}
@@ -266,7 +176,6 @@ function _showBashPermissionModeDialog({
detailsLabel,
currentMode,
requestId,
- onPresented,
allowRun = true,
allowRunLabel = t('bash.permission.allow_run'),
showModeControl = true,
@@ -332,8 +241,6 @@ function _showBashPermissionModeDialog({
</div>
`;
document.body.appendChild(overlay);
- try { if (typeof onPresented === 'function') onPresented(); } catch (_) { /* telemetry only */ }
-
const selectedMode = () => {
return modeValidator(selectedModeValue) ? selectedModeValue : safeCurrentMode;
};
@@ -473,10 +380,9 @@ function _webAssistActionMessage(info) {
}
async function _showBashPermissionDialog(info) {
- const startedAt = Date.now();
const requestId = String(info.request_id || '');
if (_bashPermCancelled.delete(requestId)) {
- _bashTrackCancelledPermission(info, null);
+ _bashPermTaskApproved.delete(info.request_id);
return;
}
const isConnector = info._permission_kind === 'connector';
@@ -501,7 +407,7 @@ async function _showBashPermissionDialog(info) {
const currentMode = await _getBashPermissionCurrentMode();
if (_bashPermCancelled.delete(requestId)) {
- _bashTrackCancelledPermission(info, currentMode);
+ _bashPermTaskApproved.delete(info.request_id);
return;
}
// Needs the resolved mode: the same step is worth flagging in every mode,
@@ -511,7 +417,6 @@ async function _showBashPermissionDialog(info) {
_bashIrreversibleText(info, currentMode),
externalMutationText,
].filter(Boolean).join('\n\n');
- let presented = false;
const isSensitiveApproval = isConnector || isWebAssist || (Array.isArray(info.reasons)
&& info.reasons.some((reason) => _BASH_PERMISSION_RISK_CATEGORIES.includes(reason)));
// A page grant is safe to offer: the host binds it to this tab, origin and
@@ -523,7 +428,6 @@ async function _showBashPermissionDialog(info) {
// An earlier queued permission can switch the account to Trusted while this
// connector waits. Its host gate already checked availability/prohibitions.
let result;
- let dialogFailed = false;
try {
result = isConnector && currentMode === 'all_files_auto'
? { choice: 'allow_once', mode: currentMode }
@@ -540,21 +444,8 @@ async function _showBashPermissionDialog(info) {
allowRun: canAllowRun,
...(isConnector && info.usage_scope === true ? { allowRunLabel: t('bash.permission.allow_usage') } : {}),
showModeControl: true,
- onPresented: () => {
- if (isConnector) return;
- if (presented) return;
- presented = true;
- _bashPermissionTelemetry('bash_risk_prompt_presented', {
- categories: _bashPermissionCategories(info),
- ...(_bashPermissionIrreversible(info) ? { irreversible: _bashPermissionIrreversible(info) } : {}),
- mode: currentMode,
- visibility_state: _bashPermissionVisibilityState(),
- queue_wait_ms: Math.max(0, Date.now() - _bashPermissionReceivedAt(info, startedAt)),
- });
- },
});
} catch (err) {
- dialogFailed = true;
result = { choice: 'deny', mode: currentMode };
_bashPermLog.warn('operation permission dialog failed', {
error_type: err && typeof err.name === 'string' ? err.name : 'unknown',
@@ -562,16 +453,13 @@ async function _showBashPermissionDialog(info) {
}
if (result && result.cancelled) {
_bashPermCancelled.delete(requestId);
- _bashTrackCancelledPermission(info, currentMode);
+ _bashPermTaskApproved.delete(info.request_id);
return;
}
const choice = result && typeof result === 'object' ? result.choice : result;
const selectedMode = _bashIsMode(result && result.mode)
? result.mode
: currentMode;
- const requestedDecision = (choice === 'allow_once' || choice === 'allow_run' || choice === 'allow_always')
- ? choice
- : 'deny';
let decision = (choice === 'allow_once' || choice === 'allow_run') ? choice : 'deny';
if (!canAllowRun && decision === 'allow_run') decision = 'allow_once';
let effectiveMode = currentMode;
@@ -591,20 +479,12 @@ async function _showBashPermissionDialog(info) {
else decision = 'deny';
}
if (_bashPermCancelled.delete(requestId)) {
- _bashTrackCancelledPermission(info, effectiveMode);
+ _bashPermTaskApproved.delete(info.request_id);
return;
}
- const baseResult = {
- decision: requestedDecision,
- effective_decision: decision,
- mode: effectiveMode,
- mode_changed: effectiveMode !== currentMode,
- categories: _bashPermissionCategories(info),
- ...(_bashPermissionIrreversible(info) ? { irreversible: _bashPermissionIrreversible(info) } : {}),
- };
try {
- const response = await window.orkas.invoke(
+ await window.orkas.invoke(
isWebAssist ? 'webAssist.actionConfirmResponse'
: isConnector ? 'connectors.action_confirm_response' : 'bash.permission_response',
isWebAssist
@@ -613,32 +493,10 @@ async function _showBashPermissionDialog(info) {
? { request_id: info.request_id, approved: decision !== 'deny', ...(decision === 'allow_run' ? { scope: info.usage_scope === true ? 'usage' : 'task' } : {}) }
: { request_id: info.request_id, decision },
);
- const failed = !response || response.ok === false;
- const stale = !failed && response.handled === false;
- try {
- _bashTrackPermissionResult(info, {
- ...baseResult,
- result: failed || dialogFailed ? 'failure' : (stale ? 'cancelled' : 'success'),
- duration_ms: Math.max(0, Date.now() - startedAt),
- ...(dialogFailed
- ? { error_code: 'dialog_failed', error_type: 'ui' }
- : failed ? { error_code: 'response_failed', error_type: 'ipc' }
- : (stale ? { error_code: 'stale_request', error_type: 'state' } : {})),
- });
- } catch (_e) { /* permission delivery must not depend on observability */ }
} catch (err) {
_bashPermLog.warn('bash permission response failed', {
error_type: err && typeof err.name === 'string' ? err.name : 'unknown',
});
- try {
- _bashTrackPermissionResult(info, {
- ...baseResult,
- result: 'failure',
- duration_ms: Math.max(0, Date.now() - startedAt),
- error_type: 'ipc',
- error_code: 'response_failed',
- });
- } catch (_) { /* the permission response must not depend on observability */ }
}
_bashPermCancelled.delete(requestId);
}
@@ -661,10 +519,8 @@ async function _drainBashPermissionQueue() {
}
async function _showLocalAgentPermissionDialog(info) {
- const startedAt = Date.now();
const requestId = String(info && info.request_id || '');
if (_bashPermCancelled.delete(requestId)) return;
- const isConnectorPermission = info && info.permission_kind === 'connector';
const agent = _bashAgentLabel(info);
const conversationTitle = _bashPermissionConversationTitle(info);
const action = String(info && (info.tool || info.description) || '').trim()
@@ -712,58 +568,17 @@ async function _showLocalAgentPermissionDialog(info) {
const decision = choice === 'allow_run'
? 'allow_run'
: choice === 'allow_once' ? 'allow_once' : 'deny';
- let response = null;
- let telemetryResult = 'success';
- let effectiveDecision = decision;
- let errorCode = '';
- let errorType = '';
try {
- response = await window.orkas.invoke('localAgents.permissionResponse', {
+ await window.orkas.invoke('localAgents.permissionResponse', {
request_id: requestId,
decision,
permission_policy: selectedMode,
});
- if (!response || response.ok === false) {
- telemetryResult = 'failure';
- effectiveDecision = 'deny';
- errorCode = 'response_failed';
- errorType = 'ipc';
- } else if (response.handled === false) {
- telemetryResult = 'cancelled';
- effectiveDecision = 'deny';
- errorCode = 'stale_request';
- errorType = 'state';
- } else {
- const returnedDecision = response.decision;
- if (returnedDecision === 'allow_once' || returnedDecision === 'allow_run' || returnedDecision === 'deny') {
- effectiveDecision = returnedDecision;
- }
- if (decision !== 'deny' && response.policy_saved === false) {
- telemetryResult = 'failure';
- effectiveDecision = 'deny';
- errorCode = 'permission_level_save_failed';
- errorType = 'storage';
- }
- }
} catch (err) {
- telemetryResult = 'failure';
- effectiveDecision = 'deny';
- errorCode = 'response_failed';
- errorType = 'ipc';
_bashPermLog.warn('external CLI permission response failed', {
error_type: err && typeof err.name === 'string' ? err.name : 'unknown',
});
}
- if (isConnectorPermission) {
- _bashPermissionTelemetry('connector_bridge_permission_result', {
- result: telemetryResult,
- decision,
- effective_decision: effectiveDecision,
- duration_ms: Math.max(0, Date.now() - startedAt),
- ...(errorCode ? { error_code: errorCode } : {}),
- ...(errorType ? { error_type: errorType } : {}),
- });
- }
_bashPermCancelled.delete(requestId);
}
@@ -783,7 +598,7 @@ function _cancelBashPermissionRequests(payload, kind) {
if (info && info._permission_kind === kind && cancelled.has(info.request_id)) {
_bashPermQueue.splice(i, 1);
_bashPermCancelled.delete(info.request_id);
- if (kind !== 'local-agent') _bashTrackCancelledPermission(info, null);
+ if (kind !== 'local-agent') _bashPermTaskApproved.delete(info.request_id);
}
}
}
@@ -794,16 +609,7 @@ if (window.orkas && typeof window.orkas.onPushEvent === 'function') {
if (!appWindow) {
window.orkas.onPushEvent('bash:permission', (info) => {
if (!info || typeof info.request_id !== 'string') return;
- const queuedInfo = {
- ...info,
- _renderer_received_at_ms: Date.now(),
- };
- _bashPermissionTelemetry('bash_risk_prompt_requested', {
- categories: _bashPermissionCategories(info),
- ...(_bashPermissionIrreversible(info) ? { irreversible: _bashPermissionIrreversible(info) } : {}),
- visibility_state: _bashPermissionVisibilityState(),
- });
- _bashPermQueue.push(queuedInfo);
+ _bashPermQueue.push(info);
_drainBashPermissionQueue();
});
window.orkas.onPushEvent('bash:permission_cancelled', (payload) => {
diff --git a/src/renderer/modules/chat-artifact.js b/src/renderer/modules/chat-artifact.js
index 043dd652..a81af941 100644
--- a/src/renderer/modules/chat-artifact.js
+++ b/src/renderer/modules/chat-artifact.js
@@ -61,16 +61,7 @@
// contexts row menus); the acting context is stashed per-open.
let _menuEl = null;
let _menuCtx = null; // { frame, cid, artifactId, title } of the open menu
- let _menuAnchor = null; // the ⋯ button that opened it
-
- function _track(action, data) {
- try { if (window.Monitor) (() => {})(action, data || {}); } catch (_) {}
- }
-
- function _trackEvent(action, data) {
- void action;
- void data;
- }
+ let _menuAnchor = null;
function _logArtifactFailure(action, data) {
try { _convLog.warn('chat artifact operation failed', { action, ...(data || {}) }); } catch (_) {}
@@ -99,7 +90,7 @@
}
}
- function _trackArtifactSaveResult(startedAt, result, sourceView, failure = {}) {
+ function _logArtifactSaveResult(startedAt, result, sourceView, failure = {}) {
if (result === 'success') return;
_logArtifactFailure('artifact_save', {
source_view: sourceView,
@@ -443,7 +434,6 @@
async function _doSave(ctx) {
const startedAt = Date.now();
const sourceView = _artifactSaveSourceView(ctx?.cid);
- _track('artifact_save', { surface: 'conversation', source_view: sourceView });
let r;
try {
r = await window.orkas.invoke('conversations.artifacts.save', {
@@ -451,20 +441,20 @@
});
} catch (err) {
const failure = _artifactSaveFailure(err, 'ipc');
- _trackArtifactSaveResult(startedAt, 'failure', sourceView, failure);
+ _logArtifactSaveResult(startedAt, 'failure', sourceView, failure);
_logArtifactSaveFailure(failure);
_notifyFail(_t('apps.save_failed', 'Could not save the app'), err);
return;
}
if (!r || r.ok === false) {
const failure = _artifactSaveFailure(r, 'operation');
- _trackArtifactSaveResult(startedAt, 'failure', sourceView, failure);
+ _logArtifactSaveResult(startedAt, 'failure', sourceView, failure);
_logArtifactSaveFailure(failure);
_notifyFail(_t('apps.save_failed', 'Could not save the app'), { message: (r && r.error) || 'save failed' });
return;
}
- _trackArtifactSaveResult(startedAt, 'success', sourceView);
+ _logArtifactSaveResult(startedAt, 'success', sourceView);
try {
const message = _t('apps.saved_toast', 'Saved to Apps');
if (typeof uiToast === 'function') uiToast(message, { variant: 'success' });
diff --git a/src/renderer/modules/chat-file-viewer.js b/src/renderer/modules/chat-file-viewer.js
index e30d544f..af87f41e 100644
--- a/src/renderer/modules/chat-file-viewer.js
+++ b/src/renderer/modules/chat-file-viewer.js
@@ -76,15 +76,6 @@ const _viewerLog = (typeof createLogger === 'function')
? createLogger('chat-file-viewer')
: { warn: () => {}, info: () => {}, error: () => {} };
-function _viewerTrack(action, data) {
- try { if (window.Monitor) (() => {})(action, data || {}); } catch (_) {}
-}
-
-function _viewerTrackEvent(action, data) {
- void action;
- void data;
-}
-
function _viewerClearPdfSlowTimer(state) {
if (!state || !state.slowTimer) return;
clearTimeout(state.slowTimer);
@@ -661,7 +652,6 @@ async function _onAddLibraryClick() {
if (!p || !_viewerCurrentCid || !_viewerAddLibraryBtn || _viewerAddLibraryBtn.disabled) return;
if (!_viewerCanAddToLibrary(p, { projectScoped: _viewerLibraryProjectScoped })) return;
const startedAt = Date.now();
- _viewerTrack('file_preview_add_library', { kind: _kindOf(p), has_project: !!_viewerCurrentProjectId });
const label = _viewerLabel('chat.preview_add_library_title', 'Add to Library');
const doneLabel = _viewerLabel('chat.preview_add_library_done', 'Added');
const original = _viewerAddLibraryButtonHtml(label);
@@ -675,12 +665,6 @@ async function _onAddLibraryClick() {
} catch (err) {
const failure = _viewerStableFailure(err, 'library_import_failed', 'ipc');
const reason = String(err && err.message || err);
- _viewerTrackEvent('file_preview_add_library_result', {
- result: 'failure',
- kind: _kindOf(p),
- duration_ms: _viewerDurationSince(startedAt),
- ...failure,
- });
_viewerLogFailure('file_preview_add_library', failure);
let message = `Add to Library failed: ${reason}`;
if (typeof t === 'function') {
@@ -700,12 +684,6 @@ async function _onAddLibraryClick() {
if (!res || !res.ok) {
const failure = _viewerStableFailure(res, 'library_import_failed', 'operation');
const reason = String((res && res.error) || 'failed');
- _viewerTrackEvent('file_preview_add_library_result', {
- result: 'failure',
- kind: _kindOf(p),
- duration_ms: _viewerDurationSince(startedAt),
- ...failure,
- });
_viewerLogFailure('file_preview_add_library', failure);
await _viewerShowAlert(`Add to Library failed: ${reason}`, 'file_preview_add_library_presentation');
return;
@@ -713,12 +691,6 @@ async function _onAddLibraryClick() {
const scope = res.scope === 'project' ? 'project' : (res.scope === 'global' ? 'global' : 'unknown');
window.OrkasPreviewHost?.filesChanged();
- _viewerTrackEvent('file_preview_add_library_result', {
- result: 'success',
- kind: _kindOf(p),
- scope,
- duration_ms: _viewerDurationSince(startedAt),
- });
try {
_viewerAddLibraryBtn.innerHTML = _viewerAddLibraryButtonHtml(doneLabel, 'check');
if (scope === 'global' && typeof currentView !== 'undefined' && currentView === 'contexts' && typeof loadContexts === 'function') {
@@ -765,14 +737,6 @@ async function _onSaveAppClick() {
if (!p || !_viewerSaveAppBtn || _viewerSaveAppBtn.disabled) return;
const startedAt = Date.now();
if (_viewerDirty) {
- _viewerTrackEvent('file_preview_save_app_result', {
- result: 'failure',
- surface: 'file_preview',
- kind: _kindOf(p),
- duration_ms: _viewerDurationSince(startedAt),
- error_type: 'validation',
- error_code: 'unsaved_changes',
- });
const message = _viewerLabel('apps.save_from_file_dirty', 'Save the file changes before saving it as an app.');
await _viewerShowAlert(message, 'file_preview_save_app_presentation');
return;
@@ -792,13 +756,6 @@ async function _onSaveAppClick() {
} catch (err) {
const failure = _viewerStableFailure(err, 'saved_app_save_failed', 'ipc');
const reason = String(err && err.message || err);
- _viewerTrackEvent('file_preview_save_app_result', {
- result: 'failure',
- surface: 'file_preview',
- kind: _kindOf(p),
- duration_ms: _viewerDurationSince(startedAt),
- ...failure,
- });
_viewerLogFailure('file_preview_save_app', failure);
const prefix = _viewerLabel('apps.save_failed', 'Could not save the app');
await _viewerShowAlert(`${prefix}: ${reason}`, 'file_preview_save_app_presentation');
@@ -808,26 +765,12 @@ async function _onSaveAppClick() {
if (!res || res.ok === false) {
const failure = _viewerStableFailure(res, 'saved_app_save_failed', 'operation');
const reason = String((res && res.error) || 'failed');
- _viewerTrackEvent('file_preview_save_app_result', {
- result: 'failure',
- surface: 'file_preview',
- kind: _kindOf(p),
- duration_ms: _viewerDurationSince(startedAt),
- ...failure,
- });
_viewerLogFailure('file_preview_save_app', failure);
const prefix = _viewerLabel('apps.save_failed', 'Could not save the app');
await _viewerShowAlert(`${prefix}: ${reason}`, 'file_preview_save_app_presentation');
_scheduleSaveAppButtonRestore(p, original);
return;
}
-
- _viewerTrackEvent('file_preview_save_app_result', {
- result: 'success',
- surface: 'file_preview',
- kind: _kindOf(p),
- duration_ms: _viewerDurationSince(startedAt),
- });
window.OrkasPreviewHost?.filesChanged();
try {
_viewerSaveAppBtn.innerHTML = _viewerSaveAppButtonHtml(doneLabel, 'check');
diff --git a/src/renderer/modules/chat-lightbox.js b/src/renderer/modules/chat-lightbox.js
index baa9f292..da47affb 100644
--- a/src/renderer/modules/chat-lightbox.js
+++ b/src/renderer/modules/chat-lightbox.js
@@ -363,7 +363,7 @@ function _ensureLightbox() {
<span class="chat-file-viewer-loading-spinner" aria-hidden="true"></span>
<span class="chat-lightbox-loading-label">${_lightboxEscapeHtml(_lightboxLoadingLabel())}</span>
</div>
- <img class="chat-lightbox-img" alt="" draggable="false" data-monitor-resource="chat-image-lightbox" />
+ <img class="chat-lightbox-img" alt="" draggable="false" />
<div class="chat-lightbox-actions">
<button type="button" class="chat-lightbox-add-library" aria-label="${addLabel}" title="${addLabel}" hidden>
${libraryIcon}
diff --git a/src/renderer/modules/connectors.js b/src/renderer/modules/connectors.js
index 11903fd5..7b1e7287 100644
--- a/src/renderer/modules/connectors.js
+++ b/src/renderer/modules/connectors.js
@@ -24,32 +24,6 @@ const _CONNECTORS_RENDER_CACHE_TTL_MS = 7 * 24 * 60 * 60 * 1000;
const _OAUTH_LAUNCH_THROTTLE_MS = 2000;
let _connectorsLegacyCachePurged = false;
-function _connectorsTrackClick(action, data) {
-}
-
-function _connectorsTrackEvent(action, data) {
-}
-
-function _connectorsTrackError(action, data) {
-}
-
-function _connectorTrackPayload(entry, instance) {
- const e = entry || {};
- const inst = instance || {};
- const rawId = String(e.id || inst.id || '');
- const origin = inst.origin === 'custom' || e._custom || rawId.startsWith('custom-') ? 'custom' : 'catalog';
- return {
- telemetry_version: 2,
- // Custom ids are derived from a user-authored display name. Keep that value out of analytics;
- // `origin` is the useful product dimension and `custom` is a stable low-cardinality bucket.
- connector_id: origin === 'custom' ? 'custom' : rawId,
- origin,
- auth_mode: origin === 'custom' ? 'custom'
- : ['server_bridge', 'mcp_dcr', 'composio', 'local_cli', 'local_api'].includes(e.auth_mode) ? e.auth_mode : 'unknown',
- is_bundle: !!(Array.isArray(e.bundle_member_ids) && e.bundle_member_ids.length),
- };
-}
-
function _connectorRequiresCredits(entry) {
return !!(entry && entry.requires_credits === true);
}
@@ -154,7 +128,7 @@ async function _assistConnectorSetup(entry, button, onReady) {
}
}
-function _connectorTrackErrorType(err) {
+function _connectorErrorType(err) {
const msg = String((err && (err.message || err.error)) || err || '').toLowerCase();
if (/timeout|timed out/.test(msg)) return 'timeout';
if (/network|fetch failed|econnreset|econnrefused|eai_again|enotfound/.test(msg)) return 'network';
@@ -172,14 +146,10 @@ function _connectorOperationErrorCode(errLike, fallback) {
function _connectorFailureDetail(errLike, fallbackCode) {
return {
error_code: _connectorOperationErrorCode(errLike, fallbackCode),
- error_type: _connectorTrackErrorType(errLike),
+ error_type: _connectorErrorType(errLike),
};
}
-function _logConnectorOperationFailure(action, detail) {
- _connectorsLog.warn('connector operation failed', { action, ...(detail || {}) });
-}
-
const CONNECT_CANCEL_CODES = new Set(['user_cancelled', 'superseded']);
function _isConnectCancel(errLike) {
@@ -190,15 +160,8 @@ function _isConnectCancel(errLike) {
return msg.includes('superseded') || msg.includes('cancelled') || msg.includes('canceled');
}
-// The commercial build records the terminal outcome at this boundary. The
-// open build keeps only the behavior needed to distinguish an intentional
-// cancellation from a failure that should be surfaced to the user.
-function _reportConnectOutcome(_payload, _startedAt, errLike, _durationMs) {
- return _isConnectCancel(errLike);
-}
-
-function _handleConnectFailure(payload, startedAt, errLike) {
- if (_reportConnectOutcome(payload, startedAt, errLike)) return;
+function _handleConnectFailure(errLike) {
+ if (_isConnectCancel(errLike)) return;
uiAlert(_formatConnectError(errLike));
}
@@ -447,16 +410,16 @@ async function loadConnectors() {
if (catRes && catRes.ok && Array.isArray(catRes.catalog)) {
_connectorsState.catalog = catRes.catalog;
} else {
- _connectorsLog.warn('catalog failed', { error_type: _connectorTrackErrorType(catRes && catRes.error) });
+ _connectorsLog.warn('catalog failed', { error_type: _connectorErrorType(catRes && catRes.error) });
}
if (listRes && listRes.ok && Array.isArray(listRes.instances)) {
_connectorsState.instances = listRes.instances;
} else {
- _connectorsLog.warn('list failed', { error_type: _connectorTrackErrorType(listRes && listRes.error) });
+ _connectorsLog.warn('list failed', { error_type: _connectorErrorType(listRes && listRes.error) });
}
_persistConnectorsRenderCache();
} catch (err) {
- _connectorsLog.warn('list failed', { error_type: _connectorTrackErrorType(err) });
+ _connectorsLog.warn('list failed', { error_type: _connectorErrorType(err) });
} finally {
if (seq === _connectorsLoadSeq) {
_connectorsState.loading = false;
@@ -487,7 +450,7 @@ async function verifyConnectors() {
_renderConnectorsGrid();
}
} catch (err) {
- _connectorsLog.warn('connector verification failed', { error_type: _connectorTrackErrorType(err) });
+ _connectorsLog.warn('connector verification failed', { error_type: _connectorErrorType(err) });
}
}
@@ -834,7 +797,6 @@ function _renderConnectorsGrid() {
if (addBtn && !addBtn.dataset.bound) {
addBtn.dataset.bound = '1';
addBtn.addEventListener('click', () => {
- _connectorsTrackClick('connector_custom_open', {});
_openAddCustomDialog();
});
}
@@ -1047,8 +1009,6 @@ function _collectConnectionParameters(entry, entryPoint = 'form') {
const lang = (typeof getLang === 'function') ? getLang() : 'en';
overlay.innerHTML = _connectorSetupMarkup(entry, fields, lang, dialogId);
document.body.appendChild(overlay);
- _connectorsTrackEvent('connector_config_view_result', { ..._connectorTrackPayload(entry, null),
- entry_point: entryPoint === 'agent' ? 'agent' : 'form', action: 'form', result: 'success' });
const form = overlay.querySelector('[data-act="setup-form"]');
const cancelBtn = overlay.querySelector('[data-act="cancel"]');
@@ -1121,7 +1081,7 @@ function _collectConnectionParameters(entry, entryPoint = 'form') {
window.orkas.invoke('auth.openExternal', { url }).catch((error) => {
_connectorsLog.warn('connector setup guide could not be opened', {
connector_id: entry.id,
- error_type: _connectorTrackErrorType(error),
+ error_type: _connectorErrorType(error),
});
});
});
@@ -1411,7 +1371,6 @@ function _useConnector(entry, instance) {
const name = String((entry && !entry._custom && _connectorDisplayName(entry))
|| (instance && instance.display_name) || (entry && entry.display_name) || id).trim();
if (!id && !name) return;
- _connectorsTrackClick('connector_use', _connectorTrackPayload(entry, instance));
setView('new-chat');
if (typeof setChatRecipient === 'function') {
setChatRecipient('new-chat', { kind: 'commander' });
@@ -1425,41 +1384,17 @@ async function _toggleConnectorEnabled(entry, instance, nextEnabled) {
const ids = Array.isArray(entry.bundle_member_ids) && entry.bundle_member_ids.length
? entry.bundle_member_ids.slice()
: [(instance && instance.id) || entry.id];
- const payload = {
- ..._connectorTrackPayload(entry, instance),
- enabled: !!nextEnabled,
- instance_count: ids.length,
- };
- const startedAt = performance.now();
- _connectorsTrackClick('connector_enable_toggle', payload);
try {
for (const id of ids) {
const res = await window.orkas.invoke('connectors.set_enabled', { id, enabled: nextEnabled });
if (!res || !res.ok) {
- const failure = _connectorFailureDetail(res, 'set_enabled_failed');
- _connectorsTrackEvent('connector_enable_result', {
- ...payload,
- result: 'failure',
- duration_ms: Math.round(performance.now() - startedAt),
- ...failure,
- });
+ _connectorsLog.warn('connector enable toggle failed', _connectorFailureDetail(res, 'set_enabled_failed'));
uiAlert(_formatConnectError(res, 'component.toggle_failed'));
return;
}
}
- _connectorsTrackEvent('connector_enable_result', {
- ...payload,
- result: 'success',
- duration_ms: Math.round(performance.now() - startedAt),
- });
} catch (err) {
- const failure = _connectorFailureDetail(err, 'set_enabled_exception');
- _connectorsTrackEvent('connector_enable_result', {
- ...payload,
- result: 'failure',
- duration_ms: Math.round(performance.now() - startedAt),
- ...failure,
- });
+ _connectorsLog.warn('connector enable toggle failed', _connectorFailureDetail(err, 'set_enabled_exception'));
uiAlert(_formatConnectError(err, 'component.toggle_failed'));
return;
}
@@ -1504,40 +1439,17 @@ async function _quickDisconnect(entry, instance) {
const ids = Array.isArray(entry.bundle_member_ids) && entry.bundle_member_ids.length
? entry.bundle_member_ids.slice()
: [(instance && instance.id) || entry.id];
- const payload = {
- ..._connectorTrackPayload(entry, instance),
- instance_count: ids.length,
- };
- const startedAt = performance.now();
- _connectorsTrackClick('connector_disconnect', payload);
try {
for (const id of ids) {
const res = await window.orkas.invoke('connectors.remove', { id });
if (!res || (!res.ok && !/not found/i.test(res.error || ''))) {
- const failure = _connectorFailureDetail(res, 'disconnect_failed');
- _connectorsTrackEvent('connector_disconnect_result', {
- ...payload,
- result: 'failure',
- duration_ms: Math.round(performance.now() - startedAt),
- ...failure,
- });
+ _connectorsLog.warn('connector disconnect failed', _connectorFailureDetail(res, 'disconnect_failed'));
uiAlert(_formatConnectError(res, 'connectors.errors.remove_failed'));
return;
}
}
- _connectorsTrackEvent('connector_disconnect_result', {
- ...payload,
- result: 'success',
- duration_ms: Math.round(performance.now() - startedAt),
- });
} catch (err) {
- const failure = _connectorFailureDetail(err, 'disconnect_exception');
- _connectorsTrackEvent('connector_disconnect_result', {
- ...payload,
- result: 'failure',
- duration_ms: Math.round(performance.now() - startedAt),
- ...failure,
- });
+ _connectorsLog.warn('connector disconnect failed', _connectorFailureDetail(err, 'disconnect_exception'));
uiAlert(_formatConnectError(err, 'connectors.errors.remove_failed'));
return;
}
@@ -1563,26 +1475,6 @@ async function _ensureLocalCliReady(uiEntry, targetEntry) {
const uiId = uiEntry.id;
if (_localCliInstallPhases.has(uiId)) return false;
const cli = targetEntry.local_cli.executable || 'CLI';
- const startedAt = performance.now();
- let reported = false;
- const finish = (result, stage, error) => {
- if (reported) return;
- reported = true;
- const rawCode = error && error.code;
- const codes = ['local_cli_runtime_missing', 'local_cli_install_unsupported', 'local_cli_install_registry_unavailable',
- 'local_cli_install_integrity_unavailable', 'local_cli_install_integrity_mismatch',
- 'local_cli_install_timeout', 'local_cli_install_failed'];
- const detail = {
- ..._connectorTrackPayload(targetEntry, null), result, stage,
- duration_ms: Math.max(0, Math.round(performance.now() - startedAt)),
- ...(result === 'failure' ? {
- error_code: codes.includes(rawCode) ? rawCode : 'local_cli_install_failed',
- error_type: rawCode === 'local_cli_install_timeout' ? 'timeout' : 'runtime',
- } : {}),
- };
- _connectorsTrackEvent('connector_cli_setup_result', detail);
- };
-
_localCliInstallPhases.set(uiId, 'checking');
_renderConnectorsGrid();
let statusResponse;
@@ -1601,20 +1493,17 @@ async function _ensureLocalCliReady(uiEntry, targetEntry) {
cli,
};
_localCliInstallErrors.set(uiId, failure);
- finish('failure', 'cli_check', failure);
_renderConnectorsGrid();
uiAlert(_formatLocalCliInstallError(failure, targetEntry));
return false;
}
if (status.installed) {
- finish('success', 'cli_check');
_localCliInstallErrors.delete(uiId);
_renderConnectorsGrid();
return true;
}
if (status.runtime_ready === false) {
const failure = { code: 'local_cli_runtime_missing', cli };
- finish('failure', 'cli_check', failure);
_localCliInstallErrors.set(uiId, failure);
_renderConnectorsGrid();
uiAlert(_formatLocalCliInstallError(failure, targetEntry));
@@ -1634,12 +1523,10 @@ async function _ensureLocalCliReady(uiEntry, targetEntry) {
cli,
};
_localCliInstallErrors.set(uiId, failure);
- finish('failure', 'cli_install', failure);
uiAlert(_formatLocalCliInstallError(failure, targetEntry));
return false;
}
_localCliInstallErrors.delete(uiId);
- finish('success', 'cli_install');
return true;
} catch (error) {
const failure = {
@@ -1647,7 +1534,6 @@ async function _ensureLocalCliReady(uiEntry, targetEntry) {
cli,
};
_localCliInstallErrors.set(uiId, failure);
- finish('failure', 'cli_install', failure);
uiAlert(_formatLocalCliInstallError(failure, targetEntry));
return false;
} finally {
@@ -1670,7 +1556,6 @@ async function _runConnect(entry, entryPoint = 'form') {
const currentLaunch = _oauthLaunchAttempts.get(entry.id);
if ((_connectorsState.connecting && _connectorsState.connecting.has(entry.id))
|| (currentLaunch && currentLaunch.throttled) || _oauthCallbackAttempts.has(entry.id)) return;
- if (entryPoint !== 'agent') _connectorsTrackClick('connector_connect', _connectorTrackPayload(entry, null));
let targetEntry = entry;
const installedEntry = installed && _catalogEntryById(installed.id);
if (installedEntry && installedEntry.catalog_parent_id === entry.id) {
@@ -1722,8 +1607,6 @@ async function _runConnect(entry, entryPoint = 'form') {
}
}
- const payload = { ..._connectorTrackPayload(entry, null), auth_mode: targetEntry.auth_mode };
- const startedAt = performance.now();
const launchToken = ++_oauthLaunchToken;
const launchAttempt = {
token: launchToken,
@@ -1748,7 +1631,7 @@ async function _runConnect(entry, entryPoint = 'form') {
});
if (res && res.ok && res.started && typeof res.attempt_id === 'string' && res.attempt_id) {
accepted = true;
- _pendingConnectAttempts.set(res.attempt_id, { payload, startedAt, uiCatalogId: entry.id });
+ _pendingConnectAttempts.set(res.attempt_id, { uiCatalogId: entry.id });
const launch = _oauthLaunchAttempts.get(entry.id);
// The browser can take focus before IPC returns. Do not recreate feedback already cleared by
// that blur; only correlate a launch phase that is still visible.
@@ -1760,12 +1643,12 @@ async function _runConnect(entry, entryPoint = 'form') {
setTimeout(() => input && input.focus(), 0);
if (typeof uiToast === 'function') uiToast(t('connectors.errors.api_key_required'));
} else if (res && !res.ok) {
- _handleConnectFailure(payload, startedAt, res);
+ _handleConnectFailure(res);
} else {
- _handleConnectFailure(payload, startedAt, { code: 'empty_response' });
+ _handleConnectFailure({ code: 'empty_response' });
}
} catch (err) {
- _handleConnectFailure(payload, startedAt, err);
+ _handleConnectFailure(err);
} finally {
if (!accepted) {
const launch = _oauthLaunchAttempts.get(entry.id);
@@ -1824,23 +1707,12 @@ function _handleOAuthConnectResult(info) {
if (busyChanged) _renderConnectorsGrid();
if (pending) _pendingConnectAttempts.delete(info.attempt_id);
const entry = _connectorsState.catalog.find((item) => item && item.id === info.catalog_id) || { id: info.catalog_id };
- const payload = pending ? pending.payload : _connectorTrackPayload(entry, null);
- const durationMs = pending
- ? Math.round(performance.now() - pending.startedAt)
- : (Number.isFinite(info.duration_ms) ? info.duration_ms : 0);
-
- if (info.result === 'success') {
- if (info.telemetry_reported !== true) _connectorsTrackEvent('connector_connect_result', {
- ...payload,
- result: 'success',
- duration_ms: Math.max(0, durationMs),
- });
- } else {
+ if (info.result !== 'success') {
const errLike = {
code: info.code || 'oauth_failed', error: info.error || 'connector authorization failed',
authorization_detail: info.authorization_detail,
};
- const cancelled = _reportConnectOutcome(payload, pending ? pending.startedAt : performance.now(), errLike, durationMs);
+ const cancelled = _isConnectCancel(errLike);
// Failed first CLI setups return to the ordinary Connect card, so report their transport
// failure here too. Other transports retain the resulting error on their connector card.
if (!cancelled && (errLike.code !== 'mcp_connect_failed' || entry.auth_mode === 'local_cli')) {
@@ -1858,9 +1730,6 @@ async function _retryConnect(entry, event, instance) {
const ids = Array.isArray(entry.bundle_member_ids) && entry.bundle_member_ids.length
? entry.bundle_member_ids.slice()
: [(instance && instance.id) || entry.id];
- const payload = { ..._connectorTrackPayload(entry, null), instance_count: ids.length };
- const startedAt = performance.now();
- _connectorsTrackClick(event, payload);
_connectorsState.connecting.add(entry.id);
_renderConnectorsGrid();
try {
@@ -1884,29 +1753,11 @@ async function _retryConnect(entry, event, instance) {
const failures = results.filter(Boolean);
if (failures.length) {
const firstFailure = failures[0];
- _connectorsTrackEvent(`${event}_result`, {
- ...payload,
- result: 'failure',
- duration_ms: Math.round(performance.now() - startedAt),
- error_code: firstFailure.error_code,
- error_type: firstFailure.error_type,
- });
uiAlert(_formatConnectorStatusError(firstFailure.error));
} else {
- _connectorsTrackEvent(`${event}_result`, {
- ...payload,
- result: 'success',
- duration_ms: Math.round(performance.now() - startedAt),
- });
}
} catch (err) {
const failure = _connectorFailureDetail(err, 'refresh_exception');
- _connectorsTrackEvent(`${event}_result`, {
- ...payload,
- result: 'failure',
- duration_ms: Math.round(performance.now() - startedAt),
- ...failure,
- });
uiAlert(_formatConnectorStatusError((err && err.message) || ''));
} finally {
_connectorsState.connecting.delete(entry.id);
@@ -2000,8 +1851,6 @@ function _openAddCustomDialog() {
overlay.className = 'modal-overlay ui-dialog-overlay open';
overlay.innerHTML = _customConnectorMarkup();
document.body.appendChild(overlay);
- _connectorsTrackEvent('connector_config_view_result', { connector_id: 'custom', origin: 'custom',
- auth_mode: 'custom', entry_point: 'form', action: 'form', result: 'success' });
const f = (name) => overlay.querySelector(`[data-f="${name}"]`);
const secHttp = overlay.querySelector('[data-sec="http"]');
@@ -2033,20 +1882,10 @@ function _openAddCustomDialog() {
const okBtn = overlay.querySelector('[data-act="ok"]');
okBtn.addEventListener('click', async () => {
const kind = f('kind').value;
- const payload = { entry_point: 'form', transport_kind: kind };
- const startedAt = performance.now();
- _connectorsTrackClick('connector_custom_add', payload);
let transport;
if (kind === 'stdio') {
const env = _parseEnvLines(f('env').value);
if (env === null) {
- _connectorsTrackEvent('connector_custom_add_result', {
- ...payload,
- result: 'failure',
- duration_ms: Math.round(performance.now() - startedAt),
- error_code: 'invalid_env',
- error_type: 'validation',
- });
uiAlert(t('connectors.custom.bad_env'));
return;
}
@@ -2059,13 +1898,6 @@ function _openAddCustomDialog() {
} else {
const headers = _parseHeaderLines(f('headers').value);
if (headers === null) {
- _connectorsTrackEvent('connector_custom_add_result', {
- ...payload,
- result: 'failure',
- duration_ms: Math.round(performance.now() - startedAt),
- error_code: 'invalid_headers',
- error_type: 'validation',
- });
uiAlert(t('connectors.custom.bad_headers'));
return;
}
@@ -2080,13 +1912,6 @@ function _openAddCustomDialog() {
transport,
});
if (res && res.ok && res.instance) {
- _connectorsTrackEvent('connector_custom_add_result', {
- ...payload,
- result: 'success',
- connection_state: ['connected', 'connecting', 'error', 'degraded', 'disconnected'].includes(res.instance.status && res.instance.status.kind)
- ? res.instance.status.kind : 'unknown',
- duration_ms: Math.round(performance.now() - startedAt),
- });
added = true;
close();
const st = res.instance.status || {};
@@ -2100,23 +1925,11 @@ function _openAddCustomDialog() {
uiAlert(`${t('connectors.status.unverified')}: ${_formatConnectorStatusError(st.message)}`);
}
} else {
- const failure = _connectorFailureDetail(res, 'custom_add_failed');
- _connectorsTrackEvent('connector_custom_add_result', {
- ...payload,
- result: 'failure',
- duration_ms: Math.round(performance.now() - startedAt),
- ...failure,
- });
+ _connectorsLog.warn('custom connector add failed', _connectorFailureDetail(res, 'custom_add_failed'));
uiAlert(_formatConnectError(res));
}
} catch (err) {
- const failure = _connectorFailureDetail(err, 'custom_add_exception');
- _connectorsTrackEvent('connector_custom_add_result', {
- ...payload,
- result: 'failure',
- duration_ms: Math.round(performance.now() - startedAt),
- ...failure,
- });
+ _connectorsLog.warn('custom connector add failed', _connectorFailureDetail(err, 'custom_add_exception'));
uiAlert(_formatConnectError(err));
} finally {
okBtn.disabled = false;
@@ -2233,7 +2046,6 @@ async function _drainConnectorInstallQueue() {
const requestId = String(info.request_id || '');
if (_connectorInstallCancelled.delete(requestId)) continue;
const warn = info.kind === 'stdio' ? `\n\n${t('connectors.install_confirm.stdio_warning')}` : '';
- const startedAt = performance.now();
let ok = false;
let dialogFailed = false;
const controller = typeof AbortController === 'function' ? new AbortController() : null;
@@ -2252,34 +2064,15 @@ async function _drainConnectorInstallQueue() {
}
_connectorInstallControllers.delete(requestId);
if (_connectorInstallCancelled.delete(requestId)) continue;
- const payload = {
- decision: ok ? 'approved' : 'denied',
- transport_kind: info.kind || '',
- };
try {
const response = await window.orkas.invoke('connectors.install_confirm_response', {
request_id: info.request_id,
approved: !!ok,
});
const stale = response && response.handled === false;
- _connectorsTrackEvent('connector_install_confirmation_result', {
- ...payload,
- result: dialogFailed ? 'failure' : (stale ? 'cancelled' : 'success'),
- duration_ms: Math.round(performance.now() - startedAt),
- ...(dialogFailed
- ? { error_code: 'dialog_failed', error_type: 'ui' }
- : (stale ? { error_code: 'request_stale' } : {})),
- });
if (ok && !stale && currentView === 'connectors') loadConnectors();
} catch (err) {
- _connectorsTrackEvent('connector_install_confirmation_result', {
- ...payload,
- result: 'failure',
- duration_ms: Math.round(performance.now() - startedAt),
- error_code: 'response_failed',
- error_type: 'ipc',
- });
- _connectorsLog.warn('install confirm response failed', { error_type: _connectorTrackErrorType(err) });
+ _connectorsLog.warn('install confirm response failed', { error_type: _connectorErrorType(err) });
}
}
} finally {
diff --git a/src/renderer/modules/contexts.js b/src/renderer/modules/contexts.js
index ab4e1d72..85375359 100644
--- a/src/renderer/modules/contexts.js
+++ b/src/renderer/modules/contexts.js
@@ -878,14 +878,9 @@ function _bindCtxTreeHandlers(container) {
}
}
-// ── Row-level actions ──
-
-function _ctxCreateEntryActionTracker(action) { return () => {}; }
-
async function reprocessCtxKbFile(rel) {
_ctxSetOperation(1);
try {
- const trackResult = _ctxCreateEntryActionTracker('reprocess');
const failedStatus = { ...(_kbStatusByPath[rel] || {}), status: 'failed' };
const restoreFailedStatus = () => {
_kbStatusByPath[rel] = failedStatus;
@@ -903,14 +898,11 @@ async function reprocessCtxKbFile(rel) {
const data = await res.json();
if (!data.ok) {
restoreFailedStatus();
- trackResult('failure', 'reprocess_failed');
await uiAlert(t('contexts.kb.reprocess_failed'));
return;
}
- trackResult('success');
} catch (_) {
restoreFailedStatus();
- trackResult('failure', 'request_failed');
await uiAlert(t('contexts.kb.reprocess_failed'));
}
} finally {
@@ -940,24 +932,20 @@ async function deleteCtxEntry(rel, kind) {
? t('contexts.dir.del_confirm', { name })
: t('contexts.file.del_confirm', { name });
if (!(await uiConfirm(prompt))) return;
- const trackResult = _ctxCreateEntryActionTracker('delete');
let data;
try {
const res = await _ctxFetch(`/api/contexts/delete?path=${encodeURIComponent(rel)}`, { method: 'DELETE' });
data = await res.json();
} catch (err) {
- trackResult('failure', 'request_failed');
_contextsLog.warn('library entry delete failed', { error_code: 'request_failed' });
await uiAlert(t('contexts.delete_failed'));
return;
}
if (!data?.ok) {
- trackResult('failure', 'delete_failed');
_contextsLog.warn('library entry delete failed', { error_code: 'delete_failed' });
await uiAlert(t('contexts.delete_failed'));
return;
}
- trackResult('success');
try {
if (_ctxActive && (_ctxActive.id === rel || _ctxActive.id.startsWith(rel + '/'))) {
_clearCtxViewer();
@@ -1239,7 +1227,7 @@ async function _handleCtxMove(srcRel, targetDir) {
.find((el) => el.dataset.path === srcRel);
const entryType = sourceWrap?.dataset?.type || 'file';
const startedAt = performance.now();
- const trackResult = (result, errorCode, reportError = true) => {
+ const logResult = (result, errorCode, reportError = true) => {
const payload = {
result,
entry_type: entryType,
@@ -1251,13 +1239,11 @@ async function _handleCtxMove(srcRel, targetDir) {
if (result === 'failure' && reportError) {
_contextsLog.warn('library file move failed', payload);
}
- if (!window.Monitor) return;
- try { Monitor.event('library_file_move_result', payload); } catch (_) {}
};
// Reject moves into self or own subtree (only meaningful for dirs but the
// check is cheap and correct for files too).
if (targetDir === srcRel || targetDir.startsWith(srcRel + '/')) {
- trackResult('failure', 'invalid_target', false);
+ logResult('failure', 'invalid_target', false);
await uiAlert(t('contexts.dnd.invalid_self'));
return;
}
@@ -1270,20 +1256,20 @@ async function _handleCtxMove(srcRel, targetDir) {
});
data = await res.json();
} catch (err) {
- trackResult('failure', 'move_failed');
+ logResult('failure', 'move_failed');
await uiAlert(t('contexts.dnd.move_failed'));
return;
}
if (!data?.ok) {
const errorCode = data.error === 'destination already exists' ? 'target_exists' : 'move_failed';
- trackResult('failure', errorCode);
+ logResult('failure', errorCode);
const message = errorCode === 'target_exists'
? t('contexts.dnd.target_exists', { name: base })
: t('contexts.dnd.move_failed');
await uiAlert(message);
return;
}
- trackResult('success');
+ logResult('success');
try {
_applyCtxPathChange(srcRel, dst, targetDir);
await loadContexts();
@@ -1337,7 +1323,6 @@ async function _commitInlineRename(rel, nextBase) {
const dir = rel.includes('/') ? rel.slice(0, rel.lastIndexOf('/')) : '';
const dst = dir ? `${dir}/${cleaned}` : cleaned;
if (dst === rel) { renderCtxTree(); return; }
- const trackResult = _ctxCreateEntryActionTracker('rename');
let data;
try {
const res = await _ctxFetch('/api/contexts/rename', {
@@ -1347,7 +1332,6 @@ async function _commitInlineRename(rel, nextBase) {
});
data = await res.json();
} catch (err) {
- trackResult('failure', 'request_failed');
_contextsLog.warn('library entry rename failed', { error_code: 'request_failed' });
await uiAlert(t('contexts.entry.rename_failed'));
try { await loadContexts(); } catch (refreshErr) { _contextsLog.warn('refresh after library entry rename failure failed', refreshErr); }
@@ -1357,13 +1341,11 @@ async function _commitInlineRename(rel, nextBase) {
const errorCode = data.error === 'destination already exists' || data.error === 'target_exists'
? 'target_exists'
: 'rename_failed';
- trackResult('failure', errorCode);
_contextsLog.warn('library entry rename failed', { error_code: errorCode });
await uiAlert(_ctxRenameFailureMessage(data.error));
try { await loadContexts(); } catch (refreshErr) { _contextsLog.warn('refresh after library entry rename failure failed', refreshErr); }
return;
}
- trackResult('success');
try {
_applyCtxPathChange(rel, dst);
await loadContexts();
@@ -1421,7 +1403,6 @@ async function saveCtxNew() {
msg.textContent = t('contexts.new.bad_chars'); msg.className = 'form-msg err'; return;
}
const joined = _ctxNewTargetDir ? `${_ctxNewTargetDir}/${nameRaw}` : nameRaw;
- const trackResult = _ctxCreateEntryActionTracker('create_directory');
let data;
try {
const res = await _ctxFetch('/api/contexts/mkdir', {
@@ -1431,7 +1412,6 @@ async function saveCtxNew() {
});
data = await res.json();
} catch (err) {
- trackResult('failure', 'request_failed');
_contextsLog.warn('library directory create failed', { error_code: 'request_failed' });
msg.textContent = t('contexts.dir.create_failed');
msg.className = 'form-msg err';
@@ -1443,11 +1423,9 @@ async function saveCtxNew() {
: t('contexts.dir.create_failed');
msg.className = 'form-msg err';
const errorCode = data.error === 'path exists and is not a directory' ? 'target_exists' : 'create_failed';
- trackResult('failure', errorCode);
_contextsLog.warn('library directory create failed', { error_code: errorCode });
return;
}
- trackResult('success');
try {
_ctxExpanded.add(joined);
closeCtxNewModal();
@@ -1477,7 +1455,6 @@ async function createCtxNewTextFile(parentDir = '') {
while (siblings.includes(`${stem}.md`)) { stem = `${stemBase} ${i++}`; }
const name = `${stem}.md`;
const fullPath = parentDir ? `${parentDir}/${name}` : name;
- const trackResult = _ctxCreateEntryActionTracker('create_text');
let data;
try {
const res = await _ctxFetch('/api/contexts/write', {
@@ -1487,18 +1464,15 @@ async function createCtxNewTextFile(parentDir = '') {
});
data = await res.json();
} catch (err) {
- trackResult('failure', 'request_failed');
_contextsLog.warn('library text create failed', { error_code: 'request_failed' });
await uiAlert(t('contexts.file.create_failed'));
return;
}
if (!data?.ok) {
- trackResult('failure', 'create_failed');
_contextsLog.warn('library text create failed', { error_code: 'create_failed' });
await uiAlert(t('contexts.file.create_failed'));
return;
}
- trackResult('success');
try {
if (parentDir) _ctxExpanded.add(parentDir);
_ctxPendingRename = { path: fullPath };
@@ -1533,7 +1507,6 @@ async function createCtxNewTodoFile(parentDir = '') {
const fullPath = parentDir ? `${parentDir}/${name}` : name;
const heading = t('contexts.new.todo_template_heading');
const template = `# ${heading}\n\n- [ ] \n- [ ] \n- [ ] \n`;
- const trackResult = _ctxCreateEntryActionTracker('create_todo');
let data;
try {
const res = await _ctxFetch('/api/contexts/write', {
@@ -1543,18 +1516,15 @@ async function createCtxNewTodoFile(parentDir = '') {
});
data = await res.json();
} catch (err) {
- trackResult('failure', 'request_failed');
_contextsLog.warn('library todo create failed', { error_code: 'request_failed' });
await uiAlert(t('contexts.file.create_failed'));
return;
}
if (!data?.ok) {
- trackResult('failure', 'create_failed');
_contextsLog.warn('library todo create failed', { error_code: 'create_failed' });
await uiAlert(t('contexts.file.create_failed'));
return;
}
- trackResult('success');
try {
if (parentDir) _ctxExpanded.add(parentDir);
_ctxPendingRename = { path: fullPath };
diff --git a/src/renderer/modules/conversation-info.js b/src/renderer/modules/conversation-info.js
index 9c6c2a66..b4f10801 100644
--- a/src/renderer/modules/conversation-info.js
+++ b/src/renderer/modules/conversation-info.js
@@ -121,7 +121,7 @@ const ConversationInfo = (() => {
return { error_type: errorType, error_code: errorCode };
}
- function _trackSavedAppSaveResult(startedAt, result, path, resourceKind, failure = {}) {
+ function _logSavedAppSaveResult(startedAt, result, path, resourceKind, failure = {}) {
const payload = {
result,
surface: 'conversation_info',
@@ -129,7 +129,6 @@ const ConversationInfo = (() => {
duration_ms: Math.max(0, Date.now() - startedAt),
};
if (result !== 'success') Object.assign(payload, failure);
- try { if (window.Monitor) Monitor.event('file_preview_save_app_result', payload); } catch (_) {}
if (result === 'failure') {
_infoLog.warn('conversation info app save failed', {
error_type: payload.error_type,
@@ -232,7 +231,7 @@ const ConversationInfo = (() => {
return 'unsupported';
}
- function _telemetryFileKind(name) {
+ function _fileKindForLog(name) {
const ext = _extForName(name);
if (ext === 'html' || ext === 'htm') return 'html';
if (ext === 'md' || ext === 'markdown') return 'markdown';
@@ -242,11 +241,11 @@ const ConversationInfo = (() => {
return kind;
}
- function _trackLibraryImportResult(startedAt, result, absPath, response, failure = {}) {
+ function _logLibraryImportResult(startedAt, result, absPath, response, failure = {}) {
const payload = {
result,
surface: 'conversation_info',
- kind: _telemetryFileKind(absPath),
+ kind: _fileKindForLog(absPath),
duration_ms: Math.max(0, Date.now() - startedAt),
};
if (result === 'success') {
@@ -256,7 +255,6 @@ const ConversationInfo = (() => {
} else {
Object.assign(payload, failure);
}
- try { if (window.Monitor) Monitor.event('file_preview_add_library_result', payload); } catch (_) {}
if (result === 'failure') {
_infoLog.warn('conversation info library import failed', {
error_type: payload.error_type,
@@ -1119,7 +1117,7 @@ const ConversationInfo = (() => {
try {
res = await window.orkas.invoke('library.importProduced', _fileActionPayload(absPath, cidOverride));
} catch (err) {
- _trackLibraryImportResult(
+ _logLibraryImportResult(
startedAt,
'failure',
absPath,
@@ -1132,7 +1130,7 @@ const ConversationInfo = (() => {
return;
}
if (!res || !res.ok) {
- _trackLibraryImportResult(
+ _logLibraryImportResult(
startedAt,
'failure',
absPath,
@@ -1145,7 +1143,7 @@ const ConversationInfo = (() => {
return;
}
- _trackLibraryImportResult(startedAt, 'success', absPath, res);
+ _logLibraryImportResult(startedAt, 'success', absPath, res);
try {
const libraryLabel = res.scope === 'project'
? _label('contexts.transfer.project_library', 'Project Library')
@@ -1175,7 +1173,7 @@ const ConversationInfo = (() => {
try {
res = await window.orkas.invoke('savedApps.saveFromPath', _fileActionPayload(absPath, cidOverride));
} catch (err) {
- _trackSavedAppSaveResult(startedAt, 'failure', absPath, resourceKind, _savedAppSaveFailure(err, 'ipc'));
+ _logSavedAppSaveResult(startedAt, 'failure', absPath, resourceKind, _savedAppSaveFailure(err, 'ipc'));
try {
await uiAlert(_label('apps.save_failed', 'Could not save the app') + ': ' + String(err && err.message || err));
} catch (_) {
@@ -1187,7 +1185,7 @@ const ConversationInfo = (() => {
return;
}
if (!res || res.ok === false) {
- _trackSavedAppSaveResult(startedAt, 'failure', absPath, resourceKind, _savedAppSaveFailure(res, 'operation'));
+ _logSavedAppSaveResult(startedAt, 'failure', absPath, resourceKind, _savedAppSaveFailure(res, 'operation'));
try {
await uiAlert(_label('apps.save_failed', 'Could not save the app') + ': ' + String((res && res.error) || 'failed'));
} catch (_) {
@@ -1199,7 +1197,7 @@ const ConversationInfo = (() => {
return;
}
- _trackSavedAppSaveResult(startedAt, 'success', absPath, resourceKind);
+ _logSavedAppSaveResult(startedAt, 'success', absPath, resourceKind);
try {
const message = _label('apps.saved_toast', 'Saved to Apps');
if (typeof uiToast === 'function') uiToast(message, { variant: 'success' });
diff --git a/src/renderer/modules/conversation.js b/src/renderer/modules/conversation.js
index 987da600..7657ff79 100644
--- a/src/renderer/modules/conversation.js
+++ b/src/renderer/modules/conversation.js
@@ -8,7 +8,7 @@ let _conversationBucketDateKey = _conversationLocalDateKey();
let _conversationBucketDateRefreshTimer = null;
let _conversationBucketDateRefreshBound = false;
-function _trackConversationManageResult(action, startedAt, result, errorCode = '', extra = {}) {
+function _logConversationManageResult(action, startedAt, result, errorCode = '', extra = {}) {
const payload = {
action: String(action || 'unknown'),
result: String(result || 'failure'),
@@ -22,18 +22,6 @@ function _trackConversationManageResult(action, startedAt, result, errorCode = '
} catch (_) {}
}
-function _convTrackClick(action, data) {
- try { if (window.Monitor) (() => {})(action, data || {}); } catch (_) {}
-}
-
-function _convTrackEvent(action, data) {
- try { if (window.Monitor) (() => {})(action, data || {}); } catch (_) {}
-}
-
-function _convTrackError(action, data) {
- try { if (window.Monitor) (() => {})(action, data || {}); } catch (_) {}
-}
-
function _taskTerminalHandlePresentation(payload) {
if (!payload || typeof payload !== 'object') return;
if (typeof _syncFailedFromTaskTerminal === 'function') {
@@ -60,18 +48,6 @@ try {
}
} catch (_) {}
-function _trackAgentRunResultTelemetry(cid, evData) {
- void cid;
- void evData;
-}
-
-function _trimTelemetryText(value, max) {
- const text = _normalizeFeedbackFieldText(value);
- const limit = Math.max(0, Number(max) || 0);
- if (!text || limit <= 0 || text.length <= limit) return text;
- return text.slice(0, limit) + '...';
-}
-
function _handleModelOutputErrorForUi(cid, msgDiv, rawError, extra) {
void cid;
void msgDiv;
@@ -3104,7 +3080,6 @@ const _DEFAULT_QUICK_START_ITEMS = [
let _quickStartItems = _DEFAULT_QUICK_START_ITEMS.map((item) => ({ ...item }));
let _quickStartConfigPromise = null;
let _quickStartSource = 'pc_default';
-let _quickStartLoadTelemetrySent = false;
let _SCENARIO_CONFIGS = {};
// English fallback templates — used when the i18n table doesn't yet carry
// the scenario template key. These are complete, ready-to-run tasks so a
@@ -3148,7 +3123,7 @@ function _setQuickStartItems(raw, source) {
return !!normalized;
}
-function _commanderTelemetryId(value) {
+function _commanderAttributionId(value) {
const text = String(value || '').trim();
return /^[A-Za-z0-9._-]{1,64}$/.test(text) ? text : '';
}
@@ -3161,8 +3136,8 @@ function _normalizeCommanderTemplateAttribution(raw, defaultManual = false) {
: (defaultManual ? 'manual' : '');
if (!validEntryPoint) return {};
const out = { entry_point: validEntryPoint };
- const resourceId = _commanderTelemetryId(src.resource_id || src.resourceId);
- const agentId = _commanderTelemetryId(src.agent_id || src.agentId);
+ const resourceId = _commanderAttributionId(src.resource_id || src.resourceId);
+ const agentId = _commanderAttributionId(src.agent_id || src.agentId);
const source = String(src.source || '').trim();
const recipientType = String(src.recipient_type || src.recipientType).trim();
const position = Math.round(Number(src.position) || 0);
@@ -3618,22 +3593,14 @@ function _bindEmptyStateScenarioButtons(row) {
const id = btn.dataset.scenario || '';
const config = _SCENARIO_CONFIGS[id];
const position = index + 1;
- const startedAt = Date.now();
- const telemetry = {
+ const attribution = {
resource_id: id,
agent_id: String((config && config.agentId) || ''),
position,
source: _quickStartSource,
};
- _convTrackClick('commander_quick_start', telemetry);
if (!config) {
_convLog.warn('Commander quick-start scenario config missing', { resource_id: id, position });
- _convTrackEvent('commander_quick_start_result', {
- ...telemetry,
- result: 'failure',
- reason: 'config_missing',
- duration_ms: Date.now() - startedAt,
- });
return;
}
const key = config && config.templateKey;
@@ -3641,40 +3608,22 @@ function _bindEmptyStateScenarioButtons(row) {
const tmpl = (raw && raw !== key) ? raw : (_SCENARIO_TEMPLATES_FALLBACK_EN[id] || '');
if (!tmpl) {
_convLog.warn('Commander quick-start template missing', { resource_id: id, position });
- _convTrackEvent('commander_quick_start_result', {
- ...telemetry,
- result: 'failure',
- reason: 'template_missing',
- duration_ms: Date.now() - startedAt,
- });
return;
}
const applied = await _scenarioApplyAgent(config, id);
if (!applied || applied.kind === 'unavailable') {
_convLog.warn('Commander quick-start recipient API unavailable', { resource_id: id, position });
- _convTrackEvent('commander_quick_start_result', {
- ...telemetry,
- result: 'failure',
- reason: (applied && applied.reason) || 'recipient_unavailable',
- duration_ms: Date.now() - startedAt,
- });
return;
}
const input = document.getElementById('new-chat-input');
if (!input) {
_convLog.warn('Commander quick-start composer missing', { resource_id: id, position });
- _convTrackEvent('commander_quick_start_result', {
- ...telemetry,
- result: 'failure',
- reason: 'composer_missing',
- duration_ms: Date.now() - startedAt,
- });
return;
}
input.value = tmpl;
_setCommanderTemplateAttribution(input, {
entry_point: 'quick_start',
- ...telemetry,
+ ...attribution,
recipient_type: applied.kind === 'agent' ? 'agent' : 'commander',
});
input.focus();
@@ -3696,13 +3645,6 @@ function _bindEmptyStateScenarioButtons(row) {
input.setSelectionRange(tmpl.length, tmpl.length);
}
try { input.dispatchEvent(new Event('input', { bubbles: true })); } catch (_) {}
- _convTrackEvent('commander_quick_start_result', {
- ...telemetry,
- result: applied.kind === 'agent' ? 'success' : 'fallback',
- reason: applied.reason || '',
- recipient_type: applied.kind === 'agent' ? 'agent' : 'commander',
- duration_ms: Date.now() - startedAt,
- });
});
});
}
@@ -5435,10 +5377,9 @@ async function _chatAttachUpload(cid, fileList, source = 'drop') {
// inside preload and are copied by main, so their bytes never cross IPC as
// base64; only path-less Files (clipboard image data, browser drags) keep the
// byte upload. Both routes paint the same placeholder chip, are bounded by the
-// same main-side per-kind caps and hash dedupe, and share one telemetry pair.
+// same main-side per-kind caps and hash dedupe.
async function _chatAttachUploadCore(cid, fileList, source) {
const clickPayload = _chatAttachPayload(cid, fileList, source);
- _convTrackClick('chat_attachment_upload', clickPayload);
const rejected = [];
const accepted = [];
for (const file of Array.from(fileList || [])) {
@@ -5456,22 +5397,10 @@ async function _chatAttachUploadCore(cid, fileList, source) {
]);
if (!localOutcome.attempted && !byteOutcome.attempted) {
if (rejected.length) uiAlert(t('chat.attach_rejected_prefix', { list: rejected.join('\n') }));
- _convTrackEvent('chat_attachment_upload_result', {
- ...clickPayload,
- result: rejected.length ? 'failure' : 'skipped',
- uploaded_count: 0,
- failed_count: rejected.length,
- });
return;
}
const uploadedCount = localOutcome.uploaded + byteOutcome.uploaded;
const failedCount = rejected.length;
- _convTrackEvent('chat_attachment_upload_result', {
- ...clickPayload,
- result: failedCount ? (uploadedCount ? 'partial_failure' : 'failure') : 'success',
- uploaded_count: uploadedCount,
- failed_count: failedCount,
- });
if (rejected.length) {
uiAlert(t('chat.attach_rejected_prefix', { list: rejected.join('\n') }));
@@ -5663,7 +5592,6 @@ async function _chatAttachPickAndUpload(cid, source = 'picker') {
async function _chatAttachPickAndUploadCore(cid, source) {
const basePayload = { source, target: _chatAttachTargetOf(cid) };
- _convTrackClick('chat_attachment_upload', basePayload);
let data;
try {
data = await window.orkas.invoke('conversations.attachments.pickAndUpload', { cid });
@@ -5671,34 +5599,14 @@ async function _chatAttachPickAndUploadCore(cid, source) {
_convLog.warn('native attachment picker failed', {
error_type: err && typeof err === 'object' ? 'Error' : typeof err,
});
- _convTrackEvent('chat_attachment_upload_result', {
- ...basePayload,
- result: 'failure',
- uploaded_count: 0,
- failed_count: 1,
- });
await uiAlert(t('chat.attach_upload_fail', { name: '', reason: err.message || t('chat.attach_upload_generic_fail') }));
return;
}
if (data && data.cancelled) {
- _convTrackEvent('chat_attachment_upload_result', {
- ...basePayload,
- result: 'cancelled',
- uploaded_count: 0,
- failed_count: 0,
- file_count: 0,
- });
return;
}
const picked = Array.isArray(data && data.items) ? data.items : [];
const failed = Array.isArray(data && data.failed) ? data.failed : [];
- _convTrackEvent('chat_attachment_upload_result', {
- ...basePayload,
- result: failed.length ? (picked.length ? 'partial_failure' : 'failure') : 'success',
- uploaded_count: picked.length,
- failed_count: failed.length,
- file_count: picked.length + failed.length,
- });
if (picked.length) {
const current = _chatAttachList(cid).slice();
for (const item of picked) {
@@ -5772,7 +5680,6 @@ async function _chatAttachImportPaths(cid, entries, source = 'internal_drop') {
async function _chatAttachImportPathsCore(cid, files, source) {
const clickPayload = _chatAttachPayload(cid, files, source);
- _convTrackClick('chat_attachment_upload', clickPayload);
const placeholders = [];
const current = _chatAttachList(cid).slice();
@@ -5827,12 +5734,6 @@ async function _chatAttachImportPathsCore(cid, files, source) {
}
}));
const uploadedCount = Math.max(0, placeholders.length - uploadFailed);
- _convTrackEvent('chat_attachment_upload_result', {
- ...clickPayload,
- result: uploadFailed ? (uploadedCount ? 'partial_failure' : 'failure') : 'success',
- uploaded_count: uploadedCount,
- failed_count: rejected.length,
- });
if (rejected.length) {
uiAlert(t('chat.attach_rejected_prefix', { list: rejected.join('\n') }));
@@ -5893,7 +5794,7 @@ window.attachKbFileToDraft = async function attachKbFileToDraft(channel, payload
const safeKind = error && error.failure_kind;
const failure_stage = ['input_validation', 'source_resolve', 'attachment_import'].includes(safeStage) ? safeStage : stage;
const failure_kind = ['not_found', 'permission_denied', 'disk_full'].includes(safeKind) ? safeKind : 'operation_failed';
- // Keep the UI's original message; logs/telemetry receive only the enums.
+ // Keep the UI's original message; diagnostics receive only the enums.
const wrapped = new Error((error && error.message) || String(error));
wrapped.failure_stage = failure_stage;
wrapped.failure_kind = failure_kind;
@@ -5946,7 +5847,7 @@ function _renderMessageAttachmentsHtml(names, cid) {
const kind = _chatAttachKindFromExt(ext);
const label = escapeHtml(n);
const icon = kind === 'image' && cid
- ? `<img class="chat-attach-thumb" src="${_chatMediaUrl(cid, n)}" alt="" data-monitor-resource="chat-attachment-image" />`
+ ? `<img class="chat-attach-thumb" src="${_chatMediaUrl(cid, n)}" alt="" />`
: _chatFileIconHtml(n, kind);
return `<span class="chat-attach-chip chat-msg-attach" data-attach-name="${label}"${cidAttr} title="${label}">
<button type="button" class="chat-attach-preview" aria-label="${label}"${previewDisabled}>
@@ -6187,7 +6088,6 @@ function _hydrateMessageCreatedSkillChip(msgDiv) {
chip.addEventListener('click', async () => {
const sid = chip.dataset.skillId;
if (!sid) return;
- if (window.Monitor) (() => {})('created_skill_chip_open', { skill_id: sid });
setView('skills');
const featureLoader = typeof loadRendererFeature === 'function'
? loadRendererFeature
@@ -6513,7 +6413,6 @@ async function loadConversations(options = {}) {
}
} catch (e) {
_convLog.error('load conversations failed', e);
- if (window.Monitor) (() => {})('load_conversations', { error_message: (e && e.message) || String(e) });
} finally {
_loadConversationsInFlight = null;
_loadConversationsMode = '';
@@ -6927,12 +6826,12 @@ async function _toggleConversationPinned(cid, pinned) {
renderConversationList();
_refreshChatHeader();
}
- _trackConversationManageResult('pin', startedAt, 'success', '', { target_state: pinned });
+ _logConversationManageResult('pin', startedAt, 'success', '', { target_state: pinned });
} catch (err) {
conversations = snapshot;
renderConversationList();
_refreshChatHeader();
- _trackConversationManageResult('pin', startedAt, 'failure', 'pin_failed', { target_state: pinned });
+ _logConversationManageResult('pin', startedAt, 'failure', 'pin_failed', { target_state: pinned });
_convLog.warn('toggle conversation pin failed', {
error_type: err && typeof err.name === 'string' ? err.name : 'unknown',
});
@@ -6954,7 +6853,7 @@ async function _saveConversationTitle(cid, raw, opts = {}) {
const current = (conv && conv.title) || t('chat.new_conv_title');
const title = _normaliseConversationTitle(raw);
if (!title) {
- _trackConversationManageResult('rename', startedAt, 'blocked', 'empty_title');
+ _logConversationManageResult('rename', startedAt, 'blocked', 'empty_title');
try { await uiAlert(t('chat.conv_rename_empty')); } catch (_) {}
return false;
}
@@ -6985,7 +6884,7 @@ async function _saveConversationTitle(cid, raw, opts = {}) {
if (window.ConversationInfo && typeof window.ConversationInfo.refresh === 'function') {
window.ConversationInfo.refresh(cid, { silent: true });
}
- _trackConversationManageResult('rename', startedAt, 'success');
+ _logConversationManageResult('rename', startedAt, 'success');
if (typeof opts.afterSave === 'function') {
try { await opts.afterSave(data.conversation); } catch (err) {
_convLog.warn('conversation rename follow-up failed', {
@@ -6995,7 +6894,7 @@ async function _saveConversationTitle(cid, raw, opts = {}) {
}
return true;
} catch (err) {
- _trackConversationManageResult('rename', startedAt, 'failure', 'rename_failed');
+ _logConversationManageResult('rename', startedAt, 'failure', 'rename_failed');
_convLog.warn('rename conversation failed', {
error_type: err && typeof err.name === 'string' ? err.name : 'unknown',
});
@@ -7076,7 +6975,7 @@ async function _deleteConversationWithConfirm(cid, opts = {}) {
throw new Error(result?.error || `delete failed (${response.status || 'unknown'})`);
}
} catch (err) {
- _trackConversationManageResult('delete', startedAt, 'failure', 'delete_failed');
+ _logConversationManageResult('delete', startedAt, 'failure', 'delete_failed');
_convLog.warn('delete conversation failed', {
error_type: err && typeof err.name === 'string' ? err.name : 'unknown',
});
@@ -7103,7 +7002,7 @@ async function _deleteConversationWithConfirm(cid, opts = {}) {
}
}
renderConversationList();
- _trackConversationManageResult('delete', startedAt, 'success');
+ _logConversationManageResult('delete', startedAt, 'success');
if (typeof opts.afterDelete === 'function') {
try { await opts.afterDelete(cid); } catch (err) {
_convLog.warn('conversation delete follow-up failed', {
@@ -7275,9 +7174,6 @@ function _bindConversationSidebarItems(container, opts = {}) {
// the transcript, reset its scroll position, refresh attachments, and
// steal composer focus even though the user's destination did not change.
if (currentView === 'conversation' && currentCid === cid) return;
- _convTrackClick('sidebar_conversation_open', {
- scope: opts.scope || (selector.includes('nested') ? 'project' : 'unprojected'),
- });
setView('conversation', cid);
});
});
@@ -7388,7 +7284,6 @@ function _ensureConvCreateAgentInline() {
btn.textContent = t('chat.create_agent_inline');
btn.addEventListener('click', () => {
if (!currentCid) return;
- if (window.Monitor) (() => {})('create_agent_from_chat', { cid: currentCid });
const input = document.getElementById('chat-input');
if (!input) return;
input.value = t('chat.create_agent_message');
@@ -9516,25 +9411,6 @@ function _marketplaceInstallRequestErrorType(errorCode) {
return 'runtime';
}
-function _marketplaceTrackInstallRequestResult(startedAt, req, result, errorCode = '') {
- const safeResult = /^(?:success|failure|cancelled)$/.test(result) ? result : 'failure';
- const safeCode = /^[a-z][a-z0-9_]{0,63}$/.test(String(errorCode || ''))
- ? String(errorCode)
- : 'install_request_failed';
- const payload = {
- result: safeResult,
- action: 'install',
- resource_kind: req?.kind === 'skill' ? 'skill' : 'agent',
- surface: 'conversation',
- duration_ms: Math.max(0, Date.now() - startedAt),
- };
- if (safeResult !== 'success') {
- payload.error_type = _marketplaceInstallRequestErrorType(safeCode);
- payload.error_code = safeCode;
- }
- _convTrackEvent('marketplace_action_result', payload);
-}
-
function _marketplaceRequestStatusLabel(status) {
if (status === 'installed') return t('marketplace_request.status_installed');
if (status === 'skipped') return t('marketplace_request.status_skipped');
@@ -9875,13 +9751,6 @@ function _mountMarketplaceInstallRequests(host, msgDiv, message, opts) {
async function _resolveMarketplaceInstallRequest(card, req, cid, msgId, decision) {
if (!card || card.dataset.busy === '1') return;
- const startedAt = Date.now();
- let resultTracked = false;
- const trackResult = (result, errorCode = '') => {
- if (resultTracked) return;
- resultTracked = true;
- _marketplaceTrackInstallRequestResult(startedAt, req, result, errorCode);
- };
_setMarketplaceCardBusy(card, true);
const installBtn = card.querySelector('[data-mp-decision="install"]');
if (decision === 'install' && installBtn) installBtn.textContent = t('marketplace.installing');
@@ -9896,13 +9765,6 @@ async function _resolveMarketplaceInstallRequest(card, req, cid, msgId, decision
throw new Error((data && data.error) || 'marketplace install request failed');
}
const updated = data.request || { ...req, status: decision === 'install' ? 'installed' : 'skipped' };
- if (updated.status === 'installed') trackResult('success');
- else if (updated.status === 'skipped') trackResult('cancelled', 'user_skipped');
- else if (updated.status === 'failed') {
- trackResult('failure', _marketplaceInstallRequestErrorCode(data.install_error));
- } else {
- trackResult('failure', 'unknown_status');
- }
_renderMarketplaceInstallCard(card, updated, cid, msgId);
if (updated.status === 'installed') {
if (updated.kind === 'agent') { try { loadAgents?.(true); } catch (_) {} }
@@ -9911,13 +9773,10 @@ async function _resolveMarketplaceInstallRequest(card, req, cid, msgId, decision
const submissionText = data.submission && data.submission.text;
if (submissionText) await sendInCurrentConversation(submissionText);
} catch (err) {
- trackResult('failure', 'request_failed');
_setMarketplaceCardBusy(card, false);
const reason = (err && err.message) || String(err);
_convLog.warn('marketplace install request failed', reason);
try { await uiAlert(_marketplaceInstallFailedText(req.kind, req.name || req.id, reason)); } catch (_) {}
- } finally {
- if (!resultTracked) trackResult('failure', 'install_request_failed');
}
}
@@ -10918,44 +10777,6 @@ async function _retryFailedAssistantMessage(msgDiv) {
});
}
-// ─── Send flows ───
-
-function _chatModelTelemetryContext(data = {}) {
- const source = data && typeof data === 'object' ? data : {};
- const provider = String(source.provider || '').trim().slice(0, 80);
- const model = String(source.model || '').trim().slice(0, 160);
- if (provider || model) {
- try {
- if (typeof _composerModelTelemetryContext === 'function') {
- return _composerModelTelemetryContext({ provider, model }, model);
- }
- } catch (_) {}
- const legacyDynamicProvider = /^cp:/i.test(provider) || provider === 'custom-openai';
- const userEnteredModel = legacyDynamicProvider || provider === 'custom' || provider === 'openrouter';
- const normalizedProvider = legacyDynamicProvider ? 'custom' : provider;
- return {
- provider: /^[A-Za-z0-9][A-Za-z0-9._:-]{0,79}$/.test(normalizedProvider)
- ? normalizedProvider
- : 'unknown',
- model: userEnteredModel
- ? 'custom'
- : (/^[A-Za-z0-9][A-Za-z0-9._:/+\-]{0,159}$/.test(model) ? model : 'unknown'),
- };
- }
- try {
- return typeof _currentComposerModelTelemetryContext === 'function'
- ? _currentComposerModelTelemetryContext()
- : {};
- } catch (_) {
- return {};
- }
-}
-
-function _trackChatSendResult(result, data = {}) {
- void result;
- void data;
-}
-
// Re-entrancy gate for handleNewChatSubmit. The Enter-key path (state.js) calls
// the function directly — it never checks the send button's disabled state — and
// the composer text is deliberately NOT cleared until conversation-create
@@ -10978,65 +10799,30 @@ async function handleNewChatSubmit() {
? getChatUseSelections('new-chat')
: [];
const entryAttribution = _readCommanderTemplateAttribution(input);
- const modelTelemetry = _chatModelTelemetryContext();
- const sendAttemptStartedAt = performance.now();
- const sendAttempt = {
- conversation_id: '',
- source_view: 'new_chat',
- content_length: requestText.length,
- attachment_count: draftItems.filter((a) => a.status !== 'error').length,
- ...modelTelemetry,
- ...entryAttribution,
- };
const multiDispatch = _composerEffectiveDispatchMode('new-chat');
const unresolvedQuickStart = _unresolvedQuickStartPlaceholder(input);
const unresolvedOss = typeof unresolvedOssTemplatePlaceholder === 'function'
? unresolvedOssTemplatePlaceholder(input)
: '';
if (unresolvedQuickStart || unresolvedOss) {
- _trackChatSendResult('failure', {
- ...sendAttempt,
- duration_ms: performance.now() - sendAttemptStartedAt,
- failure_stage: 'preflight',
- failure_reason: 'template_incomplete',
- });
await uiAlert(t(unresolvedQuickStart ? 'new_chat.quick.task_required' : 'oss.task_required'));
return;
}
if (!ensureModelConfigured()) {
- _trackChatSendResult('failure', {
- ...sendAttempt,
- duration_ms: performance.now() - sendAttemptStartedAt,
- failure_stage: 'preflight',
- failure_reason: 'model_not_configured',
- });
return;
}
const releaseAttachmentSend = _chatAttachTryBeginSend(DRAFT_CID);
if (!releaseAttachmentSend) {
- _trackChatSendResult('failure', {
- ...sendAttempt,
- duration_ms: performance.now() - sendAttemptStartedAt,
- failure_stage: 'preflight',
- failure_reason: 'attachment_uploading',
- });
await uiAlert(t('chat.attach_still_uploading'));
return;
}
const attachmentSnapshot = await _chatAttachSnapshotForSend(DRAFT_CID, { requireServerMatch: true });
if (!attachmentSnapshot.ok) {
releaseAttachmentSend();
- _trackChatSendResult('failure', {
- ...sendAttempt,
- duration_ms: performance.now() - sendAttemptStartedAt,
- failure_stage: 'preflight',
- failure_reason: 'attachment_adopt_failed',
- });
await uiAlert(t('chat.attach_sync_failed'));
return;
}
draftItems = attachmentSnapshot.items;
- sendAttempt.attachment_count = draftItems.length;
const references = _referenceSnapshotsForQuotes(quotes);
// Keep resource selections in the composer until attachment adoption has
// completed. A failed preflight must leave the whole request retryable.
@@ -11100,12 +10886,6 @@ async function handleNewChatSubmit() {
resource_id: entryAttribution.resource_id || '',
error: e && e.message ? e.message : String(e || ''),
});
- _trackChatSendResult('failure', {
- ...sendAttempt,
- duration_ms: performance.now() - sendAttemptStartedAt,
- failure_stage: 'conversation_create',
- failure_reason: 'conversation_create_failed',
- });
await uiAlert(t('chat.create_conv_failed_with_reason', { reason: e.message || e }));
if (newBtn) newBtn.disabled = false;
_newChatSubmitting = false; // text kept in the input — allow a retry submit
@@ -11157,12 +10937,6 @@ async function handleNewChatSubmit() {
error_code: 'discard_empty_failed',
});
}
- _trackChatSendResult('failure', {
- ...sendAttempt,
- duration_ms: performance.now() - sendAttemptStartedAt,
- failure_stage: 'preflight',
- failure_reason: 'attachment_adopt_failed',
- });
await uiAlert(t('chat.attach_adopt_failed', { reason: adoptionError }));
if (newBtn) newBtn.disabled = false;
_newChatSubmitting = false;
@@ -11570,7 +11344,6 @@ async function sendInConversation(cid, content, extra, options = {}) {
if (!cid) return { started: false, aborted: false, errored: false, result: 'failure' };
const startedAt = performance.now();
const sendOptions = options && typeof options === 'object' ? options : {};
- const modelTelemetry = _chatModelTelemetryContext(sendOptions);
const entryAttribution = _normalizeCommanderTemplateAttribution(sendOptions);
const statAgentId = String(sendOptions.agent_id || '');
let doneResult = null;
@@ -11708,20 +11481,6 @@ async function sendInConversation(cid, content, extra, options = {}) {
success: false,
});
}
- if (window.Monitor) {
- (() => {})('chat_send_result', {
- result: 'failure',
- conversation_id: cid,
- source_view: sendOptions.source_view || 'conversation',
- content_length: measuredContentLength,
- attachment_count: attachmentCount,
- duration_ms: durationMs,
- failure_stage: taskStarted ? 'stream' : 'preflight',
- failure_reason: taskStarted ? 'stream_error' : 'stream_not_started',
- ...modelTelemetry,
- ...entryAttribution,
- });
- }
_convLog.warn('chat send request failed', {
cid,
error_type: err && typeof err.name === 'string' ? err.name : 'unknown',
@@ -14158,33 +13917,7 @@ function createChatController(config) {
} finally {
const wasAborted = pending?.aborted;
const wasErrored = pending?.errored;
- const terminalPending = pending;
terminalResult = { started: true, aborted: !!wasAborted, errored: !!wasErrored, accepted: !!pending?.accepted };
- const telemetrySurface = String(config.telemetrySurface || '');
- if (telemetrySurface === 'agent_edit' || telemetrySurface === 'skill_edit') {
- const waitingForInput = terminalPending?.waitingForInput === true;
- const missingTerminal = !wasAborted && !wasErrored && !terminalPending?.sawFinal && !waitingForInput;
- const result = wasAborted ? 'cancelled' : ((wasErrored || missingTerminal) ? 'failure' : 'success');
- const payload = {
- surface: telemetrySurface === 'agent_edit' ? 'agent' : 'skill',
- result,
- terminal_status: wasAborted ? 'cancelled' : ((wasErrored || missingTerminal) ? 'failed' : waitingForInput ? 'waiting_input' : 'completed'),
- duration_ms: Math.max(
- 0,
- Date.now() - Number(terminalPending?.startedAtMs || Date.now()),
- ),
- has_output: !!terminalPending?.sawOutput,
- };
- if (result === 'failure') {
- payload.failure_phase = missingTerminal
- ? 'result'
- : String(terminalPending?.failurePhase || 'stream_event');
- payload.error_code = missingTerminal
- ? 'missing_terminal'
- : String(terminalPending?.failureCode || 'interactive_run_failed');
- }
- _convTrackEvent('interactive_task_run_result', payload);
- }
_clearOffViewGroupProcessEvents(id);
pending = null;
_updateSendUI();
@@ -15426,7 +15159,6 @@ function _finalizeActorPlaceholder(ph, gm, cid, archive) {
// Group-chat bus event router. Each event is one of:
// { type: 'message', cid, msg: GroupMessage, turn_id? }
// { type: 'process', cid, actor, turn_id?, data: { type, text?, event? } }
-// { type: 'agent_run_result', cid, actor, actor_type, turn_id?, data }
// { type: 'artifact_created', cid, actor, turn_id?, artifact: { id, title, agent_id } }
// { type: 'state_changed', cid, state: { status, in_flight }, active_turns? }
// { type: 'member_joined', cid, actor }
@@ -15434,9 +15166,6 @@ function _finalizeActorPlaceholder(ph, gm, cid, archive) {
function _handleGroupBusEvent(cid, streamingMsg, evData, { archive = false } = {}) {
if (!evData || typeof evData !== 'object') return;
if (evData.type === 'message') window.CliAsyncInput?.observe(cid, evData.msg);
- if (evData.type === 'agent_run_result') {
- return;
- }
if (
evData.type === 'process'
|| evData.type === 'artifact_created'
@@ -16339,7 +16068,7 @@ function _formatEventLine(evt, displayContext) {
if (runtimeDurationMs == null) return null;
// Keep the process summary compact: expose only total wall time. Provider,
// aggregate tool, compaction, and retry breakdowns remain internal
- // telemetry; individual completed tool rows show their persisted E2E time.
+ // diagnostics; individual completed tool rows show their persisted E2E time.
return t('chat.stream.runtime_total', { duration: _formatProcessDuration(runtimeDurationMs) });
}
diff --git a/src/renderer/modules/delete-file-confirm.js b/src/renderer/modules/delete-file-confirm.js
index ad81402f..6ef52868 100644
--- a/src/renderer/modules/delete-file-confirm.js
+++ b/src/renderer/modules/delete-file-confirm.js
@@ -230,26 +230,6 @@ function _createDeleteConfirmBatch(container, key, hasTurnId) {
duration_ms: Math.max(0, Date.now() - batch.createdAt),
});
} catch (_) {}
- try {
- if (window.Monitor) {
- const decision = granted ? 'allow' : 'deny';
- const result = failedCount > 0 ? 'failure' : 'success';
- const payload = {
- result,
- decision,
- file_count: count,
- failed_count: failedCount,
- duration_ms: Math.max(0, Date.now() - batch.createdAt),
- };
- if (failedCount > 0) {
- payload.error_code = 'response_failed';
- payload.error_type = 'ipc';
- }
- Monitor.event('delete_file_confirmation_result', payload);
- }
- } catch (_) {
- // File approval must not depend on observability.
- }
// The token state flip alone doesn't wake the LLM — Step 1 already
// ended the turn, so without a fresh user message Step 2 never fires
// and the file isn't actually unlinked. Auto-dispatch a short user
diff --git a/src/renderer/modules/ipc-shim.js b/src/renderer/modules/ipc-shim.js
index c347e19a..ded1ab33 100644
--- a/src/renderer/modules/ipc-shim.js
+++ b/src/renderer/modules/ipc-shim.js
@@ -161,7 +161,7 @@ function _mockErrorResponse(error, status) {
};
}
-function _monitorIpcError(kind, channel, data) {
+function _logIpcError(kind, channel, data) {
try {
if (_ipcErrorSentCount >= _IPC_ERROR_MAX_PER_SESSION) return;
const payload = {
@@ -248,7 +248,7 @@ function _streamResponse(channel, payload, signal) {
try { controller.close(); } catch (_) {}
return;
}
- _monitorIpcError('ipc_stream', channel, _ipcFailureMeta(err));
+ _logIpcError('ipc_stream', channel, _ipcFailureMeta(err));
try { controller.error(new Error('ipc stream failed')); } catch (_) {}
});
},
@@ -307,7 +307,7 @@ async function _uploadBinary(channel, options, extraParams) {
const result = await window.orkas.invoke(channel, { ...(extraParams || {}), name, data });
return _mockJsonResponse(result);
} catch (err) {
- _monitorIpcError('ipc_invoke', channel, { ..._ipcFailureMeta(err), transport: 'upload' });
+ _logIpcError('ipc_invoke', channel, { ..._ipcFailureMeta(err), transport: 'upload' });
throw new Error('ipc upload failed');
}
}
@@ -333,7 +333,7 @@ function apiFetch(url, options) {
const route = _matchRoute(method, pathname);
if (!route) {
_shimLog.warn('unmatched API route', { method });
- _monitorIpcError('ipc_unmatched_route', 'unmatched', { method });
+ _logIpcError('ipc_unmatched_route', 'unmatched', { method });
return Promise.resolve(_mockErrorResponse('unknown API route', 404));
}
@@ -386,7 +386,7 @@ function apiFetch(url, options) {
return _mockJsonResponse(result);
})
.catch((err) => {
- _monitorIpcError('ipc_invoke', channel, _ipcFailureMeta(err));
+ _logIpcError('ipc_invoke', channel, _ipcFailureMeta(err));
return _mockErrorResponse('ipc request failed', 500);
});
}
@@ -444,7 +444,7 @@ async function apiLibraryFetch(projectId, url, options = {}) {
}
return _mockJsonResponse(result);
} catch (err) {
- _monitorIpcError('ipc_invoke', channel || 'projects.files.upload', _ipcFailureMeta(err));
+ _logIpcError('ipc_invoke', channel || 'projects.files.upload', _ipcFailureMeta(err));
return _mockErrorResponse('ipc request failed', 500);
}
}
diff --git a/src/renderer/modules/lazy-features.js b/src/renderer/modules/lazy-features.js
index bb55dee3..3f78afab 100644
--- a/src/renderer/modules/lazy-features.js
+++ b/src/renderer/modules/lazy-features.js
@@ -57,7 +57,7 @@ function _rendererFeatureNow() {
return Date.now();
}
-function _rendererFeatureTelemetryName(feature) {
+function _rendererFeatureLogName(feature) {
return Object.prototype.hasOwnProperty.call(_rendererFeatureManifest, feature)
? feature
: 'unknown';
@@ -65,7 +65,7 @@ function _rendererFeatureTelemetryName(feature) {
function _trackRendererFeatureLoad(result, feature, startedAt, retryCount, errorCode = '') {
const normalizedResult = result === 'success' ? 'success' : 'failure';
- const normalizedFeature = _rendererFeatureTelemetryName(feature);
+ const normalizedFeature = _rendererFeatureLogName(feature);
const normalizedCode = errorCode === 'unknown_feature'
? 'unknown_feature'
: 'script_load_failed';
diff --git a/src/renderer/modules/library-transfer.js b/src/renderer/modules/library-transfer.js
index 2670e0fa..d157e26a 100644
--- a/src/renderer/modules/library-transfer.js
+++ b/src/renderer/modules/library-transfer.js
@@ -77,7 +77,7 @@
return state?.loading === false && state?.destinationReady === true;
}
- function _transferFailureTelemetry(error) {
+ function _transferFailureDetails(error) {
const raw = typeof error === 'string'
? error.trim()
: String((error && (error.error_code || error.code || error.error || error.message)) || '').trim();
@@ -160,12 +160,6 @@
return data.tree;
}
- function _track(name, payload, kind = 'event') {
- void name;
- void payload;
- void kind;
- }
-
async function openLibraryTransfer(opts) {
const source = opts?.source;
const paths = Array.from(new Set((opts?.paths || []).map((item) => String(item || '')).filter(Boolean)));
@@ -319,15 +313,8 @@
overlay.querySelector('[data-transfer-cancel]')?.addEventListener('click', close);
confirmBtn.addEventListener('click', async () => {
if (!_canSubmitTransfer({ loading: loadingFolders, destinationReady }) || confirmBtn.disabled) return;
- const startedAt = performance.now();
confirmBtn.disabled = true;
showError('');
- _track('library_transfer_submit', {
- mode,
- source_scope: source.scope,
- destination_scope: currentRef.scope,
- entry_count: paths.length,
- }, 'click');
let result;
try {
result = await root.orkas.invoke('library.transfer', {
@@ -337,36 +324,14 @@
destination: { ...currentRef, dir: targetDir },
});
} catch (err) {
- const failure = _transferFailureTelemetry(err);
- _track('library_transfer_result', {
- result: 'failure',
- mode,
- source_scope: source.scope,
- destination_scope: currentRef.scope,
- entry_count: paths.length,
- succeeded_count: 0,
- failed_count: paths.length,
- duration_ms: Math.round(performance.now() - startedAt),
- ...failure,
- });
+ const failure = _transferFailureDetails(err);
transferLog.warn('library transfer failed', { mode, source_scope: source.scope, destination_scope: currentRef.scope, ...failure });
showError(t('contexts.transfer.error_generic'));
confirmBtn.disabled = false;
return;
}
if (!result?.ok) {
- const failure = _transferFailureTelemetry(result);
- _track('library_transfer_result', {
- result: 'failure',
- mode,
- source_scope: source.scope,
- destination_scope: currentRef.scope,
- entry_count: paths.length,
- succeeded_count: 0,
- failed_count: paths.length,
- duration_ms: Math.round(performance.now() - startedAt),
- ...failure,
- });
+ const failure = _transferFailureDetails(result);
transferLog.warn('library transfer failed', { mode, source_scope: source.scope, destination_scope: currentRef.scope, ...failure });
showError(_errorLabel(failure.error_code));
confirmBtn.disabled = false;
@@ -378,18 +343,7 @@
? 'success'
: (succeededCount > 0 ? 'partial' : 'failure');
const firstError = result.results?.find((row) => !row.ok)?.error;
- const failure = resultValue === 'success' ? {} : _transferFailureTelemetry(firstError || 'transfer_failed');
- _track('library_transfer_result', {
- result: resultValue,
- mode,
- source_scope: source.scope,
- destination_scope: currentRef.scope,
- entry_count: paths.length,
- succeeded_count: succeededCount,
- failed_count: failedCount,
- duration_ms: Math.round(performance.now() - startedAt),
- ...failure,
- });
+ const failure = resultValue === 'success' ? {} : _transferFailureDetails(firstError || 'transfer_failed');
if (succeededCount === 0) {
transferLog.warn('library transfer failed', { mode, source_scope: source.scope, destination_scope: currentRef.scope, ...failure });
showError(_errorLabel(firstError));
@@ -428,7 +382,7 @@
_folderRows,
_projectsFromResponse,
_canSubmitTransfer,
- _transferFailureTelemetry,
+ _transferFailureDetails,
_createLatestFolderLoader,
};
}
diff --git a/src/renderer/modules/local-agents.js b/src/renderer/modules/local-agents.js
index 5ea310cf..c642f427 100644
--- a/src/renderer/modules/local-agents.js
+++ b/src/renderer/modules/local-agents.js
@@ -96,9 +96,8 @@ let _localCliEntriesInFlight = null;
let _localCliPresenceEntries = null;
let _localCliPresenceInFlight = null;
let _externalCliVisibleEntries = [];
-let _externalCliDetectionTelemetryInFlight = false;
-/** Bounded telemetry/UI state for the current renderer-side discovery cache.
+/** Bounded UI state for the current renderer-side discovery cache.
* A background refresh never hides a completed cache; `detecting` is reserved
* for a cold path lookup where no result exists yet. Once path-only discovery
* finds a CLI, availability can be reported immediately while its version is
@@ -181,8 +180,7 @@ function _replaceLocalCliEntry(entries, nextEntry) {
/** Validate installed CLI entries concurrently through the single-type IPC.
* Each successful response is merged into the stable presence-order list and
* surfaced immediately. The aggregate promise still resolves only after all
- * probes settle so callers can emit one bounded telemetry row and cache only
- * a fully validated snapshot. */
+ * probes settle so callers can cache one fully validated snapshot. */
async function _validateInstalledLocalCliEntries(entries, installedTypes, onEntry) {
if (_localCliEntriesInFlight) return _localCliEntriesInFlight;
const initialEntries = Array.isArray(entries)
@@ -234,45 +232,6 @@ async function loadLocalCliEntries(options = {}) {
//
let _extCliSelectApi = null;
-function _trackExternalCliDetectionResult({
- result,
- entries,
- startedAt,
- errorCode = '',
-}) {
- if (!window.Monitor) return;
- const list = Array.isArray(entries) ? entries : [];
- const typesFor = (predicate) => list
- .filter(predicate)
- .map(entry => String(entry?.type || ''))
- .filter(Boolean)
- .sort()
- .join(',');
- const availableTypes = typesFor(entry => entry?.available === true);
- const notFoundTypes = typesFor(entry => entry?.error === 'not_found');
- const versionTooOldTypes = typesFor(entry => entry?.error === 'version_too_old');
- const versionTimeoutTypes = typesFor(entry => entry?.error === 'version_timeout');
- const versionUnknownTypes = typesFor(entry => entry?.error === 'version_unknown');
- const payload = {
- result,
- available_count: availableTypes ? availableTypes.split(',').length : 0,
- not_found_count: notFoundTypes ? notFoundTypes.split(',').length : 0,
- version_too_old_count: versionTooOldTypes ? versionTooOldTypes.split(',').length : 0,
- version_timeout_count: versionTimeoutTypes ? versionTimeoutTypes.split(',').length : 0,
- version_unknown_count: versionUnknownTypes ? versionUnknownTypes.split(',').length : 0,
- available_types: availableTypes,
- not_found_types: notFoundTypes,
- version_too_old_types: versionTooOldTypes,
- version_timeout_types: versionTimeoutTypes,
- version_unknown_types: versionUnknownTypes,
- duration_ms: Math.max(0, Date.now() - startedAt),
- };
- if (result !== 'success') payload.error_code = errorCode || 'unknown';
- try {
- Monitor.event('external_cli_detect_result', payload);
- } catch (_) {}
-}
-
function _setExternalCliDetectionBusy(
busy,
{ disableSelect = false, showTitleStatus = busy } = {},
@@ -419,14 +378,6 @@ async function mountExternalCliSelect(onChange) {
const mount = document.getElementById('agent-modal-ext-cli-select');
if (!mount) return null;
const cachedEntries = _localCliEntries;
- // Concurrent mounts share the same two discovery requests. Only the mount
- // that starts the path lookup owns the aggregate telemetry row.
- const ownsDetectionTelemetry = !_externalCliDetectionTelemetryInFlight;
- if (ownsDetectionTelemetry) _externalCliDetectionTelemetryInFlight = true;
- const detectionStartedAt = Date.now();
-
- try {
-
// Cold entry: put the progress copy in the menu itself and keep the title
// clean. Cached entry: immediately select its first available CLI and use
// the title-side live region only for the background update.
@@ -471,13 +422,6 @@ async function mountExternalCliSelect(onChange) {
_localCliEntries = presence.entries;
_localCliPresenceEntries = null;
_setExternalCliDetectionBusy(false);
- if (ownsDetectionTelemetry) {
- _trackExternalCliDetectionResult({
- result: 'success',
- entries: presence.entries,
- startedAt: detectionStartedAt,
- });
- }
return _extCliSelectApi;
}
_setExternalCliDetectionBusy(true, {
@@ -506,21 +450,7 @@ async function mountExternalCliSelect(onChange) {
);
_localCliPresenceEntries = null;
_setExternalCliDetectionBusy(false);
- if (ownsDetectionTelemetry) {
- const hasFallback = !!cachedEntries || presence.ok;
- _trackExternalCliDetectionResult({
- result: validated.ok ? 'success' : (hasFallback ? 'fallback' : 'failure'),
- entries: validated.entries.length > 0
- ? validated.entries
- : (presence.ok ? presence.entries : (cachedEntries || [])),
- startedAt: detectionStartedAt,
- errorCode: validated.ok ? '' : (hasFallback ? 'validation_failed' : 'invoke_failed'),
- });
- }
- return _extCliSelectApi;
- } finally {
- if (ownsDetectionTelemetry) _externalCliDetectionTelemetryInFlight = false;
- }
+ return _extCliSelectApi;
}
/** Read the currently-selected CLI type from the External tab, or null when
diff --git a/src/renderer/modules/marketplace.js b/src/renderer/modules/marketplace.js
index b13c6b98..75b1cc19 100644
--- a/src/renderer/modules/marketplace.js
+++ b/src/renderer/modules/marketplace.js
@@ -1984,7 +1984,7 @@ function _mpActionResult(result) {
return result === 'success' || result === 'cancelled' ? result : 'failure';
}
-function _mpTrackActionResult(startedAt, action, kind, result, errorCode = '') {
+function _mpLogActionResult(startedAt, action, kind, result, errorCode = '') {
const safeAction = _mpActionName(action);
const safeKind = _mpResourceKind(kind);
const safeResult = _mpActionResult(result);
@@ -2043,11 +2043,11 @@ async function _mpInstall(kind, id, itemOverride = null) {
const startedAt = Date.now();
const initialStatus = _mpInstallStatus(kind, item);
const actionName = initialStatus.installed && initialStatus.updateAvailable ? 'update' : 'install';
- let resultTracked = false;
- const trackResult = (result, errorCode = '') => {
- if (resultTracked) return;
- resultTracked = true;
- _mpTrackActionResult(startedAt, actionName, kind, result, errorCode);
+ let resultLogged = false;
+ const logResult = (result, errorCode = '') => {
+ if (resultLogged) return;
+ resultLogged = true;
+ _mpLogActionResult(startedAt, actionName, kind, result, errorCode);
};
_mpState.installing.add(key);
_mpRender();
@@ -2067,7 +2067,7 @@ async function _mpInstall(kind, id, itemOverride = null) {
const installed = await invokeInstall(false);
// Main's completed install response is the durable boundary. Local cache,
// list refresh, alerts, and rendering cannot reverse this success.
- trackResult('success');
+ logResult('success');
_mpApplyInstalledState(kind, item, installed);
await _mpRefreshAfterAction(kind);
// Success: no toast — the button flips to "Installed" + state set above is the signal.
@@ -2092,26 +2092,26 @@ async function _mpInstall(kind, id, itemOverride = null) {
if (action === 'force') {
try {
const installed = await invokeInstall(true);
- trackResult('success');
+ logResult('success');
_mpApplyInstalledState(kind, item, installed);
await _mpRefreshAfterAction(kind);
} catch (forceErr) {
- trackResult('failure', _mpActionErrorCode(forceErr));
+ logResult('failure', _mpActionErrorCode(forceErr));
uiAlert(_mpInstallFailedText(kind, item, forceErr));
}
} else {
- trackResult('cancelled', 'validation_cancelled');
+ logResult('cancelled', 'validation_cancelled');
}
} else {
- trackResult('failure', _mpActionErrorCode(err, 'quality_rejected'));
+ logResult('failure', _mpActionErrorCode(err, 'quality_rejected'));
uiAlert(_mpInstallFailedText(kind, item, err));
}
} else {
- trackResult('failure', _mpActionErrorCode(err));
+ logResult('failure', _mpActionErrorCode(err));
uiAlert(_mpInstallFailedText(kind, item, err));
}
} finally {
- if (!resultTracked) trackResult('failure', 'operation_failed');
+ if (!resultLogged) logResult('failure', 'operation_failed');
_mpState.installing.delete(key);
_mpRender();
if (_mpState.view === 'detail') _mpRenderDetail();
@@ -2132,11 +2132,11 @@ async function _mpUninstall(kind, id) {
const key = `${kind}:${id}`;
if (_mpState.installing.has(key)) return;
const startedAt = Date.now();
- let resultTracked = false;
- const trackResult = (result, errorCode = '') => {
- if (resultTracked) return;
- resultTracked = true;
- _mpTrackActionResult(startedAt, 'uninstall', kind, result, errorCode);
+ let resultLogged = false;
+ const logResult = (result, errorCode = '') => {
+ if (resultLogged) return;
+ resultLogged = true;
+ _mpLogActionResult(startedAt, 'uninstall', kind, result, errorCode);
};
_mpState.installing.add(key);
_mpState.uninstalling.add(key);
@@ -2145,16 +2145,16 @@ async function _mpUninstall(kind, id) {
const channel = kind === 'agent' ? 'marketplace.uninstallAgent' : 'marketplace.uninstallSkill';
const r = await window.orkas.invoke(channel, { id });
if (!r || r.ok === false) throw _mpErrorFromResponse(r, 'uninstall failed');
- trackResult('success');
+ logResult('success');
_mpApplyUninstalledState(kind, id);
await _mpRefreshAfterAction(kind);
// Success: button flips back to "Install" — no toast needed. (Failures still alert.)
} catch (err) {
- trackResult('failure', _mpActionErrorCode(err));
+ logResult('failure', _mpActionErrorCode(err));
const msg = _mpUserErrorMessage(err, 'marketplace.action_failed_retry_later');
uiAlert(t('marketplace.uninstall_failed').replace('{reason}', msg));
} finally {
- if (!resultTracked) trackResult('failure', 'operation_failed');
+ if (!resultLogged) logResult('failure', 'operation_failed');
_mpState.installing.delete(key);
_mpState.uninstalling.delete(key);
_mpRender();
diff --git a/src/renderer/modules/md-view-edit.js b/src/renderer/modules/md-view-edit.js
index 373f8d8c..cbfd255b 100644
--- a/src/renderer/modules/md-view-edit.js
+++ b/src/renderer/modules/md-view-edit.js
@@ -353,16 +353,6 @@ function _mveActionButton(state, action, labelKey, iconName, extraClass) {
return `<button type="button" class="${cls}" data-mve-action="${action}" aria-label="${escapeHtml(label)}" title="${escapeHtml(label)}">${icon}</button>`;
}
-function _mveTrack(action, state, data) {
- try {
- if (!window.Monitor) return;
- (() => {})(action, Object.assign({
- source: state && state.source ? String(state.source.kind || '') : '',
- can_save: !!(state && state.caps && state.caps.save),
- }, data || {}));
- } catch (_) {}
-}
-
function _mveRenderView(state) {
state.mode = 'view';
const bodyEl = state.bodyEl;
@@ -485,21 +475,6 @@ function _mveSourceType(source) {
return source.cid ? 'conversation' : 'workspace';
}
-function _mveTrackSaveResult(source, content, startedAt, result, errorCode = '') {
- try {
- if (!window.Monitor) return;
- const payload = {
- result,
- surface: 'markdown_editor',
- source_type: _mveSourceType(source),
- char_count: String(content || '').length,
- duration_ms: Math.max(0, Date.now() - startedAt),
- };
- if (result !== 'success') payload.error_code = errorCode || 'unknown';
- Monitor.event('text_editor_save_result', payload);
- } catch (_) {}
-}
-
async function _mveSave(state) {
if (state.saving && state.savePromise) return state.savePromise;
const ta = state.bodyEl.querySelector('[data-mve-textarea]');
@@ -611,13 +586,6 @@ async function _mveToggleTask(state, lineIdx, liEl, boxEl) {
if (liEl) liEl.classList.toggle('is-done', !wasChecked);
if (boxEl) boxEl.checked = !wasChecked;
const res = await _mveWriteSource(state.source, next);
- _mveTrackSaveResult(
- state.source,
- next,
- startedAt,
- res && res.ok ? 'success' : 'failure',
- res && res.ok ? '' : 'write_failed',
- );
if (!res.ok) {
if (liEl) liEl.classList.toggle('is-done', wasChecked);
if (boxEl) boxEl.checked = wasChecked;
diff --git a/src/renderer/modules/memory.js b/src/renderer/modules/memory.js
index 8a9b0474..30f95350 100644
--- a/src/renderer/modules/memory.js
+++ b/src/renderer/modules/memory.js
@@ -52,15 +52,11 @@ function _memLogSafe(level, message, data) {
} catch (_) { /* diagnostics must not alter the operation result */ }
}
-function _memTrackEvent(action, data) {
+function _memLogResult(action, data) {
_memLogSafe('info', 'memory action result', { action, ...(data || {}) });
}
-function _memTrackError(action, data) {
- try { if (window.Monitor) (() => {})(action, data || {}); } catch (_) {}
-}
-
-function _memTrackReadResult(action, startedAt, results) {
+function _memLogReadResult(action, startedAt, results) {
const rows = Array.isArray(results) ? results : [];
const failures = rows.filter((row) => !row || row.ok !== true);
const successCount = rows.length - failures.length;
@@ -82,7 +78,7 @@ function _memTrackReadResult(action, startedAt, results) {
payload.error_code = errorCodes.length === 1 ? errorCodes[0] : 'multiple';
payload.error_type = errorTypes.length === 1 ? errorTypes[0] : 'runtime';
}
- _memTrackEvent('memory_read_result', payload);
+ _memLogResult('memory_read_result', payload);
}
function _memDuration(startedAt) {
@@ -139,12 +135,6 @@ function _memReportIpcFailure(channel, result) {
if (_memIpcFailureCount >= _MEM_IPC_FAILURE_MAX_PER_SESSION) return;
_memIpcFailureState.set(key, now);
_memIpcFailureCount += 1;
- _memTrackError('memory_ipc', {
- channel: safeChannel,
- error_type: details.error_type,
- error_code: details.error_code,
- error_message: details.error_code,
- });
}
async function _memInvoke(channel, payload, options) {
@@ -226,7 +216,7 @@ async function _memLoad() {
_memParseScope(s.key),
{ resultOwned: true },
)));
- _memTrackReadResult('list', startedAt, results);
+ _memLogReadResult('list', startedAt, results);
_memData = {};
_memScopes.forEach((s, i) => {
const r = results[i];
@@ -241,7 +231,7 @@ async function _memReveal(target) {
_memParseScope(target),
{ resultOwned: true },
);
- _memTrackReadResult('reveal', startedAt, [result]);
+ _memLogReadResult('reveal', startedAt, [result]);
return result;
}
@@ -488,7 +478,7 @@ async function _memSaveEditor(target) {
const durationMs = _memDuration(startedAt);
if (!res.ok) {
const details = _memFailureDetails(res);
- _memTrackEvent('memory_entry_save_result', {
+ _memLogResult('memory_entry_save_result', {
result: 'failure',
target: safeTarget,
mode,
@@ -498,7 +488,7 @@ async function _memSaveEditor(target) {
_memToast(_memErrorToText(res.error), 'error');
return;
}
- _memTrackEvent('memory_entry_save_result', {
+ _memLogResult('memory_entry_save_result', {
result: 'success',
target: safeTarget,
mode,
@@ -524,7 +514,7 @@ async function _memDelete(target, text) {
const durationMs = _memDuration(startedAt);
if (!res.ok) {
const details = _memFailureDetails(res);
- _memTrackEvent('memory_entry_delete_result', {
+ _memLogResult('memory_entry_delete_result', {
result: 'failure',
target: safeTarget,
duration_ms: durationMs,
@@ -533,7 +523,7 @@ async function _memDelete(target, text) {
_memToast(_memErrorToText(res.error), 'error');
return;
}
- _memTrackEvent('memory_entry_delete_result', {
+ _memLogResult('memory_entry_delete_result', {
result: 'success',
target: safeTarget,
duration_ms: durationMs,
@@ -797,7 +787,7 @@ async function _memDoMerge() {
}
// Persistence is the terminal boundary. Modal/toast/render failures cannot
// erase or reverse the completed aggregate result.
- _memTrackEvent('memory_import_result', resultPayload);
+ _memLogResult('memory_import_result', resultPayload);
_memCloseModal();
if (added) _memToast(t('memory.merge_done', { n: added }), 'success');
if (failed) _memToast(t('memory.merge_partial', { n: failed }), 'warning');
diff --git a/src/renderer/modules/model-guard.js b/src/renderer/modules/model-guard.js
index c77188a1..4cd9f448 100644
--- a/src/renderer/modules/model-guard.js
+++ b/src/renderer/modules/model-guard.js
@@ -16,7 +16,6 @@ function _modelGuardErrorType(error) {
let _hasConfiguredModel = true; // optimistic — flipped to false after refresh if empty
let _modelGuardRefreshSequence = 0;
-let _modelConfigSnapshotSignature = '';
async function refreshModelGuard() {
const refreshSequence = ++_modelGuardRefreshSequence;
@@ -49,64 +48,12 @@ async function refreshModelConfigSnapshot() {
window.dispatchEvent(new CustomEvent('orkas:model-entries-changed', {
detail: { entries: res.entries },
}));
- trackModelConfigSnapshot(res.entries);
}
} catch (err) {
_guardLog.warn('model config snapshot refresh failed', { error: (err && err.message) || String(err) });
}
}
-function _modelConfigTelemetryEntry(entry, entryRank) {
- const rawProvider = String((entry && entry.provider) || '').trim();
- const rawModel = String((entry && entry.model) || '').trim();
- if (!rawProvider || !rawModel) return null;
- const legacyDynamicProvider = /^cp:/i.test(rawProvider) || rawProvider === 'custom-openai';
- const userEnteredModel = legacyDynamicProvider
- || rawProvider === 'custom'
- || rawProvider === 'openrouter';
- const normalizedProvider = legacyDynamicProvider ? 'custom' : rawProvider;
- return {
- provider: /^[A-Za-z0-9][A-Za-z0-9._:-]{0,79}$/.test(normalizedProvider)
- ? normalizedProvider
- : 'unknown',
- model: userEnteredModel
- ? 'custom'
- : (/^[A-Za-z0-9][A-Za-z0-9._:/+\-]{0,119}$/.test(rawModel) ? rawModel : 'unknown'),
- entry_rank: entryRank,
- };
-}
-
-function trackModelConfigSnapshot(entries) {
- try {
- if (!window.Monitor || typeof Monitor.event !== 'function') return;
- const safeEntries = (Array.isArray(entries) ? entries : [])
- .map((entry, idx) => _modelConfigTelemetryEntry(entry, idx + 1))
- .filter(Boolean);
- const uid = (typeof globalThis.currentUserId === 'string') ? globalThis.currentUserId : '';
- const signature = uid + '|' + safeEntries
- .map((entry) => entry.provider + '/' + entry.model + '#' + entry.entry_rank)
- .join('|');
- if (signature === _modelConfigSnapshotSignature) return;
- _modelConfigSnapshotSignature = signature;
-
- const snapshotId = String(Date.now()) + '-' + Math.random().toString(36).slice(2, 8);
- Monitor.event('model_config_snapshot', {
- snapshot_id: snapshotId,
- entry_count: safeEntries.length,
- });
- safeEntries.forEach((entry) => {
- Monitor.event('model_config_entry', {
- snapshot_id: snapshotId,
- provider: entry.provider,
- model: entry.model,
- entry_rank: entry.entry_rank,
- });
- });
- } catch (err) {
- _guardLog.warn('model config snapshot telemetry failed', { error: (err && err.message) || String(err) });
- }
-}
-
function isModelConfigured() {
return _hasConfiguredModel;
}
diff --git a/src/renderer/modules/oss.js b/src/renderer/modules/oss.js
index ec79f40f..998711c0 100644
--- a/src/renderer/modules/oss.js
+++ b/src/renderer/modules/oss.js
@@ -11,16 +11,6 @@
const _ossLog = createLogger('oss');
-function _ossTrackClick(action, data) {
- void action;
- void data;
-}
-
-function _ossTrackEvent(action, data) {
- void action;
- void data;
-}
-
// category code → centralized ui-icon name (icons.js). We deliberately do NOT
// render the unicode project glyph as an icon (CLAUDE.md: icons go through the
// icon module).
@@ -416,10 +406,6 @@ function _ossPromptForComposer(p, input) {
}
function _openOssMarketplace() {
- _ossTrackClick('commander_oss_quick_task', {
- source_view: 'new_chat',
- destination: 'marketplace_oss',
- });
const load = typeof loadRendererFeature === 'function' ? loadRendererFeature : window.loadRendererFeature;
if (typeof load !== 'function') {
_ossLog.warn('Commander OSS quick task failed: marketplace loader unavailable');
diff --git a/src/renderer/modules/preview-host.js b/src/renderer/modules/preview-host.js
index e710afd5..e12d8e78 100644
--- a/src/renderer/modules/preview-host.js
+++ b/src/renderer/modules/preview-host.js
@@ -46,7 +46,7 @@ const _convLog = createLogger('preview-host');
}
window.OrkasPreviewHost = { close, loadGalleryPage, projectScopedFor: cid => !!cid && cid === currentCid && projectScoped,
setDirty: dirty => window.orkas.invoke('previewWindows.setDirty', { dirty }).catch(() => {}),
- filesChanged: () => window.orkas.invoke('previewWindows.report', { kind: 'files-changed' }).catch(() => {}) };
+ filesChanged: () => window.orkas.invoke('previewWindows.filesChanged', {}).catch(() => {}) };
window.orkas.onPushEvent('preview-windows:close-request', requestClose);
window.orkas.onPushEvent('preview-windows:replace-request', async () => {
if (replacing || closing) return;
diff --git a/src/renderer/modules/preview-monitor.js b/src/renderer/modules/preview-monitor.js
deleted file mode 100644
index f6140077..00000000
--- a/src/renderer/modules/preview-monitor.js
+++ /dev/null
@@ -1,5 +0,0 @@
-// The main renderer owns telemetry identity and broadcast subscriptions.
-// Forward only this window's existing action/result events to that owner.
-window.Monitor = Object.fromEntries(['click', 'event', 'error'].map(method => [method, (action, data) => {
- window.orkas.invoke('previewWindows.report', { kind: 'telemetry', method, action, data: data || {} }).catch(() => {});
-}]));
diff --git a/src/renderer/modules/preview-windows.js b/src/renderer/modules/preview-windows.js
index fe54d666..d21f8d59 100644
--- a/src/renderer/modules/preview-windows.js
+++ b/src/renderer/modules/preview-windows.js
@@ -38,13 +38,10 @@
return open({ kind: 'image', src, title: title || '', options: options({ ...opts, cid }), gallery });
}
window.OrkasPreviewWindows = { open, image, options };
- window.orkas.onPushEvent('preview-windows:report', report => {
- if (report.kind === 'telemetry') window.Monitor?.[report.method]?.(report.action, report.data);
- else if (report.kind === 'files-changed') {
- if (currentView === 'contexts' && typeof loadContexts === 'function') loadContexts();
- if (currentView === 'apps' && typeof loadSavedApps === 'function') loadSavedApps(true);
- if (currentView === 'project' && typeof loadProjectDetail === 'function' && typeof _projectDetailPid !== 'undefined') void loadProjectDetail(_projectDetailPid);
- }
+ window.orkas.onPushEvent('preview-windows:files-changed', () => {
+ if (currentView === 'contexts' && typeof loadContexts === 'function') loadContexts();
+ if (currentView === 'apps' && typeof loadSavedApps === 'function') loadSavedApps(true);
+ if (currentView === 'project' && typeof loadProjectDetail === 'function' && typeof _projectDetailPid !== 'undefined') void loadProjectDetail(_projectDetailPid);
});
window.orkas.onPushEvent('preview-windows:owner-request', async request => {
let result = { ok: false };
diff --git a/src/renderer/modules/project-detail.js b/src/renderer/modules/project-detail.js
index b213b5f5..9c72353d 100644
--- a/src/renderer/modules/project-detail.js
+++ b/src/renderer/modules/project-detail.js
@@ -25,16 +25,6 @@ const PROJECT_LIBRARY_ALLOWED_EXTS = [
'.mp4', '.webm', '.mov', '.m4v', '.ogv',
];
-function _projectTrackClick(action, data) {
- void action;
- void data;
-}
-
-function _projectTrackEvent(action, data) {
- void action;
- void data;
-}
-
function _projectLogFailure(action, data) {
_projectDetailLog.warn('project detail operation failed', { action, ...(data || {}) });
}
@@ -473,7 +463,6 @@ function _bindProjectAutoAddBtn() {
btn.dataset.bound = '1';
btn.addEventListener('click', () => {
if (!_projectDetailPid || typeof openAutoTaskDialog !== 'function') return;
- _projectTrackClick('project_auto_task_open', {});
openAutoTaskDialog({
projectId: _projectDetailPid,
onSaved: () => {
@@ -631,19 +620,13 @@ function _bindProjectInstructions() {
const res = await window.orkas.invoke('projects.instructions.set', { projectId, content });
if (!res?.ok) {
const failure = _projectDetailFailure(res, 'instructions_save_failed');
- _projectTrackEvent('project_instructions_update_result', {
- result: 'failure',
- source: 'detail',
- duration_ms: Math.max(0, Math.round(performance.now() - startedAt)),
- ...failure,
- });
_projectLogFailure('project_instructions_update', { source: 'detail', ...failure });
if (typeof uiAlert === 'function') uiAlert(t('project.instructions.save_failed'));
_updateProjectInstructionsFoot();
return;
}
// The user may switch projects while this save is in flight. The
- // mutation still belongs to the captured project and its telemetry is
+ // mutation still belongs to the captured project and its result is
// valid, but the shared detail input may already render another one.
if (input.dataset.projectId === projectId) input.dataset.savedValue = content;
if (projectId === _projectDetailPid && _projectDetailMeta?.instructions) {
@@ -652,19 +635,8 @@ function _bindProjectInstructions() {
_renderProjectInstructionsRead();
_closeProjectInstructionsEditor({ force: true });
_setProjectInstructionsStatus(t('project.instructions.saved'));
- _projectTrackEvent('project_instructions_update_result', {
- result: 'success',
- source: 'detail',
- duration_ms: Math.max(0, Math.round(performance.now() - startedAt)),
- });
} catch (err) {
const failure = _projectDetailFailure(err, 'instructions_save_exception');
- _projectTrackEvent('project_instructions_update_result', {
- result: 'failure',
- source: 'detail',
- duration_ms: Math.max(0, Math.round(performance.now() - startedAt)),
- ...failure,
- });
_projectLogFailure('project_instructions_update', { source: 'detail', ...failure });
_projectDetailLog.warn('save project instructions failed', err);
if (typeof uiAlert === 'function') uiAlert(t('project.instructions.save_failed'));
@@ -996,16 +968,6 @@ async function _saveProjectMemoryEditor() {
isEdit ? 'memory.replace' : 'memory.add',
isEdit ? { oldText, content } : { content },
);
- _projectTrackEvent('memory_entry_save_result', {
- result: outcome.ok ? 'success' : 'failure',
- target: 'project',
- mode: isEdit ? 'edit' : 'add',
- duration_ms: Math.max(0, Date.now() - startedAt),
- ...(outcome.ok ? {
- chars: content.length,
- char_count: content.length,
- } : outcome.failure),
- });
if (outcome.ok) _closeProjectMemoryEditor();
}
@@ -1071,12 +1033,6 @@ function _bindProjectMemory() {
if (!confirmed) return;
const startedAt = Date.now();
const outcome = await _mutateProjectMemory('memory.remove', { oldText: text });
- _projectTrackEvent('memory_entry_delete_result', {
- result: outcome.ok ? 'success' : 'failure',
- target: 'project',
- duration_ms: Math.max(0, Date.now() - startedAt),
- ...(!outcome.ok ? outcome.failure : {}),
- });
if (outcome.ok && _projectMemoryEditor?.oldText === text) _closeProjectMemoryEditor();
});
}
@@ -1730,12 +1686,6 @@ async function _saveProjectTodoEditor() {
...owner,
...(_todoEditorTid ? { taskId: _todoEditorTid } : {}),
})), pid);
- _projectTrackEvent('project_todo_action_result', {
- result: outcome.ok ? 'success' : 'failure',
- action: taskId ? 'edit' : 'create',
- duration_ms: Math.max(0, Date.now() - startedAt),
- ...(!outcome.ok ? outcome.failure : {}),
- });
if (!outcome.ok) {
_projectLogFailure('project_todo_action', { action: taskId ? 'edit' : 'create', ...outcome.failure });
} else if (generation === _todoEditorGeneration) {
@@ -1771,13 +1721,6 @@ async function _setTodoStatus(tid, status, context = _projectTodoContext()) {
taskId: tid,
status,
}), context.pid);
- _projectTrackEvent('project_todo_toggle_result', {
- result: outcome.ok ? 'success' : 'failure',
- from_status: fromStatus,
- to_status: status,
- duration_ms: Date.now() - startedAt,
- ...(!outcome.ok ? outcome.failure : {}),
- });
if (!outcome.ok) {
_projectLogFailure('project_todo_toggle', {
from_status: fromStatus, to_status: status, ...outcome.failure,
@@ -1812,12 +1755,6 @@ async function _assignTodoAgent(tid, agent, context = _projectTodoContext()) {
owner_agent: agent ? String(agent.name || '') : '',
owner_agent_id: agent ? String(agent.agent_id || '') : '',
}), context.pid);
- _projectTrackEvent('project_todo_assign_result', {
- result: outcome.ok ? 'success' : 'failure',
- action: agent ? 'assign' : 'clear',
- duration_ms: Date.now() - startedAt,
- ...(!outcome.ok ? outcome.failure : {}),
- });
if (!outcome.ok) {
_projectLogFailure('project_todo_assign', {
action: agent ? 'assign' : 'clear', ...outcome.failure,
@@ -1854,10 +1791,6 @@ async function _runTodoTask(tid, context = _projectTodoContext()) {
} finally {
_projectTodoRunning = false;
}
- _projectTrackEvent('project_todo_run_result', {
- result: ok ? 'success' : 'failure',
- duration_ms: Date.now() - startedAt,
- });
if (!ok) {
_projectLogFailure('project_todo_run', { error_type: 'run_failed' });
if (typeof uiAlert === 'function') uiAlert(t('project.todo.run_failed'));
@@ -2090,9 +2023,6 @@ function _bindProjectDriver() {
} finally {
_projectDriverMutating = false;
}
- _projectTrackEvent('project_driver_toggle_result', {
- result: ok ? 'success' : 'failure', enabled: next, duration_ms: Date.now() - startedAt,
- });
if (!ok) _projectLogFailure('project_driver_toggle', { enabled: next, error_type: 'set_failed' });
});
}
@@ -2240,9 +2170,6 @@ async function _removeProjectAgent(agentId) {
if (!_projectDetailPid || !agentId) return;
const projectId = _projectDetailPid;
const startedAt = performance.now();
- // One terminal result at the binding write boundary (analytics contract);
- // the presentation refresh that follows is not part of the outcome.
- _projectTrackClick('project_binding_remove', { binding_kind: 'agent' });
let removed = false;
try {
const res = await window.orkas.invoke('projects.bindings.remove', {
@@ -2252,19 +2179,8 @@ async function _removeProjectAgent(agentId) {
});
if (!res?.ok) throw res || new Error('remove_failed');
removed = true;
- _projectTrackEvent('project_binding_remove_result', {
- binding_kind: 'agent',
- result: 'success',
- duration_ms: Math.round(performance.now() - startedAt),
- });
} catch (err) {
const failure = _projectDetailFailure(err, 'binding_remove_failed');
- _projectTrackEvent('project_binding_remove_result', {
- binding_kind: 'agent',
- result: 'failure',
- duration_ms: Math.round(performance.now() - startedAt),
- ...failure,
- });
_projectLogFailure('project_binding_remove', { binding_kind: 'agent', ...failure });
_projectDetailLog.warn('remove project agent failed', err);
return;
@@ -2882,7 +2798,6 @@ async function _openProjectFile(name, options = {}) {
const row = _findProjectFileRow(name);
const kind = row?.dataset?.projectFileKind || '';
if (options.trackIntent !== false) {
- _projectTrackClick('project_file_open', { file_kind: kind || 'other' });
}
_projectLibraryActiveName = name;
_markProjectLibraryActive();
@@ -3146,7 +3061,6 @@ async function _reprocessProjectFile(name) {
if (!_projectDetailPid || !name) return;
const projectId = _projectDetailPid;
const startedAt = performance.now();
- _projectTrackClick('project_file_reprocess', {});
try {
_projectKbStatusByName[name] = {
...(_projectKbStatusByName[name] || {}),
@@ -3159,17 +3073,8 @@ async function _reprocessProjectFile(name) {
name,
});
if (!res?.ok) throw res || new Error('reprocess_failed');
- _projectTrackEvent('project_file_reprocess_result', {
- result: 'success',
- duration_ms: Math.round(performance.now() - startedAt),
- });
} catch (err) {
const failure = _projectDetailFailure(err, 'reprocess_failed');
- _projectTrackEvent('project_file_reprocess_result', {
- result: 'failure',
- duration_ms: Math.round(performance.now() - startedAt),
- ...failure,
- });
_projectLogFailure('project_file_reprocess', failure);
_projectDetailLog.warn('reprocess project file failed', err);
if (typeof uiAlert === 'function') uiAlert(t('project.files.reprocess_failed'));
@@ -3188,9 +3093,6 @@ async function _deleteProjectFile(name) {
: t('contexts.file.del_confirm', { name: _projectBasename(name) });
if (!(await uiConfirm(prompt))) return;
const startedAt = performance.now();
- _projectTrackClick('project_file_delete', {
- file_kind: kind || 'other',
- });
let res;
try {
res = await window.orkas.invoke('projects.files.delete', {
@@ -3200,23 +3102,11 @@ async function _deleteProjectFile(name) {
if (!res?.ok) throw res || new Error('delete_failed');
} catch (err) {
const failure = _projectDetailFailure(err, 'delete_failed');
- _projectTrackEvent('project_file_delete_result', {
- result: 'failure',
- file_kind: kind || 'other',
- duration_ms: Math.round(performance.now() - startedAt),
- ...failure,
- });
_projectLogFailure('project_file_delete', { file_kind: kind || 'other', ...failure });
_projectDetailLog.warn('delete project file failed', err);
if (typeof uiAlert === 'function') uiAlert(t('project.files.delete_failed'));
return;
}
-
- _projectTrackEvent('project_file_delete_result', {
- result: 'success',
- file_kind: kind || 'other',
- duration_ms: Math.round(performance.now() - startedAt),
- });
try {
if (_projectLibraryActiveName === name || _projectLibraryActiveName.startsWith(`${name}/`)) {
for (const key of Array.from(_projectLibraryDrafts.keys())) {
@@ -3538,9 +3428,6 @@ async function _createProjectTextFile(parentDir = '') {
const stem = t('contexts.new.untitled_stem');
const fullPath = _projectJoinPath(parentDir, `${stem}.md`);
const startedAt = performance.now();
- _projectTrackClick('project_file_create_text', {
- has_target_dir: !!parentDir,
- });
let createdName = fullPath;
try {
const res = await window.orkas.invoke('projects.files.createText', {
@@ -3551,23 +3438,11 @@ async function _createProjectTextFile(parentDir = '') {
createdName = res.info?.relPath || res.info?.name || fullPath;
} catch (err) {
const failure = _projectDetailFailure(err, 'create_text_failed');
- _projectTrackEvent('project_file_create_text_result', {
- result: 'failure',
- has_target_dir: !!parentDir,
- duration_ms: Math.round(performance.now() - startedAt),
- ...failure,
- });
_projectLogFailure('project_file_create_text', { has_target_dir: !!parentDir, ...failure });
_projectDetailLog.warn('create project text failed', err);
if (typeof uiAlert === 'function') uiAlert(t('contexts.file.create_failed'));
return;
}
-
- _projectTrackEvent('project_file_create_text_result', {
- result: 'success',
- has_target_dir: !!parentDir,
- duration_ms: Math.round(performance.now() - startedAt),
- });
try {
if (parentDir) _projectLibraryExpanded.add(parentDir);
_projectLibraryActiveName = createdName;
@@ -3590,9 +3465,6 @@ async function _createProjectDir(parentDir = '') {
}
const rel = _projectJoinPath(parentDir, nameRaw);
const startedAt = performance.now();
- _projectTrackClick('project_folder_create', {
- has_target_dir: !!parentDir,
- });
let createdPath = rel;
try {
const res = await window.orkas.invoke('projects.files.mkdir', {
@@ -3603,23 +3475,11 @@ async function _createProjectDir(parentDir = '') {
createdPath = res.path || rel;
} catch (err) {
const failure = _projectDetailFailure(err, 'create_folder_failed');
- _projectTrackEvent('project_folder_create_result', {
- result: 'failure',
- has_target_dir: !!parentDir,
- duration_ms: Math.round(performance.now() - startedAt),
- ...failure,
- });
_projectLogFailure('project_folder_create', { has_target_dir: !!parentDir, ...failure });
_projectDetailLog.warn('create project folder failed', err);
if (typeof uiAlert === 'function') uiAlert(t('contexts.dir.create_failed'));
return;
}
-
- _projectTrackEvent('project_folder_create_result', {
- result: 'success',
- has_target_dir: !!parentDir,
- duration_ms: Math.round(performance.now() - startedAt),
- });
try {
if (parentDir) _projectLibraryExpanded.add(parentDir);
_projectLibraryExpanded.add(createdPath);
@@ -3688,13 +3548,6 @@ async function _handleProjectLibraryMove(srcName, targetDir) {
const next = _projectJoinPath(targetDir, base);
if (next === srcName) return;
if (targetDir === srcName || targetDir.startsWith(`${srcName}/`)) {
- _projectTrackEvent('project_file_move_result', {
- result: 'blocked',
- entry_type: 'dir',
- has_target_dir: !!targetDir,
- error_code: 'invalid_target',
- error_type: 'validation',
- });
if (typeof uiAlert === 'function') await uiAlert(t('contexts.dnd.invalid_self'));
return;
}
@@ -3712,13 +3565,6 @@ async function _handleProjectLibraryMove(srcName, targetDir) {
actual = res.name || next;
} catch (err) {
const failure = _projectDetailFailure(err, 'move_failed');
- _projectTrackEvent('project_file_move_result', {
- result: 'failure',
- entry_type: entryType,
- has_target_dir: !!targetDir,
- duration_ms: Math.round(performance.now() - startedAt),
- ...failure,
- });
_projectLogFailure('project_file_move', {
entry_type: entryType,
has_target_dir: !!targetDir,
@@ -3733,13 +3579,6 @@ async function _handleProjectLibraryMove(srcName, targetDir) {
}
return;
}
-
- _projectTrackEvent('project_file_move_result', {
- result: 'success',
- entry_type: entryType,
- has_target_dir: !!targetDir,
- duration_ms: Math.round(performance.now() - startedAt),
- });
try {
_applyProjectLibraryPathChange(srcName, actual, targetDir);
if (projectId === _projectDetailPid) await loadProjectDetail(projectId);
@@ -3768,9 +3607,6 @@ async function _renameProjectFile(name) {
const kind = row?.dataset?.projectFileKind || '';
const startedAt = performance.now();
let failureKey = 'contexts.entry.rename_failed';
- _projectTrackClick('project_file_rename', {
- file_kind: kind || 'other',
- });
let actual = next;
try {
const res = await window.orkas.invoke('projects.files.rename', {
@@ -3785,23 +3621,11 @@ async function _renameProjectFile(name) {
actual = res.name || next;
} catch (err) {
const failure = _projectDetailFailure(err, 'rename_file_failed');
- _projectTrackEvent('project_file_rename_result', {
- result: 'failure',
- file_kind: kind || 'other',
- duration_ms: Math.round(performance.now() - startedAt),
- ...failure,
- });
_projectLogFailure('project_file_rename', { file_kind: kind || 'other', ...failure });
_projectDetailLog.warn('rename project file failed', err);
if (typeof uiAlert === 'function') uiAlert(t(failureKey));
return;
}
-
- _projectTrackEvent('project_file_rename_result', {
- result: 'success',
- file_kind: kind || 'other',
- duration_ms: Math.round(performance.now() - startedAt),
- });
try {
_applyProjectLibraryPathChange(name, actual, parentDir);
if (projectId === _projectDetailPid) await loadProjectDetail(projectId);
@@ -3923,7 +3747,6 @@ async function _uploadProjectFiles(fileList, targetDir = '', source = 'drop') {
if (targetDir) _projectLibraryExpanded.add(targetDir);
const payload = _projectFileUploadPayload(files, source, targetDir);
const startedAt = performance.now();
- _projectTrackClick('project_file_upload', payload);
_setProjectFilesStatus(t('project.files.uploading'));
const hiddenRejected = files
.filter((file) => _projectUploadHasHiddenPath(file))
@@ -3978,15 +3801,6 @@ async function _uploadProjectFiles(fileList, targetDir = '', source = 'drop') {
error_type: rejectedCount && !failed.length ? 'validation' : 'operation',
}
: {};
- _projectTrackEvent('project_file_upload_result', {
- ...payload,
- result: unsuccessfulCount ? (unsuccessfulCount < files.length ? 'partial_failure' : 'failure') : 'success',
- uploaded_count: Math.max(0, uploadable.length - failed.length),
- failed_count: unsuccessfulCount,
- rejected_count: rejectedCount,
- duration_ms: Math.round(performance.now() - startedAt),
- ...uploadFailure,
- });
if (unsuccessfulCount) {
_projectLogFailure('project_file_upload', {
source,
@@ -4022,7 +3836,6 @@ async function _uploadProjectFilesNative(targetDir = '') {
if (targetDir) _projectLibraryExpanded.add(targetDir);
const payload = { source: 'picker', has_target_dir: !!targetDir };
const startedAt = performance.now();
- _projectTrackClick('project_file_upload', payload);
_setProjectFilesStatus(t('project.files.uploading'));
let data;
try {
@@ -4033,14 +3846,6 @@ async function _uploadProjectFilesNative(targetDir = '') {
} catch (err) {
_setProjectFilesStatus('');
const failure = _projectDetailFailure(err, 'picker_failed');
- _projectTrackEvent('project_file_upload_result', {
- ...payload,
- result: 'failure',
- uploaded_count: 0,
- failed_count: 1,
- duration_ms: Math.round(performance.now() - startedAt),
- ...failure,
- });
_projectLogFailure('project_file_upload', { source: 'picker', ...failure });
if (typeof uiAlert === 'function') {
await uiAlert(t('contexts.upload_picker_failed'));
@@ -4050,42 +3855,16 @@ async function _uploadProjectFilesNative(targetDir = '') {
_setProjectFilesStatus('');
if (!data?.ok) {
const failure = _projectDetailFailure(data, 'picker_failed');
- _projectTrackEvent('project_file_upload_result', {
- ...payload,
- result: 'failure',
- uploaded_count: 0,
- failed_count: 1,
- duration_ms: Math.round(performance.now() - startedAt),
- ...failure,
- });
_projectLogFailure('project_file_upload', { source: 'picker', ...failure });
if (typeof uiAlert === 'function') await uiAlert(t('contexts.upload_picker_failed'));
return;
}
if (data.cancelled) {
- _projectTrackEvent('project_file_upload_result', {
- ...payload,
- result: 'cancelled',
- uploaded_count: 0,
- failed_count: 0,
- file_count: 0,
- duration_ms: Math.round(performance.now() - startedAt),
- error_code: 'picker_cancelled',
- });
return;
}
const rows = Array.isArray(data && data.files) ? data.files : [];
const failed = rows.filter((r) => !r || r.ok === false);
const pickerFailure = failed.length ? { error_code: 'upload_failed', error_type: 'operation' } : {};
- _projectTrackEvent('project_file_upload_result', {
- ...payload,
- result: failed.length ? (failed.length < rows.length ? 'partial_failure' : 'failure') : 'success',
- uploaded_count: Math.max(0, rows.length - failed.length),
- failed_count: failed.length,
- file_count: rows.length,
- duration_ms: Math.round(performance.now() - startedAt),
- ...pickerFailure,
- });
if (failed.length) {
_projectLogFailure('project_file_upload', {
source: 'picker',
@@ -4131,39 +3910,7 @@ async function _submitProjectChat() {
? _chatAttachList(draftCid)
: [];
let intendedAttachmentCount = draftItems.filter((item) => item && item.status !== 'error').length;
- const modelTelemetry = typeof _chatModelTelemetryContext === 'function'
- ? _chatModelTelemetryContext()
- : {};
- const sendAttemptStartedAt = performance.now();
- const commonSendPayload = {
- source_view: 'project',
- content_length: requestText.length,
- recipient_type: recipientType,
- has_skill: pendingUseSelections.some((sel) => sel.kind === 'skill'),
- has_connector: pendingUseSelections.some((sel) => sel.kind === 'connector'),
- attachment_count: intendedAttachmentCount,
- ...modelTelemetry,
- };
- _projectTrackClick('project_chat_send', {
- ...commonSendPayload,
- });
- _projectTrackClick('chat_send', commonSendPayload);
if (typeof ensureModelConfigured === 'function' && !ensureModelConfigured()) {
- const resultPayload = {
- result: 'failure',
- source_view: 'project',
- content_length: requestText.length,
- attachment_count: intendedAttachmentCount,
- duration_ms: Math.max(0, Math.round(performance.now() - sendAttemptStartedAt)),
- failure_stage: 'preflight',
- failure_reason: 'model_not_configured',
- ...modelTelemetry,
- };
- if (typeof _trackChatSendResult === 'function') {
- _trackChatSendResult('failure', resultPayload);
- } else {
- _projectTrackEvent('chat_send_result', resultPayload);
- }
return;
}
const releaseAttachmentSend = typeof _chatAttachTryBeginSend === 'function'
@@ -4172,21 +3919,6 @@ async function _submitProjectChat() {
? null
: (() => {}));
if (!releaseAttachmentSend) {
- const resultPayload = {
- result: 'failure',
- source_view: 'project',
- content_length: requestText.length,
- attachment_count: intendedAttachmentCount,
- duration_ms: Math.max(0, Math.round(performance.now() - sendAttemptStartedAt)),
- failure_stage: 'preflight',
- failure_reason: 'attachment_uploading',
- ...modelTelemetry,
- };
- if (typeof _trackChatSendResult === 'function') {
- _trackChatSendResult('failure', resultPayload);
- } else {
- _projectTrackEvent('chat_send_result', resultPayload);
- }
if (typeof uiAlert === 'function') await uiAlert(t('chat.attach_still_uploading'));
return;
}
@@ -4195,21 +3927,6 @@ async function _submitProjectChat() {
: { ok: true, items: draftItems };
if (!attachmentSnapshot.ok) {
releaseAttachmentSend();
- const resultPayload = {
- result: 'failure',
- source_view: 'project',
- content_length: requestText.length,
- attachment_count: intendedAttachmentCount,
- duration_ms: Math.max(0, Math.round(performance.now() - sendAttemptStartedAt)),
- failure_stage: 'preflight',
- failure_reason: 'attachment_adopt_failed',
- ...modelTelemetry,
- };
- if (typeof _trackChatSendResult === 'function') {
- _trackChatSendResult('failure', resultPayload);
- } else {
- _projectTrackEvent('chat_send_result', resultPayload);
- }
if (typeof uiAlert === 'function') await uiAlert(t('chat.attach_sync_failed'));
return;
}
@@ -4256,21 +3973,6 @@ async function _submitProjectChat() {
}
createdConversation = conv;
} catch (err) {
- const resultPayload = {
- result: 'failure',
- source_view: 'project',
- content_length: requestText.length,
- attachment_count: intendedAttachmentCount,
- duration_ms: Math.max(0, Math.round(performance.now() - sendAttemptStartedAt)),
- failure_stage: 'conversation_create',
- failure_reason: 'conversation_create_failed',
- ...modelTelemetry,
- };
- if (typeof _trackChatSendResult === 'function') {
- _trackChatSendResult('failure', resultPayload);
- } else {
- _projectTrackEvent('chat_send_result', resultPayload);
- }
if (typeof uiAlert === 'function') {
await uiAlert(t('chat.create_conv_failed_with_reason', { reason: err?.message || err }));
}
@@ -4327,21 +4029,6 @@ async function _submitProjectChat() {
error_code: 'discard_empty_failed',
});
}
- const resultPayload = {
- result: 'failure',
- source_view: 'project',
- content_length: requestText.length,
- attachment_count: intendedAttachmentCount,
- duration_ms: Math.max(0, Math.round(performance.now() - sendAttemptStartedAt)),
- failure_stage: 'preflight',
- failure_reason: 'attachment_adopt_failed',
- ...modelTelemetry,
- };
- if (typeof _trackChatSendResult === 'function') {
- _trackChatSendResult('failure', resultPayload);
- } else {
- _projectTrackEvent('chat_send_result', resultPayload);
- }
if (typeof uiAlert === 'function') {
await uiAlert(t('chat.attach_adopt_failed', { reason: adoptionError }));
}
@@ -4438,11 +4125,6 @@ function _projectBindingSourceHtml(source) {
async function _openAddPicker() {
// Dispose any previously-open picker so re-clicks don't stack.
document.getElementById('project-binding-picker-overlay')?.remove();
- // `binding_kind` stays on the wire as a constant so the existing PMS
- // Project funnel keeps reading these rows across the removal.
- _projectTrackClick('project_binding_picker_open', {
- binding_kind: 'agent',
- });
let candidates;
try {
@@ -4536,19 +4218,11 @@ async function _openAddPicker() {
const k = row.dataset.kind;
const projectId = _projectDetailPid;
const startedAt = performance.now();
- _projectTrackClick('project_binding_add', {
- binding_kind: k,
- });
try {
const res = await window.orkas.invoke('projects.bindings.add', {
projectId, kind: k, id,
});
if (!res?.ok) throw res || new Error('add_failed');
- _projectTrackEvent('project_binding_add_result', {
- binding_kind: k,
- result: 'success',
- duration_ms: Math.round(performance.now() - startedAt),
- });
// Drop the picked id from the local candidate set so it
// disappears from subsequent renders without a server round-trip.
candidates = candidates.filter((c) => {
@@ -4563,12 +4237,6 @@ async function _openAddPicker() {
}
} catch (err) {
const failure = _projectDetailFailure(err, 'binding_add_failed');
- _projectTrackEvent('project_binding_add_result', {
- binding_kind: k,
- result: 'failure',
- duration_ms: Math.round(performance.now() - startedAt),
- ...failure,
- });
_projectLogFailure('project_binding_add', { binding_kind: k, ...failure });
_projectDetailLog.warn('add binding failed', err);
}
@@ -4626,9 +4294,6 @@ async function _commitRename(newName) {
let failure = null;
const startedAt = performance.now();
_projectRenameCommitInFlight = true;
- _projectTrackClick('project_rename_submit', {
- source: 'detail',
- });
try {
const res = await window.orkas.invoke('projects.rename', {
projectId: _projectDetailPid, name: trimmed,
@@ -4637,11 +4302,6 @@ async function _commitRename(newName) {
code = (res && res.error) || 'generic';
failure = _projectDetailFailure(res, 'rename_failed');
} else {
- _projectTrackEvent('project_rename_result', {
- result: 'success',
- source: 'detail',
- duration_ms: Math.round(performance.now() - startedAt),
- });
_projectDetailMeta.project = res.project;
if (typeof loadProjects === 'function') loadProjects(true);
_exitRenameMode();
@@ -4653,12 +4313,6 @@ async function _commitRename(newName) {
code = (err && err.message) || 'generic';
failure = _projectDetailFailure(err, 'rename_exception');
}
- _projectTrackEvent('project_rename_result', {
- result: 'failure',
- source: 'detail',
- duration_ms: Math.round(performance.now() - startedAt),
- ...(failure || _projectDetailFailure(null, 'rename_failed')),
- });
_projectLogFailure('project_rename', {
source: 'detail',
...(failure || _projectDetailFailure(null, 'rename_failed')),
diff --git a/src/renderer/modules/projects.js b/src/renderer/modules/projects.js
index ae1c2718..81b94fbd 100644
--- a/src/renderer/modules/projects.js
+++ b/src/renderer/modules/projects.js
@@ -15,14 +15,6 @@
const _projectsLog = createLogger('projects');
-function _projectsTrackClick(action, data) {
- try { if (window.Monitor) (() => {})(action, data || {}); } catch (_) {}
-}
-
-function _projectsTrackEvent(action, data) {
- try { if (window.Monitor) (() => {})(action, data || {}); } catch (_) {}
-}
-
function _projectsLogFailure(action, data) {
_projectsLog.warn('project operation failed', { action, ...(data || {}) });
}
@@ -416,7 +408,6 @@ function _bindProjectsHandlers(container) {
return;
}
if (!_isProjectSelected(pid)) {
- _projectsTrackClick('project_open', {});
if (typeof setView === 'function') setView('project', pid);
renderProjectsSection();
return;
@@ -472,7 +463,6 @@ window.addEventListener('sidebar-section-toggle', (event) => {
function _startProjectInlineCreate() {
if (_projectsInlineCreate) return;
if (_projectsInlineRenameSubmitting) return;
- _projectsTrackClick('project_create_open', {});
_projectsInlineRenamePid = null;
_projectsInlineRenameOriginal = '';
_projectsInlineRenameDraft = '';
@@ -518,17 +508,11 @@ function _bindInlineCreateInput(input) {
_projectsInlineCreateError = '';
const requestId = ++_projectsInlineCreateRequestId;
const startedAt = performance.now();
- _projectsTrackClick('project_create_submit', {});
try {
const res = await window.orkas.invoke('projects.create', { name });
if (requestId !== _projectsInlineCreateRequestId || !_projectsInlineCreate) return;
if (!res || !res.ok) {
const failure = _projectsFailureDetail(res, 'create_failed');
- _projectsTrackEvent('project_create_result', {
- result: 'failure',
- duration_ms: Math.round(performance.now() - startedAt),
- ...failure,
- });
_projectsLogFailure('project_create', failure);
_projectsInlineCreateSubmitting = false;
_showProjectInlineCreateError(res && res.error);
@@ -538,10 +522,6 @@ function _bindInlineCreateInput(input) {
// successful create lands on the project detail instead of leaving the
// user on the previous page with only an empty sidebar row.
const pid = res.project && res.project.project_id;
- _projectsTrackEvent('project_create_result', {
- result: 'success',
- duration_ms: Math.round(performance.now() - startedAt),
- });
if (pid) {
_projectsExpanded[pid] = true;
_saveProjectsExpanded();
@@ -557,11 +537,6 @@ function _bindInlineCreateInput(input) {
} catch (err) {
if (requestId !== _projectsInlineCreateRequestId || !_projectsInlineCreate) return;
const failure = _projectsFailureDetail(err, 'create_exception');
- _projectsTrackEvent('project_create_result', {
- result: 'failure',
- duration_ms: Math.round(performance.now() - startedAt),
- ...failure,
- });
_projectsLogFailure('project_create', failure);
_projectsInlineCreateSubmitting = false;
_showProjectInlineCreateError(err && err.message);
@@ -645,9 +620,6 @@ function _bindInlineRenameInput(input) {
_projectsInlineRenameError = '';
const requestId = ++_projectsInlineRenameRequestId;
const startedAt = performance.now();
- _projectsTrackClick('project_rename_submit', {
- source: 'sidebar',
- });
try {
const res = await window.orkas.invoke('projects.rename', { projectId: pid, name: next });
if (
@@ -656,22 +628,11 @@ function _bindInlineRenameInput(input) {
) return;
if (!res || !res.ok) {
const failure = _projectsFailureDetail(res, 'rename_failed');
- _projectsTrackEvent('project_rename_result', {
- result: 'failure',
- source: 'sidebar',
- duration_ms: Math.round(performance.now() - startedAt),
- ...failure,
- });
_projectsLogFailure('project_rename', { source: 'sidebar', ...failure });
_projectsInlineRenameSubmitting = false;
_showProjectInlineRenameError(res && res.error);
return;
}
- _projectsTrackEvent('project_rename_result', {
- result: 'success',
- source: 'sidebar',
- duration_ms: Math.round(performance.now() - startedAt),
- });
_projectsInlineRenamePid = null;
_projectsInlineRenameOriginal = '';
_projectsInlineRenameDraft = '';
@@ -684,12 +645,6 @@ function _bindInlineRenameInput(input) {
|| _projectsInlineRenamePid !== pid
) return;
const failure = _projectsFailureDetail(err, 'rename_exception');
- _projectsTrackEvent('project_rename_result', {
- result: 'failure',
- source: 'sidebar',
- duration_ms: Math.round(performance.now() - startedAt),
- ...failure,
- });
_projectsLogFailure('project_rename', { source: 'sidebar', ...failure });
_projectsInlineRenameSubmitting = false;
_showProjectInlineRenameError(err && err.message);
@@ -906,20 +861,11 @@ async function _confirmDeleteProject(pid, source = 'sidebar') {
if (!ok) return;
const startedAt = performance.now();
- _projectsTrackClick('project_delete', {
- source,
- });
let deleted = false;
try {
const res = await window.orkas.invoke('projects.delete', { projectId: pid });
if (!res || !res.ok) {
const failure = _projectsFailureDetail(res, 'delete_failed');
- _projectsTrackEvent('project_delete_result', {
- result: 'failure',
- source,
- duration_ms: Math.round(performance.now() - startedAt),
- ...failure,
- });
_projectsLogFailure('project_delete', { source, ...failure });
const code = res && res.error;
if (code === 'has_running_conv') {
@@ -931,20 +877,9 @@ async function _confirmDeleteProject(pid, source = 'sidebar') {
}
return;
}
- _projectsTrackEvent('project_delete_result', {
- result: 'success',
- source,
- duration_ms: Math.round(performance.now() - startedAt),
- });
deleted = true;
} catch (err) {
const failure = _projectsFailureDetail(err, 'delete_exception');
- _projectsTrackEvent('project_delete_result', {
- result: 'failure',
- source,
- duration_ms: Math.round(performance.now() - startedAt),
- ...failure,
- });
_projectsLogFailure('project_delete', { source, ...failure });
_projectsLog.error('delete project failed', err);
await uiAlert(t('project.delete_failed_generic'));
diff --git a/src/renderer/modules/saved-apps.js b/src/renderer/modules/saved-apps.js
index ffa8ee13..916253a0 100644
--- a/src/renderer/modules/saved-apps.js
+++ b/src/renderer/modules/saved-apps.js
@@ -36,9 +36,6 @@
} catch (_) {}
}
- function _track(action, data) { void action; void data; }
- function _trackError(action, data) { void action; void data; }
-
const _SAVED_APP_STABLE_ERROR_CODES = new Set([
'invalid_response',
'invalid_title',
@@ -81,7 +78,7 @@
_appsLog.warn('saved app operation failed', { action, ...(data || {}) });
}
- function _trackManageResult(startedAt, action, result, failure = {}) {
+ function _logManageResult(startedAt, action, result, failure = {}) {
const payload = {
result,
action,
@@ -97,7 +94,7 @@
}
}
- function _trackOpenResult(startedAt, result, failure = {}) {
+ function _logOpenResult(startedAt, result, failure = {}) {
const payload = {
result,
duration_ms: Math.max(0, Date.now() - startedAt),
@@ -278,20 +275,20 @@
if (window.OrkasPreviewWindows) {
const app = (_appsCache || []).find(item => item.id === appId);
const result = await window.OrkasPreviewWindows.open({ kind: 'app', appId, title: app?.title || _t('artifact.title', 'Interactive app') });
- _trackOpenResult(startedAt, result?.ok ? 'success' : 'failure', result?.ok ? {} : { error_type: 'presentation', error_code: 'saved_app_viewer_failed' });
+ _logOpenResult(startedAt, result?.ok ? 'success' : 'failure', result?.ok ? {} : { error_type: 'presentation', error_code: 'saved_app_viewer_failed' });
return;
}
let r;
try {
r = await window.orkas.invoke('savedApps.openInApp', { appId: String(appId) });
} catch (err) {
- _trackOpenResult(startedAt, 'failure', _savedAppFailure(err, 'saved_app_open_failed', 'ipc'));
+ _logOpenResult(startedAt, 'failure', _savedAppFailure(err, 'saved_app_open_failed', 'ipc'));
_fail(_t('apps.open_failed', 'Could not open the app'), err);
return;
}
if (!r || r.ok === false || !r.url) {
const failure = _savedAppFailure(r, r && r.ok === false ? 'saved_app_open_failed' : 'invalid_response');
- _trackOpenResult(startedAt, 'failure', failure);
+ _logOpenResult(startedAt, 'failure', failure);
_fail(_t('apps.open_failed', 'Could not open the app'), { message: (r && r.error) || 'open failed' });
return;
}
@@ -299,11 +296,10 @@
const app = (_appsCache || []).find((a) => a && a.id === appId);
_openAppViewer(r, (app && app.title) || _t('artifact.title', 'Interactive app'));
} catch (err) {
- _trackError('saved_app_open', { error_message: 'saved_app_open_failed' });
_fail(_t('apps.open_failed', 'Could not open the app'), err);
return;
}
- _trackOpenResult(startedAt, 'success');
+ _logOpenResult(startedAt, 'success');
}
// "Edit" — backend creates a fresh conversation with the app's source bundled
@@ -318,22 +314,22 @@
try {
r = await window.orkas.invoke('savedApps.openForEditing', { appId: String(appId) });
} catch (err) {
- _trackManageResult(startedAt, 'edit', 'failure', _savedAppFailure(err, 'saved_app_edit_failed', 'ipc'));
+ _logManageResult(startedAt, 'edit', 'failure', _savedAppFailure(err, 'saved_app_edit_failed', 'ipc'));
_fail(_t('apps.edit_failed', 'Could not open an edit conversation'), err);
return;
}
if (!r || r.ok === false) {
- _trackManageResult(startedAt, 'edit', 'failure', _savedAppFailure(r, 'saved_app_edit_failed'));
+ _logManageResult(startedAt, 'edit', 'failure', _savedAppFailure(r, 'saved_app_edit_failed'));
_fail(_t('apps.edit_failed', 'Could not open an edit conversation'), { message: (r && r.error) || 'open-for-editing failed' });
return;
}
const conv = r.conversation;
if (!conv || !conv.conversation_id) {
- _trackManageResult(startedAt, 'edit', 'failure', _savedAppFailure(r, 'invalid_response'));
+ _logManageResult(startedAt, 'edit', 'failure', _savedAppFailure(r, 'invalid_response'));
_fail(_t('apps.edit_failed', 'Could not open an edit conversation'));
return;
}
- _trackManageResult(startedAt, 'edit', 'success');
+ _logManageResult(startedAt, 'edit', 'success');
// Add to the sidebar list. Set last_active_at explicitly — backend
// create response doesn't include the derived field, so timeBucket
// would otherwise put this brand-new row in the 'older' bucket.
@@ -384,16 +380,16 @@
try {
r = await window.orkas.invoke('savedApps.rename', { appId: String(appId), title: next });
} catch (err) {
- _trackManageResult(startedAt, 'rename', 'failure', _savedAppFailure(err, 'saved_app_rename_failed', 'ipc'));
+ _logManageResult(startedAt, 'rename', 'failure', _savedAppFailure(err, 'saved_app_rename_failed', 'ipc'));
_fail(_t('apps.rename_failed', 'Could not rename'), err);
return;
}
if (!r || r.ok === false) {
- _trackManageResult(startedAt, 'rename', 'failure', _savedAppFailure(r, 'saved_app_rename_failed'));
+ _logManageResult(startedAt, 'rename', 'failure', _savedAppFailure(r, 'saved_app_rename_failed'));
_fail(_t('apps.rename_failed', 'Could not rename'), { message: (r && r.error) || 'rename failed' });
return;
}
- _trackManageResult(startedAt, 'rename', 'success');
+ _logManageResult(startedAt, 'rename', 'success');
try { loadSavedApps(true); } catch (_) {
_appsLogFailure('saved_app_refresh', { error_type: 'presentation', error_code: 'saved_app_viewer_failed' });
}
@@ -419,16 +415,16 @@
try {
r = await window.orkas.invoke('savedApps.delete', { appId: String(appId) });
} catch (err) {
- _trackManageResult(startedAt, 'delete', 'failure', _savedAppFailure(err, 'saved_app_delete_failed', 'ipc'));
+ _logManageResult(startedAt, 'delete', 'failure', _savedAppFailure(err, 'saved_app_delete_failed', 'ipc'));
_fail(_t('apps.delete_failed', 'Could not delete'), err);
return;
}
if (!r || r.ok === false) {
- _trackManageResult(startedAt, 'delete', 'failure', _savedAppFailure(r, 'saved_app_delete_failed'));
+ _logManageResult(startedAt, 'delete', 'failure', _savedAppFailure(r, 'saved_app_delete_failed'));
_fail(_t('apps.delete_failed', 'Could not delete'), { message: (r && r.error) || 'delete failed' });
return;
}
- _trackManageResult(startedAt, 'delete', 'success');
+ _logManageResult(startedAt, 'delete', 'success');
try { loadSavedApps(true); } catch (_) {
_appsLogFailure('saved_app_refresh', { error_type: 'presentation', error_code: 'saved_app_viewer_failed' });
}
@@ -487,9 +483,8 @@
return _appTemplates.some(item => item.id === value) ? value : 'custom';
}
- function _trackCreateAction(action, template = 'custom') {
+ function _logCreateAction(action, template = 'custom') {
const payload = { action, template: _createTemplateId(template) };
- try { window.Monitor?.click('saved_app_create', payload); } catch (_) {}
_appsLog.info?.('app creation action', payload);
}
@@ -505,7 +500,6 @@
duration_ms: Math.max(0, Date.now() - startedAt) };
if (result === 'failure') payload.error_code = stage === 'preflight'
? 'model_not_configured' : stage === 'conversation_create' ? 'conversation_create_failed' : 'send_not_started';
- try { window.Monitor?.event('saved_app_create_result', payload); } catch (_) {}
if (result === 'failure') _appsLog.warn('app creation did not start', payload);
else _appsLog.info?.('app creation started', payload);
};
@@ -604,26 +598,26 @@
if (_uiTrapDialogTab(overlay, event)) return;
if (event.key === 'Escape') {
event.preventDefault(); event.stopPropagation();
- if (!submitting) { _trackCreateAction('cancel', selectedTemplate); close(); }
+ if (!submitting) { _logCreateAction('cancel', selectedTemplate); close(); }
}
};
document.addEventListener('keydown', onKey, true);
overlay.addEventListener('click', async (event) => {
if (submitting) return;
if (event.target === overlay || event.target.closest('[data-create-cancel]')) {
- _trackCreateAction('cancel', selectedTemplate); close(); return;
+ _logCreateAction('cancel', selectedTemplate); close(); return;
}
const template = event.target.closest('[data-app-template]');
if (template) {
selectedTemplate = _createTemplateId(template.dataset.appTemplate);
- _trackCreateAction('template', selectedTemplate);
+ _logCreateAction('template', selectedTemplate);
idea.value = _t(`apps.template_${template.dataset.appTemplate}_prompt`, '');
updateSubmit();
idea.focus();
return;
}
if (!event.target.closest('[data-create-submit]') || !idea.value.trim()) return;
- _trackCreateAction('submit', selectedTemplate);
+ _logCreateAction('submit', selectedTemplate);
submitting = true;
updateSubmit();
cancelButton.disabled = true;
@@ -733,7 +727,7 @@
const createButton = document.getElementById('apps-create-btn');
if (createButton) createButton.onclick = () => {
if (_createPanel) return;
- _trackCreateAction('open');
+ _logCreateAction('open');
_openCreatePanel();
};
// `_force` accepted for parity with loadAgents/loadSkills; this module
diff --git a/src/renderer/modules/search.js b/src/renderer/modules/search.js
index 627a2883..6c36c153 100644
--- a/src/renderer/modules/search.js
+++ b/src/renderer/modules/search.js
@@ -75,13 +75,6 @@ function _reportGlobalSearchFailure(stage, error, fallbackCode) {
return { stage: safeStage, error_code: errorCode };
}
-// Search-result telemetry is commercial-only. Keep a stable local hook so
-// shared control flow can report outcomes without coupling OSS search to the
-// private Monitor runtime.
-function _trackGlobalSearchResult() {
- // Intentionally empty in the open build.
-}
-
function _bindGlobalSearch() {
document.getElementById('sidebar-search-btn')?.addEventListener('click', () => openGlobalSearch('sidebar'));
// Library page-header search button reuses the same Cmd+K overlay
@@ -267,19 +260,11 @@ async function _runSearchNow(queryArg) {
});
const data = await res.json();
if (seq !== _searchSeq) {
- _trackGlobalSearchResult('cancelled', 'superseded', startedAt, {
- has_project: !!projectId,
- });
return; // a newer query arrived; drop this
}
_searchLoading = false;
if (!data.ok) {
const failure = _reportGlobalSearchFailure('response', data, 'search_rejected');
- _trackGlobalSearchResult('failure', failure.stage, startedAt, {
- has_project: !!projectId,
- error_type: 'http',
- error_code: failure.error_code,
- });
_renderSearchError(data.error);
return;
}
@@ -294,33 +279,12 @@ async function _runSearchNow(queryArg) {
_searchLastQuery = query;
_setSearchTabsVisible(true);
_renderSearchResults(query);
- _trackGlobalSearchResult(
- degradation ? 'partial_failure' : 'success',
- degradation ? 'partial' : 'complete',
- startedAt,
- {
- item_count: _searchResults.length,
- has_project: !!projectId,
- ...(degradation ? {
- error_type: 'runtime',
- error_code: degradation.error_code,
- } : {}),
- },
- );
} catch (e) {
if (seq !== _searchSeq) {
- _trackGlobalSearchResult('cancelled', 'superseded', startedAt, {
- has_project: !!projectId,
- });
return;
}
_searchLoading = false;
const failure = _reportGlobalSearchFailure('request', e, 'search_request_failed');
- _trackGlobalSearchResult('failure', failure.stage, startedAt, {
- has_project: !!projectId,
- error_type: 'network',
- error_code: failure.error_code,
- });
_renderSearchError(e.message || String(e));
} finally {
pending.active = false;
diff --git a/src/renderer/modules/settings.js b/src/renderer/modules/settings.js
index aaac9f88..7a3da6a9 100644
--- a/src/renderer/modules/settings.js
+++ b/src/renderer/modules/settings.js
@@ -58,26 +58,14 @@ let _settingsState = {
taskNotificationsBound: false,
taskNotificationsToggleEpoch: 0,
taskNotificationPermissionRefreshTimer: null,
- taskNotificationPermissionTelemetryKey: '',
+ taskNotificationPermissionLogKey: '',
clientConfigBound: false,
recycleBound: false,
orkasApiCredential: null,
orkasApiEditing: false,
};
-function _settingsTrackClick() {}
-
-function _settingsTrackEvent(action, payload) {
- void action;
- void payload;
-}
-
-function _settingsTrackError(action, payload) {
- void action;
- void payload;
-}
-
-function _settingsTrackOperationResult(eventAction, startedAt, result, data, errorCode = '', errorType = 'operation') {
+function _settingsLogOperationResult(eventAction, startedAt, result, data, errorCode = '', errorType = 'operation') {
const payload = {
result,
duration_ms: Math.max(0, Date.now() - startedAt),
@@ -91,12 +79,6 @@ function _settingsTrackOperationResult(eventAction, startedAt, result, data, err
_settingsLog[level]('settings operation result', { operation: eventAction, ...payload });
}
-function _settingsTrackModelProviderSelect() {}
-
-// The open build keeps the settings flow intact but intentionally has no
-// internal model-configuration telemetry sink.
-function _settingsTrackModelConfigResult() {}
-
function _settingsResultErrorCode(res, fallback = 'operation_failed') {
const code = String((res && res.code) || '').trim();
return /^[A-Za-z0-9_.-]{1,64}$/.test(code) ? code : fallback;
@@ -179,21 +161,20 @@ function _settingsNormalizeTaskNotificationPermission(permission) {
};
}
-function _settingsReportTaskNotificationPermission(source) {
+function _settingsLogTaskNotificationPermission(source) {
const state = _settingsState.taskNotifications || {
enabled: true,
permission: { state: 'unknown', can_open_settings: false },
};
const permissionState = _settingsTaskNotificationPermissionState(state);
const key = `${!!state.enabled}:${permissionState}`;
- if (_settingsState.taskNotificationPermissionTelemetryKey === key) return;
- _settingsState.taskNotificationPermissionTelemetryKey = key;
+ if (_settingsState.taskNotificationPermissionLogKey === key) return;
+ _settingsState.taskNotificationPermissionLogKey = key;
const payload = {
enabled: !!state.enabled,
permission_state: permissionState,
source: String(source || 'settings_load'),
};
- _settingsTrackEvent('task_notification_permission_state', payload);
_settingsLog.info('task notification state observed', payload);
}
@@ -220,7 +201,7 @@ async function _settingsRefreshTaskNotifications(source = 'settings_load') {
} catch (_) {
return false;
}
- _settingsReportTaskNotificationPermission(source);
+ _settingsLogTaskNotificationPermission(source);
_settingsRenderTaskNotifications();
return true;
}
@@ -271,7 +252,6 @@ function _settingsRenderTaskNotifications() {
if (!openBtn.dataset.bound) {
openBtn.addEventListener('click', async () => {
openBtn.disabled = true;
- _settingsTrackClick('task_notification_permission_open');
try {
const res = await window.orkas.invoke('prefs.openTaskNotificationSettings');
if (!res || !res.ok || !res.opened) {
@@ -293,14 +273,12 @@ function _settingsRenderTaskNotifications() {
if (!cb.dataset.bound) {
cb.addEventListener('change', async () => {
_settingsState.taskNotificationsToggleEpoch += 1;
- const startedAt = Date.now();
const next = !!cb.checked;
const currentState = _settingsState.taskNotifications || {
enabled: true,
permission: { state: 'unknown', can_open_settings: false },
};
const previous = !!currentState.enabled;
- const targetState = next ? 'enabled' : 'disabled';
const permissionState = _settingsTaskNotificationPermissionState(currentState);
// Keep state aligned with the already-changed checkbox while persistence
// is pending. A concurrent permission refresh can then render without
@@ -325,19 +303,12 @@ function _settingsRenderTaskNotifications() {
: latestState.permission,
};
const savedPermissionState = _settingsTaskNotificationPermissionState(_settingsState.taskNotifications);
- _settingsTrackEvent('task_notification_toggle_result', {
- result: 'success',
- enabled: savedEnabled,
- target_state: targetState,
- permission_state: savedPermissionState,
- duration_ms: Math.max(0, Date.now() - startedAt),
- });
_settingsLog.info('task notification toggle saved', {
previous_enabled: previous,
enabled: savedEnabled,
permission_state: savedPermissionState,
});
- _settingsReportTaskNotificationPermission('toggle_result');
+ _settingsLogTaskNotificationPermission('toggle_result');
} else {
const actualEnabled = res && res.ok ? savedEnabled : previous;
_settingsState.taskNotifications = {
@@ -347,43 +318,19 @@ function _settingsRenderTaskNotifications() {
? _settingsNormalizeTaskNotificationPermission(res.permission)
: latestState.permission,
};
- const actualPermissionState = _settingsTaskNotificationPermissionState(
- _settingsState.taskNotifications,
- );
const mismatch = !!(res && res.ok);
- _settingsTrackEvent('task_notification_toggle_result', {
- result: 'failure',
- enabled: actualEnabled,
- target_state: targetState,
- permission_state: actualPermissionState,
- duration_ms: Math.max(0, Date.now() - startedAt),
- error_type: 'persistence',
- error_code: mismatch ? 'update_mismatch' : 'update_rejected',
- });
_settingsLog.warn('set task notifications rejected', {
target_enabled: next,
actual_enabled: actualEnabled,
error_code: mismatch ? 'update_mismatch' : 'update_rejected',
});
- if (mismatch) _settingsReportTaskNotificationPermission('toggle_result');
+ if (mismatch) _settingsLogTaskNotificationPermission('toggle_result');
}
} catch (err) {
_settingsState.taskNotifications = {
...(_settingsState.taskNotifications || currentState),
enabled: previous,
};
- const actualPermissionState = _settingsTaskNotificationPermissionState(
- _settingsState.taskNotifications,
- );
- _settingsTrackEvent('task_notification_toggle_result', {
- result: 'failure',
- enabled: previous,
- target_state: targetState,
- permission_state: actualPermissionState,
- duration_ms: Math.max(0, Date.now() - startedAt),
- error_type: 'ipc',
- error_code: 'invoke_failed',
- });
_settingsLog.warn('set task notifications failed', {
error_type: err && typeof err.name === 'string' ? err.name : 'unknown',
});
@@ -731,7 +678,7 @@ function _settingsRenderLocalExec() {
const actual = res && res.ok && returnedMode ? returnedMode : prev;
_settingsState.localExec = { mode: actual };
_settingsRenderLocalExec();
- _settingsTrackOperationResult(
+ _settingsLogOperationResult(
'localexec_mode_change_result', startedAt, 'failure',
{ target_mode: next, actual_mode: actual },
res && res.ok ? 'update_mismatch' : 'update_rejected',
@@ -740,7 +687,7 @@ function _settingsRenderLocalExec() {
} catch (err) {
_settingsState.localExec = { mode: prev };
_settingsRenderLocalExec();
- _settingsTrackOperationResult(
+ _settingsLogOperationResult(
'localexec_mode_change_result', startedAt, 'failure',
{ target_mode: next, actual_mode: prev }, 'invoke_failed', 'ipc',
);
@@ -823,12 +770,6 @@ function _settingsBindMetacognitionOnce() {
if (epoch !== _settingsState.metacognitionToggleEpoch) return;
if (res && res.ok) {
_settingsState.metacognition = { ..._settingsState.metacognition, enabled: !!res.enabled };
- _settingsTrackEvent('metacognition_toggle_result', {
- result: 'success',
- enabled: !!res.enabled,
- target_enabled: next,
- duration_ms: Math.max(0, Date.now() - startedAt),
- });
} else {
// The initial preference read may have been in flight when the user
// clicked. Its enabled value is intentionally ignored after the epoch
@@ -837,14 +778,6 @@ function _settingsBindMetacognitionOnce() {
await _settingsRefreshMetacognition({ failureFallbackEnabled: previous });
const actualEnabled = !!(_settingsState.metacognition && _settingsState.metacognition.enabled);
_settingsLog.warn('setMetacognition rejected', { error_code: 'update_rejected' });
- _settingsTrackEvent('metacognition_toggle_result', {
- result: 'failure',
- enabled: actualEnabled,
- target_enabled: next,
- duration_ms: Math.max(0, Date.now() - startedAt),
- error_type: 'operation',
- error_code: 'update_rejected',
- });
}
} catch (err) {
if (epoch !== _settingsState.metacognitionToggleEpoch) return;
@@ -853,14 +786,6 @@ function _settingsBindMetacognitionOnce() {
_settingsLog.warn('setMetacognition failed', {
error_type: err && typeof err.name === 'string' ? err.name : 'unknown',
});
- _settingsTrackEvent('metacognition_toggle_result', {
- result: 'failure',
- enabled: actualEnabled,
- target_enabled: next,
- duration_ms: Math.max(0, Date.now() - startedAt),
- error_type: 'ipc',
- error_code: 'invoke_failed',
- });
} finally {
if (epoch === _settingsState.metacognitionToggleEpoch) {
_settingsRenderMetacognition();
@@ -911,28 +836,12 @@ function _settingsRenderDataRoot() {
_settingsLog.warn('open data root failed', {
error_type: err && typeof err.name === 'string' ? err.name : 'unknown',
});
- _settingsTrackEvent('settings_open_data_root_result', {
- result: 'failure',
- duration_ms: Math.max(0, Date.now() - startedAt),
- error_type: 'ipc',
- error_code: 'invoke_failed',
- });
return;
}
if (!res || res.ok === false) {
_settingsLog.warn('open data root rejected', { error_code: 'open_rejected' });
- _settingsTrackEvent('settings_open_data_root_result', {
- result: 'failure',
- duration_ms: Math.max(0, Date.now() - startedAt),
- error_type: 'operation',
- error_code: 'open_rejected',
- });
return;
}
- _settingsTrackEvent('settings_open_data_root_result', {
- result: 'success',
- duration_ms: Math.max(0, Date.now() - startedAt),
- });
});
btn.dataset.bound = '1';
}
@@ -1038,7 +947,7 @@ function _settingsBindModelTabsOnce() {
_settingsActivateModelTab(list[next].dataset.settingsModelTab, { focus: true, explicit: true });
});
});
- // Initial / programmatic activation: no telemetry (mirrors click_settings_tab).
+ // Initial / programmatic activation does not represent a user navigation.
_settingsActivateModelTab(_settingsState.modelTab || 'chat');
}
@@ -1047,7 +956,6 @@ function _settingsActivateModelTab(kind, opts = {}) {
// `click_settings_model_tab` — explicit user selection of a Models purpose
// sub-tab (mouse or arrow keys). Bounded payload: the purpose id only.
if (opts.explicit) {
- _settingsTrackClick('settings_model_tab', { kind: target, source_view: 'settings' });
}
_settingsState.modelTab = target;
_settingsQueryAll('[data-settings-model-tab]').forEach((btn) => {
@@ -1561,14 +1469,12 @@ function _settingsShowApiKeyForm(provider, modelId) {
if (!resolvedModelId) {
msg.textContent = t('settings.custom.error_model');
msg.className = 'form-msg error';
- _settingsTrackModelConfigResult(startedAt, 'add', 'api_key', 'blocked', 'model_required');
modelInput?.focus();
return;
}
if (!apiKey) {
msg.textContent = t('settings.paste_key_first');
msg.className = 'form-msg error';
- _settingsTrackModelConfigResult(startedAt, 'add', 'api_key', 'blocked', 'api_key_required');
return;
}
saveBtn.disabled = true;
@@ -1592,7 +1498,6 @@ function _settingsShowApiKeyForm(provider, modelId) {
_settingsLog.warn('add api key failed', { provider: provider.id, error: addRes && addRes.error });
return;
}
- _settingsTrackModelConfigResult(startedAt, 'add', 'api_key', 'success');
saveBtn.disabled = false;
_settingsCloseModal(overlay);
await _settingsReload();
@@ -1751,13 +1656,6 @@ function _settingsShowCustomModelForm(provider) {
if (errorCode) {
msg.textContent = _settingsCustomModelError(errorCode);
msg.className = 'form-msg error';
- _settingsTrackModelConfigResult(
- startedAt,
- 'add',
- 'custom',
- 'blocked',
- _settingsModelConfigValidationCode(errorCode),
- );
return;
}
@@ -1780,16 +1678,8 @@ function _settingsShowCustomModelForm(provider) {
model,
error_code: addRes && addRes.code,
});
- _settingsTrackModelConfigResult(
- startedAt,
- 'add',
- 'custom',
- 'failure',
- _settingsResultErrorCode(addRes),
- );
return;
}
- _settingsTrackModelConfigResult(startedAt, 'add', 'custom', 'success');
saveBtn.disabled = false;
_settingsCloseModal(overlay);
await _settingsReload();
@@ -1843,15 +1733,7 @@ function _settingsCloseModal(overlay) {
let _oauthFlowPollTimer = null;
let _oauthFlowId = null;
-let _oauthFlowTarget = null; // { provider, modelId }
-let _oauthFlowTelemetry = null;
-
-function _settingsFinishOAuthTelemetry(result, errorCode = '') {
- if (!_oauthFlowTelemetry || _oauthFlowTelemetry.done) return;
- const startedAt = _oauthFlowTelemetry.startedAt;
- _oauthFlowTelemetry.done = true;
- _settingsTrackModelConfigResult(startedAt, 'add', 'oauth', result, errorCode);
-}
+let _oauthFlowTarget = null;
async function _settingsStartOAuthFlow(provider, modelId) {
const overlay = document.getElementById('oauth-flow-modal');
@@ -1867,7 +1749,6 @@ async function _settingsStartOAuthFlow(provider, modelId) {
_settingsCloseAddModal();
_oauthFlowTarget = { provider, modelId, oauthProviderId };
- _oauthFlowTelemetry = { startedAt: Date.now(), done: false };
title.textContent = t('settings.oauth.title_prefix', { provider: provider.label || provider.id });
const aliasTip = aliased
? `<div class="oauth-flow-hint">${escapeHtml(t('settings.oauth.alias_tip', { provider: oauthProviderId }))}</div>`
@@ -1876,14 +1757,12 @@ async function _settingsStartOAuthFlow(provider, modelId) {
overlay.classList.add('open');
const closeFlow = () => {
- _settingsFinishOAuthTelemetry('cancelled', 'cancelled');
if (_oauthFlowPollTimer) { clearInterval(_oauthFlowPollTimer); _oauthFlowPollTimer = null; }
if (_oauthFlowId) {
window.orkas.invoke('auth.cancelOAuthFlow', { flowId: _oauthFlowId }).catch(() => {});
}
_oauthFlowId = null;
_oauthFlowTarget = null;
- _oauthFlowTelemetry = null;
overlay.classList.remove('open');
document.removeEventListener('keydown', onKey, true);
};
@@ -2019,7 +1898,6 @@ function _oauthFlowRender(provider, status, closeFlow) {
error_code: errorCode,
...logContext,
});
- _settingsFinishOAuthTelemetry('failure', errorCode);
};
if (!target || !target.modelId || !profileId) {
@@ -2066,7 +1944,6 @@ function _oauthFlowRender(provider, status, closeFlow) {
});
return;
}
- _settingsFinishOAuthTelemetry('success');
closeFlow();
await _settingsReload();
})();
@@ -2076,7 +1953,6 @@ function _oauthFlowRender(provider, status, closeFlow) {
if (status.kind === 'error') {
body.innerHTML = `<div class="oauth-flow-stage error">${escapeHtml(status.error || t('settings.oauth.auth_failed'))}</div>`;
if (_oauthFlowPollTimer) { clearInterval(_oauthFlowPollTimer); _oauthFlowPollTimer = null; }
- _settingsFinishOAuthTelemetry('failure', 'oauth_failed');
return;
}
}
@@ -2149,18 +2025,10 @@ async function _settingsUpdateEntryModel(entry, model, modelSel) {
if (!res || !res.ok) {
const errorCode = _settingsResultErrorCode(res);
_settingsLog.warn('model configuration update failed', { error_code: errorCode });
- _settingsTrackModelConfigResult(
- startedAt,
- 'update_model',
- 'existing',
- 'failure',
- errorCode,
- );
await uiAlert((res && res.error) || t('settings.entries.switch_model_failed'));
modelSel?.setValue(entry.model);
return false;
}
- _settingsTrackModelConfigResult(startedAt, 'update_model', 'existing', 'success');
await _settingsReload();
return true;
}
@@ -2453,17 +2321,9 @@ async function _settingsRemoveEntry(entry) {
catch (_) { res = { ok: false, code: 'invoke_failed' }; }
if (!res || !res.ok) {
_settingsLog.warn('remove entry failed', { entry_id: entry.entryId, error: res && res.error });
- _settingsTrackModelConfigResult(
- startedAt,
- 'remove',
- 'existing',
- 'failure',
- _settingsResultErrorCode(res),
- );
await uiAlert((res && res.error) || t('settings.entries.delete_failed'));
return;
}
- _settingsTrackModelConfigResult(startedAt, 'remove', 'existing', 'success');
await _settingsReload();
}
@@ -2852,7 +2712,6 @@ function _settingsRenderVideoPicker() {
placeholder: t('settings.video.pick_provider'),
});
_settingsState.videoProviderSel.onChange((provider) => {
- _settingsTrackModelProviderSelect('video_auth_picker', provider);
_settingsSetStatus('settings-video-status', '', '');
});
}
diff --git a/src/renderer/modules/sidebar-sections.js b/src/renderer/modules/sidebar-sections.js
index 4ffdb855..ff8c4e51 100644
--- a/src/renderer/modules/sidebar-sections.js
+++ b/src/renderer/modules/sidebar-sections.js
@@ -59,17 +59,6 @@
);
}
- function trackSidebarSectionToggle(detail, monitor) {
- try {
- if (monitor && typeof monitor.click === 'function') {
- monitor.click('sidebar_section_toggle', {
- section: detail.name,
- control_state: detail.collapsed ? 'close' : 'open',
- });
- }
- } catch (_) {}
- }
-
function initSidebarSections(doc, storage, translate, onToggle) {
const state = readCollapsedState(storage);
const applyAll = () => SECTION_CONFIG.forEach((config) => {
@@ -99,7 +88,6 @@
localStorage,
(key, params) => t(key, params),
(detail) => {
- trackSidebarSectionToggle(detail, window.Monitor);
window.dispatchEvent(new CustomEvent('sidebar-section-toggle', { detail }));
},
);
@@ -113,7 +101,6 @@
readCollapsedState,
applySectionState,
initSidebarSections,
- trackSidebarSectionToggle,
};
}
if (typeof document !== 'undefined') {
diff --git a/src/renderer/modules/skills.js b/src/renderer/modules/skills.js
index 912e4c92..304192ce 100644
--- a/src/renderer/modules/skills.js
+++ b/src/renderer/modules/skills.js
@@ -1,7 +1,7 @@
const _skillsLog = createLogger('skills');
// ─── Skills ───
-function _skillsTrackError(action, data) {
+function _skillsLogError(action, data) {
_skillsLog.warn('skill operation failed', { action, ...(data || {}) });
}
@@ -43,7 +43,7 @@ function _reportSkillAutosaveFailure(value) {
if (previousAt && now - previousAt < _SKILL_AUTOSAVE_FAILURE_DEDUPE_MS) return;
_skillAutosaveFailureState.lastAtByCode.set(errorCode, now);
_skillAutosaveFailureState.uploadCount += 1;
- _skillsTrackError('skill_manage', {
+ _skillsLogError('skill_manage', {
action: 'edit',
error_type: 'ipc',
error_code: errorCode,
@@ -750,11 +750,9 @@ function _wireOpenSkillCards(gridEl) {
}
async function _setOpenSkillEnabled(id, nextEnabled) {
- const trackResult = _createSkillManageTracker('toggle');
try {
const res = await window.orkas.invoke('skills.setEnabled', { id, enabled: nextEnabled });
if (!res || !res.ok) {
- trackResult('failure', _skillManageErrorCode(res, 'update_failed'));
await uiAlert(t('component.toggle_failed'));
return false;
}
@@ -762,10 +760,8 @@ async function _setOpenSkillEnabled(id, nextEnabled) {
// external and global, so flip every matching row's optimistic state.
for (const r of _openSkillsCache) if (r.id === id) r.enabled = nextEnabled;
renderSkillsList(_skillsCache || []);
- trackResult('success');
return true;
} catch (error) {
- trackResult('failure', _skillManageErrorCode(error, 'invoke_failed'));
await uiAlert(t('component.toggle_failed'));
return false;
}
@@ -777,13 +773,11 @@ async function _setGlobalSkillGroupEnabled(key, nextEnabled) {
.filter((row) => (row.enabled !== false) !== nextEnabled)
.map((row) => row.id));
if (!targetIds.size) return true;
- const trackResult = _createSkillManageTracker('toggle');
try {
const results = await Promise.allSettled(Array.from(targetIds).map((id) => (
window.orkas.invoke('skills.setEnabled', { id, enabled: nextEnabled })
)));
if (results.some((res) => res.status === 'rejected' || !res.value || !res.value.ok)) {
- trackResult('failure', 'partial_failure');
await loadSkills(true);
await uiAlert(t('component.toggle_failed'));
return false;
@@ -792,10 +786,8 @@ async function _setGlobalSkillGroupEnabled(key, nextEnabled) {
if (targetIds.has(row.id)) row.enabled = nextEnabled;
}
renderSkillsList(_skillsCache || []);
- trackResult('success');
return true;
} catch (error) {
- trackResult('failure', _skillManageErrorCode(error, 'invoke_failed'));
await loadSkills(true);
await uiAlert(t('component.toggle_failed'));
return false;
@@ -967,21 +959,17 @@ async function _flipOpenSkillEnabled(id) {
* and the detail-page enable/disable button). On failure, alerts and does
* not mutate UI state; on success, refreshes the grid + detail page. */
async function _flipSkillEnabled(skillId, nextEnabled) {
- const trackResult = _createSkillManageTracker('toggle');
let res;
try {
res = await window.orkas.invoke('skills.setEnabled', { id: skillId, enabled: nextEnabled });
} catch (err) {
- trackResult('failure', 'invoke_failed');
await uiAlert(t('component.toggle_failed'));
return false;
}
if (!res || !res.ok) {
- trackResult('failure', 'update_failed');
await uiAlert(t('component.toggle_failed'));
return false;
}
- trackResult('success');
const cached = _skillsCache?.find((s) => s.id === skillId);
if (cached) cached.enabled = nextEnabled;
try {
@@ -995,22 +983,6 @@ async function _flipSkillEnabled(skillId, nextEnabled) {
return true;
}
-function _createSkillManageTracker(action) {
- const startedAt = Date.now();
- let done = false;
- return (result, errorCode = '') => {
- if (done) return;
- done = true;
- const payload = {
- result,
- action,
- duration_ms: Math.max(0, Date.now() - startedAt),
- };
- if (result !== 'success') payload.error_code = errorCode || 'unknown';
- _skillsLog.info('skill operation result', payload);
- };
-}
-
// ─── View switching: grid ↔ detail ─────────────────────────────────────
// Back from the skill detail/edit view. An unconfirmed URL-import draft (a
@@ -1764,7 +1736,6 @@ function _renderSkillDetailCategory(skill, source) {
_mountDetailCategorySelect(sourceEl, {
value: skill?.category || 'general',
onChange: async (category, api) => {
- const trackResult = _createSkillManageTracker('edit');
try {
const res = await window.orkas.invoke('skills.update', {
id: skillId,
@@ -1772,12 +1743,10 @@ function _renderSkillDetailCategory(skill, source) {
skipRename: true,
});
if (!res || res.ok === false || !res.skill) {
- trackResult('failure', _skillManageErrorCode(res, 'update_failed'));
api.setValue(skill?.category || 'general');
uiAlert((res && res.error) || t('skills.save_failed'));
return;
}
- trackResult('success');
skill.category = res.skill.category || category || 'general';
_skillsCache = null;
await loadSkills(true);
@@ -1785,7 +1754,6 @@ function _renderSkillDetailCategory(skill, source) {
await selectSkillFile('custom', skillId, _selectedSkill.filepath || 'SKILL.md', null);
}
} catch (err) {
- trackResult('failure', _skillManageErrorCode(err, 'invoke_failed'));
api.setValue(skill?.category || 'general');
uiAlert((err && err.message) || t('skills.save_failed'));
}
@@ -2580,55 +2548,6 @@ async function pickSkillImportDir() {
}
window.pickSkillImportDir = pickSkillImportDir;
-function _skillCreateNow() {
- if (typeof performance !== 'undefined' && performance && typeof performance.now === 'function') {
- return performance.now();
- }
- return Date.now();
-}
-
-function _skillCreateDuration(startedAt) {
- return Math.max(0, Math.round(_skillCreateNow() - Number(startedAt || 0)));
-}
-
-function _skillCreatePayload(creationMethod, data) {
- return Object.assign({ creation_method: creationMethod }, data || {});
-}
-
-function _skillCreateTrackClick(creationMethod, data) {
- try {
- const monitor = (typeof window !== 'undefined') ? window.Monitor : null;
- if (monitor && typeof monitor.click === 'function') {
- monitor.click('skill_create_submit', _skillCreatePayload(creationMethod, data));
- }
- } catch (_) {}
-}
-
-function _skillCreateTrackResult(tracking, result, data) {
- if (!tracking || tracking.done) return false;
- tracking.done = true;
- try {
- const monitor = (typeof window !== 'undefined') ? window.Monitor : null;
- if (monitor && typeof monitor.event === 'function') {
- monitor.event('skill_create_result', _skillCreatePayload(tracking.creationMethod, Object.assign({
- result,
- duration_ms: _skillCreateDuration(tracking.startedAt),
- }, data || {})));
- }
- } catch (_) {}
- return true;
-}
-
-function _skillCreateTracking(creationMethod, clickData) {
- const tracking = {
- creationMethod,
- startedAt: _skillCreateNow(),
- done: false,
- };
- _skillCreateTrackClick(creationMethod, clickData);
- return tracking;
-}
-
function _skillCreateIdFromResponse(data) {
return data?.skill?.id || data?.skills?.[0]?.id || '';
}
@@ -2656,7 +2575,6 @@ async function saveSkill() {
window.saveSkill = saveSkill;
async function _saveSkillManual({ editId, msgEl }) {
- const tracking = editId ? null : _skillCreateTracking('manual');
const rawName = document.getElementById('skill-name').value;
const name = rawName.trim();
const description = document.getElementById('skill-description').value.trim();
@@ -2664,21 +2582,18 @@ async function _saveSkillManual({ editId, msgEl }) {
msgEl.textContent = t('skills.input_name_needed');
msgEl.className = 'form-msg err';
document.getElementById('skill-name').focus();
- if (tracking) _skillCreateTrackResult(tracking, 'blocked', { error_code: 'no_name' });
return;
}
if (!_isValidSkillNameCharset(rawName)) {
msgEl.textContent = t('skills.name_invalid');
msgEl.className = 'form-msg err';
document.getElementById('skill-name').focus();
- if (tracking) _skillCreateTrackResult(tracking, 'blocked', { error_code: 'name_invalid' });
return;
}
if (!description) {
msgEl.textContent = t('skills.input_desc_needed');
msgEl.className = 'form-msg err';
document.getElementById('skill-description').focus();
- if (tracking) _skillCreateTrackResult(tracking, 'blocked', { error_code: 'no_desc' });
return;
}
try {
@@ -2701,38 +2616,21 @@ async function _saveSkillManual({ editId, msgEl }) {
if (!data.ok) {
msgEl.textContent = data.error || t('skills.save_failed');
msgEl.className = 'form-msg err';
- if (tracking) {
- _skillCreateTrackResult(tracking, 'failure', {
- error_code: _skillManageErrorCode(data, 'create_failed'),
- });
- }
return;
}
- if (tracking) {
- _skillCreateTrackResult(tracking, 'success', {
- skill_count: _skillCreateCountFromResponse(data),
- });
- }
await _afterSkillCreated(data.skill?.id || editId, !editId, null);
} catch (e) {
msgEl.textContent = t('skills.network_error_plain');
msgEl.className = 'form-msg err';
- if (tracking) {
- if (!_skillCreateTrackResult(tracking, 'failure', { error_code: 'network_failed' })) {
- _skillsLog.warn('skill post-create refresh failed', { creation_method: 'manual', error_code: 'refresh_failed' });
- }
- }
}
}
async function _saveSkillFromUrl({ msgEl }) {
- const tracking = _skillCreateTracking('url');
const url = document.getElementById('skill-url-input').value.trim();
if (!/^https?:\/\//i.test(url)) {
msgEl.textContent = t('skill_modal.err_url_invalid');
msgEl.className = 'form-msg err';
document.getElementById('skill-url-input').focus();
- _skillCreateTrackResult(tracking, 'blocked', { error_code: 'url_invalid' });
return;
}
try {
@@ -2750,9 +2648,6 @@ async function _saveSkillFromUrl({ msgEl }) {
msgEl.textContent = data.error || t('skills.save_failed');
msgEl.className = 'form-msg err';
_setSkillModalBusy(false);
- _skillCreateTrackResult(tracking, 'failure', {
- error_code: _skillManageErrorCode(data, 'import_failed'),
- });
return;
}
const createdId = _skillCreateIdFromResponse(data);
@@ -2760,35 +2655,26 @@ async function _saveSkillFromUrl({ msgEl }) {
// URL imports start as empty placeholders. If the user backs out before
// the edit chat authors real content, offer to discard that placeholder.
_importDraftId = data.skill?.id && _skillAutoSeedHasModelText(autoSeed) ? data.skill.id : null;
- _skillCreateTrackResult(tracking, 'success', {
- skill_count: _skillCreateCountFromResponse(data),
- });
await _afterSkillCreated(createdId, true, autoSeed);
} catch (e) {
msgEl.textContent = t('skills.network_error_plain');
msgEl.className = 'form-msg err';
- if (!_skillCreateTrackResult(tracking, 'failure', { error_code: 'network_failed' })) {
- _skillsLog.warn('skill post-create refresh failed', { creation_method: 'url', error_code: 'refresh_failed' });
- }
} finally {
_setSkillModalBusy(false);
}
}
async function _saveSkillFromDir({ msgEl }) {
- const tracking = _skillCreateTracking('dir');
const srcDir = document.getElementById('skill-dir-path').value.trim();
if (!srcDir) {
msgEl.textContent = t('skill_modal.err_dir_missing');
msgEl.className = 'form-msg err';
- _skillCreateTrackResult(tracking, 'blocked', { error_code: 'dir_missing' });
return;
}
return _saveSkillFromDirWithQuality({
msgEl,
srcDir,
force: false,
- tracking,
});
}
@@ -2805,8 +2691,7 @@ function _qualityImportRejectedTitle(name) {
: tmpl.replace('{name}', name);
}
-async function _saveSkillFromDirWithQuality({ msgEl, srcDir, force, tracking }) {
- tracking = tracking || _skillCreateTracking('dir');
+async function _saveSkillFromDirWithQuality({ msgEl, srcDir, force }) {
try {
msgEl.textContent = t('skills.saving');
msgEl.className = 'form-msg';
@@ -2828,39 +2713,21 @@ async function _saveSkillFromDirWithQuality({ msgEl, srcDir, force, tracking })
forceLabel: _qualityForceImportLabel(),
});
if (action === 'force') {
- return await _saveSkillFromDirWithQuality({ msgEl, srcDir, force: true, tracking });
+ return await _saveSkillFromDirWithQuality({ msgEl, srcDir, force: true });
}
- _skillCreateTrackResult(tracking, 'blocked', {
- forced: false,
- error_code: _skillManageErrorCode(data, 'quality_validation'),
- });
msgEl.textContent = data.error || t('skills.save_failed');
msgEl.className = 'form-msg err';
return;
}
msgEl.textContent = data.error || t('skills.save_failed');
msgEl.className = 'form-msg err';
- _skillCreateTrackResult(tracking, 'failure', {
- forced: !!force,
- error_code: _skillManageErrorCode(data, data.report ? 'quality_validation' : 'import_failed'),
- });
return;
}
const createdId = _skillCreateIdFromResponse(data);
- _skillCreateTrackResult(tracking, 'success', {
- skill_count: _skillCreateCountFromResponse(data),
- forced: !!force,
- });
await _afterSkillCreated(createdId, true, _skillImportAutoSeedFromResponse(data));
} catch (e) {
msgEl.textContent = t('skills.network_error_plain');
msgEl.className = 'form-msg err';
- if (!_skillCreateTrackResult(tracking, 'failure', {
- forced: !!force,
- error_code: 'network_failed',
- })) {
- _skillsLog.warn('skill post-create refresh failed', { creation_method: 'dir', error_code: 'refresh_failed' });
- }
} finally {
_setSkillModalBusy(false);
}
@@ -2918,23 +2785,19 @@ async function deleteSelectedSkill() {
const confirmKey = isMarketplace ? 'skills.uninstall_confirm' : 'skills.delete_confirm';
const failedWithKey = isMarketplace ? 'skills.uninstall_failed_with' : 'skills.delete_failed_with';
if (!(await uiConfirm(t(confirmKey, { name: cached?.name || sid })))) return;
- const trackResult = _createSkillManageTracker('delete');
let result;
try {
result = isMarketplace
? await window.orkas.invoke('skills.builtin.delete', { id: sid })
: await (await apiFetch(`/api/skills/${sid}`, { method: 'DELETE' })).json();
} catch (e) {
- trackResult('failure', 'request_failed');
await uiAlert(t(failedWithKey, { reason: e.message || e }));
return;
}
if (!result || !result.ok) {
- trackResult('failure', 'delete_failed');
await uiAlert(t(failedWithKey, { reason: result?.error || '' }));
return;
}
- trackResult('success');
_selectedSkill = null;
_skillsCache = null;
_skillTreeCache.clear();
diff --git a/src/renderer/modules/state.js b/src/renderer/modules/state.js
index 8d405309..8d186def 100644
--- a/src/renderer/modules/state.js
+++ b/src/renderer/modules/state.js
@@ -93,9 +93,7 @@ function _consumePendingTaskNotificationConversation() {
return _openTaskNotificationConversation(_pendingTaskNotificationNavigation);
}
-// Keep sidebar navigation independent from private analytics. The commercial
-// build decorates this boundary with click tracking; the open build still
-// needs the routing wrapper because every sidebar handler calls it.
+// Keep the shared routing wrapper because every sidebar handler calls it.
function _setViewFromSidebar(targetView) {
// The shell becomes clickable before asynchronous boot stages finish.
// Preserve explicit user navigation over the later startup restore.
@@ -103,10 +101,6 @@ function _setViewFromSidebar(targetView) {
setView(targetView);
}
-// Public agent creation has no analytics dependency, but its click handler
-// intentionally keeps the same hook as the commercial build.
-function _trackAgentCreateOpen() {}
-
const _DRAFT_KEY = (cid) => `draft_${cid}`;
// Polling: detect assistant responses even after page refresh / reconnect
@@ -427,7 +421,6 @@ function bindStaticHandlers() {
// Agents (grid + detail)
// "Done" button (only visible while editing) — exits edit mode.
document.getElementById('create-agent-btn')?.addEventListener('click', () => {
- _trackAgentCreateOpen('agents_create_button');
openAgentModal({
entryPoint: 'agents_create_button',
sourceView: currentView || '',
@@ -462,7 +455,6 @@ function bindStaticHandlers() {
// what the button promises. Its own `entry_point` keeps the funnel separable
// from the create button's.
document.getElementById('agents-connect-cli-btn')?.addEventListener('click', () => {
- _trackAgentCreateOpen('agents_connect_cli_button', { agent_type: 'cli' });
openAgentModal({
initialTab: 'external',
externalOnly: true,
diff --git a/src/renderer/modules/task-board.js b/src/renderer/modules/task-board.js
index 24bd0f77..affc4d32 100644
--- a/src/renderer/modules/task-board.js
+++ b/src/renderer/modules/task-board.js
@@ -681,9 +681,8 @@ async function _taskBoardEdit(cid, taskId) {
}
}
-// Queued rows currently known for a conversation. Telemetry-facing (the
-// task_stop click reports how much work was waiting behind the stopped
-// execution); 0 for a conversation whose board was never observed.
+// Queued rows currently known for a conversation; 0 for a conversation whose
+// board was never observed.
function _taskBoardQueuedCount(cid) {
const m = cid ? _taskBoardTasks.get(cid) : null;
if (!m) return 0;
diff --git a/src/renderer/modules/text-view-edit.js b/src/renderer/modules/text-view-edit.js
index 4026de49..710b9f8d 100644
--- a/src/renderer/modules/text-view-edit.js
+++ b/src/renderer/modules/text-view-edit.js
@@ -144,15 +144,6 @@ function _tveRender(state) {
else _tveRenderView(state);
}
-function _tveTrack(action, state, data) {
- try {
- if (!window.Monitor) return;
- (() => {})(action, Object.assign({
- can_save: !!(state && state.caps && state.caps.save),
- }, data || {}));
- } catch (_) {}
-}
-
function _tveRenderView(state) {
state.mode = 'view';
state.bodyEl.innerHTML = `<pre class="chat-file-viewer-text">${escapeHtml(state.content)}</pre>`;
diff --git a/src/renderer/modules/user-workspace.js b/src/renderer/modules/user-workspace.js
index cb83159c..1f3203ed 100644
--- a/src/renderer/modules/user-workspace.js
+++ b/src/renderer/modules/user-workspace.js
@@ -28,7 +28,7 @@ const _wsInfoByTarget = {
project: { currentPath: '', defaultPath: '', isDefault: true, recentPaths: [], scope: 'default' },
};
-function _trackWorkspaceOpenFolderResult(target, result, startedAt, errorCode = '') {
+function _logWorkspaceOpenFolderResult(target, result, startedAt, errorCode = '') {
if (result !== 'failure') return;
_wsLog.warn('workspace open folder failed', {
target,
@@ -233,14 +233,14 @@ async function _openWorkspaceFolder(target) {
try {
const result = await window.orkas.invoke('workspace.openPath', hint);
if (result && result.ok) {
- _trackWorkspaceOpenFolderResult(target, 'success', startedAt, '', result);
+ _logWorkspaceOpenFolderResult(target, 'success', startedAt, '', result);
_wsLog.info('workspace opened', { target });
} else {
- _trackWorkspaceOpenFolderResult(target, 'failure', startedAt, 'open_rejected');
+ _logWorkspaceOpenFolderResult(target, 'failure', startedAt, 'open_rejected');
_wsLog.warn('workspace open rejected', { target, error_code: 'open_rejected' });
}
} catch (err) {
- _trackWorkspaceOpenFolderResult(target, 'failure', startedAt, 'invoke_failed');
+ _logWorkspaceOpenFolderResult(target, 'failure', startedAt, 'invoke_failed');
_wsLog.error('workspace open failed', {
target,
error_type: err && typeof err.name === 'string' ? err.name : 'unknown',
diff --git a/src/renderer/modules/utils.js b/src/renderer/modules/utils.js
index 89d56710..d1936baf 100644
--- a/src/renderer/modules/utils.js
+++ b/src/renderer/modules/utils.js
@@ -1098,7 +1098,7 @@ function _dbImage(props) {
const alt = escapeHtml(props.alt || '');
const caption = props.caption
? `<figcaption class="db-image-caption">${escapeHtml(props.caption)}</figcaption>` : '';
- return `<figure class="db-image"><img src="${escapeHtml(src)}" alt="${alt}" data-monitor-resource="dashboard-image">${caption}</figure>`;
+ return `<figure class="db-image"><img src="${escapeHtml(src)}" alt="${alt}">${caption}</figure>`;
}
// ── Chart (minimal inline SVG; line/bar/area/pie) ─────────────────────
@@ -1329,7 +1329,7 @@ function _markdownVideoHtml(src, label, title) {
const openButton = localPath
? `<button type="button" class="chat-md-video-float" data-chat-md-video-open="1" data-video-src="${escapeHtml(src)}" aria-label="${escapeHtml(openLabel)}" title="${escapeHtml(openLabel)}">${_markdownVideoOpenIconHtml()}</button>`
: '';
- return `<span class="chat-md-video-shell" data-chat-video-playback-surface="markdown_bubble"><video class="chat-md-video" width="640" height="360" controls controlslist="nodownload nofullscreen noremoteplayback" disablepictureinpicture disableremoteplayback playsinline preload="metadata" src="${escapeHtml(renderedSrc)}"${t}${materializationAttrs} aria-label="${escapeHtml(label || 'video')}" data-monitor-resource="chat-markdown-video"></video>${openButton}</span>`;
+ return `<span class="chat-md-video-shell" data-chat-video-playback-surface="markdown_bubble"><video class="chat-md-video" width="640" height="360" controls controlslist="nodownload nofullscreen noremoteplayback" disablepictureinpicture disableremoteplayback playsinline preload="metadata" src="${escapeHtml(renderedSrc)}"${t}${materializationAttrs} aria-label="${escapeHtml(label || 'video')}"></video>${openButton}</span>`;
}
function _markdownMediaLabel(src, label, fallback) {
@@ -1369,7 +1369,7 @@ function _markdownAudioHtml(src, label, title) {
return `<span class="chat-md-audio-card"${titleAttr} role="group" aria-label="${escapeHtml(name)}">
<span class="chat-md-audio-icon">${_markdownAudioIconHtml(name)}</span>
<span class="chat-md-audio-header"><span class="chat-md-audio-name">${escapeHtml(name)}</span>${menuButton}</span>
- <audio class="chat-md-audio" controls controlslist="nodownload noplaybackrate noremoteplayback" preload="metadata" src="${escapeHtml(src)}" aria-label="${escapeHtml(name)}" data-monitor-resource="chat-markdown-audio"></audio>
+ <audio class="chat-md-audio" controls controlslist="nodownload noplaybackrate noremoteplayback" preload="metadata" src="${escapeHtml(src)}" aria-label="${escapeHtml(name)}"></audio>
</span>`;
}
@@ -1571,7 +1571,7 @@ function _markdownImageHtml(src, alt, title) {
const materializationAttrs = mediaMeta && managedLocalSrc
? ` data-orkas-remote-src="${escapeHtml(mediaMeta.remoteSrc)}" data-orkas-local-src="${escapeHtml(managedLocalSrc)}"`
: '';
- return `<span class="chat-image-shell chat-md-img-shell is-loading"><img class="chat-md-img" src="${escapeHtml(renderedSrc)}" alt="${escapeHtml(alt)}"${t}${materializationAttrs} data-monitor-resource="chat-markdown-image"></span>`;
+ return `<span class="chat-image-shell chat-md-img-shell is-loading"><img class="chat-md-img" src="${escapeHtml(renderedSrc)}" alt="${escapeHtml(alt)}"${t}${materializationAttrs}></span>`;
}
function _notifyChatImageSettled(node) {
diff --git a/src/renderer/modules/web-assist.js b/src/renderer/modules/web-assist.js
index 71b5e8ab..5ab4f2d0 100644
--- a/src/renderer/modules/web-assist.js
+++ b/src/renderer/modules/web-assist.js
@@ -908,10 +908,6 @@
renderState(state);
});
window.orkas.onPushEvent('web-assist:show', (state) => showFromMain(state));
- window.orkas.onPushEvent('web-assist:failure', (payload) => {
- // Main owns classification, privacy projection and the shared rate budget.
- try { window.Monitor?.error('browser', payload); } catch { /* telemetry is best effort */ }
- });
window.WebAssist = {
openForModel,
close,
diff --git a/src/renderer/preview.html b/src/renderer/preview.html
index 256c472a..da825770 100644
--- a/src/renderer/preview.html
+++ b/src/renderer/preview.html
@@ -10,7 +10,6 @@
<body class="preview-window">
<div id="preview-loading" role="status" data-i18n="common.loading">Loading…</div>
<script src="./modules/logger.js"></script>
- <script src="./modules/preview-monitor.js"></script>
<script src="./modules/dialogs.js"></script>
<script src="./modules/ipc-shim.js"></script>
<script src="./modules/i18n.js"></script>
diff --git a/test/main/features/agents.test.ts b/test/main/features/agents.test.ts
index 34de5cff..5072df9e 100644
--- a/test/main/features/agents.test.ts
+++ b/test/main/features/agents.test.ts
@@ -2666,7 +2666,7 @@ describe('agents › streamSendToAgentEditChat synthesized progress', () => {
yield {
type: 'event',
event: {
- stream: 'agent_run_result',
+ stream: 'agent_run_terminal',
data: {
result: 'success',
terminal_status: terminalStatus,
@@ -2686,7 +2686,7 @@ describe('agents › streamSendToAgentEditChat synthesized progress', () => {
}
expect(events).not.toContainEqual(expect.objectContaining({
- event: expect.objectContaining({ stream: 'agent_run_result' }),
+ event: expect.objectContaining({ stream: 'agent_run_terminal' }),
}));
expect(events).toContainEqual(expect.objectContaining({
type: 'event',
diff --git a/test/main/features/edit_chat_runtime.test.ts b/test/main/features/edit_chat_runtime.test.ts
index e0e843ab..bd01b542 100644
--- a/test/main/features/edit_chat_runtime.test.ts
+++ b/test/main/features/edit_chat_runtime.test.ts
@@ -68,7 +68,7 @@ describe('edit chat runtime normalization', () => {
const normalized = normalizeEditChatRuntimeEvent({
type: 'event',
event: {
- stream: 'agent_run_result',
+ stream: 'agent_run_terminal',
data: {
result: 'success',
terminal_status: terminalStatus,
@@ -106,7 +106,7 @@ describe('edit chat runtime normalization', () => {
const normalized = normalizeEditChatRuntimeEvent({
type: 'event',
event: {
- stream: 'agent_run_result',
+ stream: 'agent_run_terminal',
data: { result, terminal_status: terminalStatus, duration_ms: 9_000 },
},
});
@@ -125,7 +125,7 @@ describe('edit chat runtime normalization', () => {
const normalized = normalizeEditChatRuntimeEvent({
type: 'event',
event: {
- stream: 'agent_run_result',
+ stream: 'agent_run_terminal',
data: { result: 'success', terminal_status: 'completed', duration_ms: 'invalid' },
},
});
diff --git a/test/main/features/group_chat/bus-integration.test.ts b/test/main/features/group_chat/bus-integration.test.ts
index 94479875..c26c64f5 100644
--- a/test/main/features/group_chat/bus-integration.test.ts
+++ b/test/main/features/group_chat/bus-integration.test.ts
@@ -5174,7 +5174,7 @@ describe('group_chat bus integration › task terminal boundary', () => {
{
type: 'event',
event: {
- stream: 'agent_run_result',
+ stream: 'agent_run_terminal',
data: {
run_kind: 'top_level',
terminal_status: 'stopped',
@@ -5441,7 +5441,7 @@ describe('group_chat bus integration › task terminal boundary', () => {
const unsubscribe = bus.subscribeTaskTerminals((event) => {
if (event.conversation_id === cid) terminals.push(event);
});
- _setScript(sid, [{ type: 'event', event: { stream: 'agent_run_result', data: {
+ _setScript(sid, [{ type: 'event', event: { stream: 'agent_run_terminal', data: {
result: 'success', terminal_status: 'waiting_input', duration_ms: 20, run_kind: 'top_level',
} } }]);
try {
diff --git a/test/main/features/group_chat/bus.test.ts b/test/main/features/group_chat/bus.test.ts
index 4c997d94..c84c210e 100644
--- a/test/main/features/group_chat/bus.test.ts
+++ b/test/main/features/group_chat/bus.test.ts
@@ -306,7 +306,7 @@ vi.mock('../../../../src/main/model/client', () => ({
yield {
type: 'event',
event: {
- stream: 'agent_run_result',
+ stream: 'agent_run_terminal',
data: {
provider_ms: 40,
tool_ms: 20,
diff --git a/test/main/features/skills.test.ts b/test/main/features/skills.test.ts
index 03f87aa0..d730d3be 100644
--- a/test/main/features/skills.test.ts
+++ b/test/main/features/skills.test.ts
@@ -2165,7 +2165,7 @@ describe('skills › streamSendToSkillChat synthesized progress', () => {
yield {
type: 'event',
event: {
- stream: 'agent_run_result',
+ stream: 'agent_run_terminal',
data: {
result: 'success',
terminal_status: terminalStatus,
@@ -2185,7 +2185,7 @@ describe('skills › streamSendToSkillChat synthesized progress', () => {
}
expect(events).not.toContainEqual(expect.objectContaining({
- event: expect.objectContaining({ stream: 'agent_run_result' }),
+ event: expect.objectContaining({ stream: 'agent_run_terminal' }),
}));
expect(events).toContainEqual(expect.objectContaining({
type: 'event',
diff --git a/test/main/features/web-assist-control.test.ts b/test/main/features/web-assist-control.test.ts
index 219ed681..e86749ba 100644
--- a/test/main/features/web-assist-control.test.ts
+++ b/test/main/features/web-assist-control.test.ts
@@ -1,9 +1,9 @@
import * as vm from 'node:vm';
import * as path from 'node:path';
import { afterAll, afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
-import { reportWebAssistFailure } from '../../../src/main/features/web_assist_diagnostics';
+import { logWebAssistFailure } from '../../../src/main/features/web_assist_diagnostics';
-vi.mock('../../../src/main/features/web_assist_diagnostics', () => ({ reportWebAssistFailure: vi.fn() }));
+vi.mock('../../../src/main/features/web_assist_diagnostics', () => ({ logWebAssistFailure: vi.fn() }));
const DOWNLOAD_ROOT = vi.hoisted(() => {
const fs = require('node:fs') as typeof import('node:fs');
@@ -354,7 +354,7 @@ import {
describe('Web Assist controlled connector lifecycle', () => {
beforeEach(() => {
electronMock.createWindow?.();
- vi.mocked(reportWebAssistFailure).mockClear();
+ vi.mocked(logWebAssistFailure).mockClear();
confirmMock.decision = 'deny';
confirmMock.requests.length = 0;
confirmMock.grants.clear();
@@ -592,11 +592,11 @@ describe('Web Assist controlled connector lifecycle', () => {
page.emit('did-fail-load', {}, -105, 'ERR_NAME_NOT_RESOLVED', 'https://frame.invalid/', false);
page.emit('did-fail-load', {}, -3, 'ERR_ABORTED', 'https://example.com/old', true);
expect(webAssistState(electronMock.renderer).state.error_code).toBeUndefined();
- expect(reportWebAssistFailure).not.toHaveBeenCalled();
+ expect(logWebAssistFailure).not.toHaveBeenCalled();
page.emit('did-fail-load', {}, -105, 'ERR_NAME_NOT_RESOLVED', 'https://missing.invalid/', true);
page.emit('did-stop-loading');
expect(webAssistState(electronMock.renderer).state).toMatchObject({ loading: false, error_code: 'page_load_failed' });
- expect(reportWebAssistFailure).toHaveBeenCalledExactlyOnceWith(electronMock.renderer, 'page_load_failed', -105);
+ expect(logWebAssistFailure).toHaveBeenCalledExactlyOnceWith(electronMock.renderer, 'page_load_failed', -105);
page.emit('did-finish-load');
expect(webAssistState(electronMock.renderer).state.error_code).toBe('page_load_failed');
page.emit('did-navigate', {}, 'https://example.com/recovered', 200, 'OK');
@@ -604,11 +604,11 @@ describe('Web Assist controlled connector lifecycle', () => {
page.emit('unresponsive');
page.emit('did-navigate', {}, 'https://example.com/recovered', 200, 'OK');
expect(webAssistState(electronMock.renderer).state.error_code).toBe('page_unresponsive');
- expect(reportWebAssistFailure).toHaveBeenLastCalledWith(electronMock.renderer, 'page_unresponsive');
+ expect(logWebAssistFailure).toHaveBeenLastCalledWith(electronMock.renderer, 'page_unresponsive');
page.emit('render-process-gone', {}, { reason: 'clean-exit' });
- expect(reportWebAssistFailure).toHaveBeenCalledTimes(2);
+ expect(logWebAssistFailure).toHaveBeenCalledTimes(2);
page.emit('render-process-gone', {}, { reason: 'crashed', exitCode: 1 });
- expect(reportWebAssistFailure).toHaveBeenLastCalledWith(electronMock.renderer, 'renderer_gone');
+ expect(logWebAssistFailure).toHaveBeenLastCalledWith(electronMock.renderer, 'renderer_gone');
});
});
diff --git a/test/main/features/web-assist-diagnostics.test.ts b/test/main/features/web-assist-diagnostics.test.ts
index bd3698bd..9c2990d3 100644
--- a/test/main/features/web-assist-diagnostics.test.ts
+++ b/test/main/features/web-assist-diagnostics.test.ts
@@ -10,53 +10,46 @@ describe('core browser incident sampling', () => {
vi.useFakeTimers();
vi.setSystemTime(0);
const report = createWebAssistDiagnostics();
- const sender = { isDestroyed: () => false, send: vi.fn() };
+ const sender = { isDestroyed: () => false };
report(sender, 'page_load_failed', -105);
- expect(sender.send).toHaveBeenCalledExactlyOnceWith('web-assist:failure', {
+ expect(warn).toHaveBeenCalledExactlyOnceWith('browser failure', {
stage: 'load', error_type: 'network', error_message: 'Browser main-frame navigation failed',
error_code: 'page_load_failed', net_error_code: -105, suppressed_count: 0,
});
for (let i = 0; i < 100; i++) report(sender, 'page_load_failed', -118);
- expect(sender.send).toHaveBeenCalledTimes(1);
expect(warn).toHaveBeenCalledTimes(1);
vi.advanceTimersByTime(300_000);
report(sender, 'page_load_failed', 'https://user:[email protected]/path?token=secret');
- expect(sender.send.mock.calls[1][1]).toEqual({
+ expect(warn.mock.calls[1][1]).toEqual({
stage: 'load', error_type: 'network', error_message: 'Browser main-frame navigation failed',
error_code: 'page_load_failed', suppressed_count: 100,
});
expect(JSON.stringify(warn.mock.calls)).not.toContain('secret');
- expect(JSON.stringify(sender.send.mock.calls)).not.toContain('example.com');
});
it('caps all windows and failure classes at twelve per rolling hour with bounded aggregation', () => {
vi.useFakeTimers();
vi.setSystemTime(0);
const report = createWebAssistDiagnostics();
- const send = vi.fn();
const kinds = ['page_load_failed', 'page_unresponsive', 'renderer_gone', 'view_unavailable'] as const;
for (let batch = 0; batch < 4; batch++) {
- for (const kind of kinds) report({ isDestroyed: () => false, send }, kind);
+ for (const kind of kinds) report({ isDestroyed: () => false }, kind);
vi.advanceTimersByTime(300_000);
}
- expect(send).toHaveBeenCalledTimes(12);
- for (let i = 0; i < 11000; i++) report({ isDestroyed: () => false, send }, 'renderer_gone');
- expect(send).toHaveBeenCalledTimes(12);
+ expect(warn).toHaveBeenCalledTimes(12);
+ for (let i = 0; i < 11000; i++) report({ isDestroyed: () => false }, 'renderer_gone');
vi.setSystemTime(3_600_000);
- report({ isDestroyed: () => false, send }, 'renderer_gone');
- expect(send).toHaveBeenCalledTimes(13);
- expect(send.mock.calls[12][1].suppressed_count).toBe(9999);
+ report({ isDestroyed: () => false }, 'renderer_gone');
+ expect(warn.mock.calls[12][1].suppressed_count).toBe(9999);
expect(warn).toHaveBeenCalledTimes(13);
});
- it('ignores invalid categories and closed owners, and never lets telemetry failure affect the browser', () => {
+ it('ignores invalid categories and closed owners, and never lets logging failure affect the browser', () => {
const report = createWebAssistDiagnostics();
- const send = vi.fn(() => { throw new Error('fixture send unavailable'); });
- report({ isDestroyed: () => true, send }, 'renderer_gone');
- report({ isDestroyed: () => false, send }, 'private-url' as any);
- expect(send).not.toHaveBeenCalled();
+ report({ isDestroyed: () => true }, 'renderer_gone');
+ report({ isDestroyed: () => false }, 'private-url' as any);
+ expect(warn).not.toHaveBeenCalled();
warn.mockImplementationOnce(() => { throw new Error('fixture logger unavailable'); });
- expect(() => report({ isDestroyed: () => false, send }, 'renderer_gone')).not.toThrow();
- expect(send).toHaveBeenCalledOnce();
+ expect(() => report({ isDestroyed: () => false }, 'renderer_gone')).not.toThrow();
});
});
diff --git a/test/main/model/core-agent/client-stall.test.ts b/test/main/model/core-agent/client-stall.test.ts
index 0aca1661..26d242c2 100644
--- a/test/main/model/core-agent/client-stall.test.ts
+++ b/test/main/model/core-agent/client-stall.test.ts
@@ -56,15 +56,6 @@ vi.mock('../../../../src/main/model/core-agent/runner', () => ({
providerId: 'mock-provider',
modelId: 'mock-model',
toolDefs: [],
- toolSurfaceTelemetry: () => ({
- mode: 'fixed',
- peakToolCount: 0,
- loadCallCount: 0,
- loadedGroupCount: 0,
- loadedSchemaChars: 0,
- loadedUnusedGroupCount: 0,
- webToolUsed: false,
- }),
skillDisplayNameById: new Map(),
agentDisplayNameById: new Map(),
}); },
@@ -135,7 +126,6 @@ type DrainedEvent = {
failureKind?: 'model' | 'config';
failureCode?: string;
failurePhase?: string;
- telemetry?: Record<string, unknown>;
event?: { stream?: string; data?: Record<string, unknown> };
};
@@ -359,7 +349,7 @@ describe('streamChatWithModel — phase-aware idle watchdog (Phase 1)', () => {
expect(events.filter((event) => event.type === 'error' || event.type === 'final')).toEqual([]);
expect(events.filter((event) => event.type === 'done')).toHaveLength(1);
// This metric describes the completed model invocation, not the downstream task.
- expect(events.find((event) => event.event?.stream === 'agent_run_result')?.event?.data)
+ expect(events.find((event) => event.event?.stream === 'agent_run_terminal')?.event?.data)
.toMatchObject({ result: 'success', terminal_status: 'completed' });
expect(h.logEntries.filter((entry) => entry.level === 'error' || entry.level === 'warn')).toEqual([]);
});
@@ -949,7 +939,7 @@ describe('streamChatWithModel — phase-aware idle watchdog (Phase 1)', () => {
setTimeout(() => controller.abort(), 80);
const { events } = await drain({ abortSignal: controller.signal, idleTimeout: 10 });
- const result = events.find((event) => event.event?.stream === 'agent_run_result')?.event?.data;
+ const result = events.find((event) => event.event?.stream === 'agent_run_terminal')?.event?.data;
expect(result).toMatchObject({
result: 'aborted',
failure_phase: 'tool',
diff --git a/test/main/model/core-agent/client.test.ts b/test/main/model/core-agent/client.test.ts
index 00068a63..ce801ad8 100644
--- a/test/main/model/core-agent/client.test.ts
+++ b/test/main/model/core-agent/client.test.ts
@@ -253,20 +253,6 @@ describe('core-agent client skill sandbox env', () => {
.toBe('unknown');
});
- it('uses the response provider and model for external-provider fallbacks', async () => {
- const client = await import('../../../../src/main/model/core-agent/client');
-
- expect(client.modelRunIdsForTelemetry(
- 'openrouter',
- 'openai/gpt-5.6-sol',
- 'anthropic',
- 'claude-opus-4-8',
- )).toEqual({
- providerId: 'anthropic',
- modelId: 'claude-opus-4-8',
- });
- });
-
it('summarizes model events without tool arguments, tool results, or final text', async () => {
const client = await import('../../../../src/main/model/core-agent/client');
const stats = client.createModelRunLogDiagnostics(1000);
@@ -562,7 +548,7 @@ describe('core-agent client skill sandbox env', () => {
expect(JSON.stringify(summary)).not.toContain('private provider body');
});
- it('counts context-gate interventions and compaction-span re-reads for run telemetry', async () => {
+ it('counts context-gate interventions and compaction-span re-reads for run diagnostics', async () => {
const client = await import('../../../../src/main/model/core-agent/client');
const stats = client.createModelRunLogDiagnostics(1000);
diff --git a/test/main/model/runner.test.ts b/test/main/model/runner.test.ts
index c7d1b59c..314ef035 100644
--- a/test/main/model/runner.test.ts
+++ b/test/main/model/runner.test.ts
@@ -1464,27 +1464,12 @@ describe('runner › scoped tool loading', () => {
{ state: {} },
))
.toMatchObject({ content: 'ok' });
- expect(lazy.toolSurfaceTelemetry(['list_connector_tools'])).toMatchObject({
- loadCallCount: 1,
- loadedGroupCount: 1,
- loadedUnusedGroupCount: 0,
- });
- expect(lazy.toolSurfaceTelemetry().loadedSchemaChars).toBeGreaterThan(0);
-
runtimeGrantedToolGroups.push('connectors');
expect(runner.activeTools().map((tool) => tool.name)).toEqual(expect.arrayContaining([
'list_connector_tools',
'call_connector_tool',
]));
- expect(built.toolSurfaceTelemetry()).toMatchObject({
- loadCallCount: 0,
- loadedGroupCount: 0,
- loadedSchemaChars: 0,
- loadedUnusedGroupCount: 0,
- });
- expect(built.toolSurfaceTelemetry().peakToolCount).toBeGreaterThan(built.toolDefs.length);
-
const selectedAtStart = await buildRunner({
sessionId: 'gmember-runtime-connector-selected-at-start',
userId: uid,
@@ -1745,13 +1730,6 @@ describe('runner › scoped tool loading', () => {
.not.toContain('Fallback only');
const initialPrompt = commander.resolvedSystemPrompt;
expect(commander.turnEphemeral).not.toContain('## Active tool groups');
- expect(commander.toolSurfaceTelemetry(['inner_browser']).webToolUsed).toBe(true);
- expect(commander.toolSurfaceTelemetry(['bash', 'web_search'])).toMatchObject({
- loadCallCount: 0,
- loadedGroupCount: 0,
- loadedSchemaChars: 0,
- webToolUsed: true,
- });
const runner = commander.runner as unknown as {
tools: Map<string, {
execute: (input: unknown, ctx: unknown) => Promise<{ content: string }>;
@@ -1770,12 +1748,6 @@ describe('runner › scoped tool loading', () => {
expect(loadedNames).toContain('skill_search');
expect(loadedNames).not.toContain('marketplace_search');
expect(loadedNames).not.toContain('app_health');
- expect(commander.toolSurfaceTelemetry(['tool_load', 'skill_search'])).toMatchObject({
- loadCallCount: 1,
- loadedGroupCount: 1,
- loadedUnusedGroupCount: 0,
- });
-
const appLoadResult = await runner.tools.get('tool_load')?.execute(
{ groups: ['management.app'] },
{ workingDir: tmpDir, state: {}, signal: undefined },
@@ -1790,11 +1762,6 @@ describe('runner › scoped tool loading', () => {
expect(appLoadedNames).toContain('skill_search');
expect(appLoadedNames).not.toContain('marketplace_search');
expect(commander.resolvedSystemPrompt).toBe(initialPrompt);
- expect(commander.toolSurfaceTelemetry(['tool_load', 'skill_search', 'app_health'])).toMatchObject({
- loadCallCount: 2,
- loadedGroupCount: 2,
- loadedUnusedGroupCount: 0,
- });
});
it('does not serialize a deferred tool schema until its group is loaded', async () => {
@@ -1834,12 +1801,9 @@ describe('runner › scoped tool loading', () => {
{ workingDir: tmpDir, state: {}, signal: undefined },
);
expect(schemaReads).toBe(0);
- const telemetry = built.toolSurfaceTelemetry();
- expect(telemetry.loadedSchemaChars).toBeGreaterThan(0);
- expect(schemaReads).toBe(1);
const activeNames = runner.getActiveToolDefinitions().map((tool) => tool.name);
+ expect(schemaReads).toBe(1);
expect(activeNames).toContain('marketplace_search');
- expect(telemetry.peakToolCount).toBe(activeNames.length);
});
it('builds process labels from lightweight Agent summaries without full enrichment', async () => {
@@ -2186,7 +2150,6 @@ describe('runner › scoped tool loading', () => {
.map((tool) => tool.name);
expect(activeRunnerTools).toContain('skill_manage');
expect([...names].sort()).toEqual([...activeRunnerTools].sort());
- expect(built.toolSurfaceTelemetry().peakToolCount).toBe(activeRunnerTools.length);
expect(built.resolvedSystemPrompt).toContain('## Loadable tool groups');
expect(built.turnEphemeral).not.toContain('## Active tool groups');
expect(built.resolvedSystemPrompt).not.toContain('**bash**');
@@ -2540,19 +2503,6 @@ describe('runner › scoped tool loading', () => {
name: 'marketplace_search',
});
expect(managementCalls).toEqual(['marketplace_search']);
- expect(built.toolSurfaceTelemetry(['tool_load', 'marketplace_search'])).toMatchObject({
- mode: 'scoped',
- loadCallCount: 1,
- loadedGroupCount: 1,
- loadedUnusedGroupCount: 0,
- webToolUsed: false,
- });
- expect(built.toolSurfaceTelemetry()).toMatchObject({
- loadedUnusedGroupCount: 1,
- webToolUsed: false,
- });
- expect(built.toolSurfaceTelemetry().loadedSchemaChars).toBeGreaterThan(0);
-
expect(runner.tools.has('auto_tasks_list')).toBe(false);
const automationLoad = await runner.tools.get('tool_load')?.execute(
{ groups: ['management.automation'] },
@@ -2582,11 +2532,6 @@ describe('runner › scoped tool loading', () => {
extraTools: managementTools,
});
expect(nextTurn.toolDefs.map((tool) => tool.name)).not.toContain('marketplace_search');
- expect(nextTurn.toolSurfaceTelemetry()).toMatchObject({
- loadCallCount: 0,
- loadedGroupCount: 0,
- loadedSchemaChars: 0,
- });
});
it('recomputes configured groups each turn without retaining removed Agent dependencies', async () => {
@@ -2964,7 +2909,6 @@ describe('runner › conversation-history scope exposure', () => {
.toEqual(['current', 'project', 'all']);
for (const built of [agent, nonProjectCommander, projectCommander]) {
expect(built.toolDefs.map(tool => tool.name)).toContain('chat_history');
- expect(built.toolSurfaceTelemetry([]).loadCallCount).toBe(0);
expect(built.resolvedSystemPrompt).not.toContain('`chat_history` —');
// Inspect the final host surface, not helper descriptions discarded by
// the consolidated tool factory. Semantic choices need live model cases.
@@ -3173,7 +3117,6 @@ describe('runner › conversation task board turn block (D8/P3)', () => {
expect(bound.resolvedSystemPrompt).not.toContain('## App creation');
if (appSystemPrompt !== undefined) expect(bound.resolvedSystemPrompt).toBe(appSystemPrompt);
appSystemPrompt = bound.resolvedSystemPrompt;
- expect(bound.toolSurfaceTelemetry()).toMatchObject({ loadCallCount: 0, loadedGroupCount: 0, loadedSchemaChars: 0 });
}
for (const sessionId of [`gmember-${cid}-agent-x`, `agent-${cid}`, `reflect-${cid}`]) {
const other = await buildRunner({ sessionId, userId: uid, cid, onArtifactCreated: artifactSink, toolList: [] });
diff --git a/test/renderer/bash-permission.test.ts b/test/renderer/bash-permission.test.ts
index e02ce547..452e5fc1 100644
--- a/test/renderer/bash-permission.test.ts
+++ b/test/renderer/bash-permission.test.ts
@@ -263,7 +263,6 @@ function loadHarness(
const pushHandlers = new Map<string, (info: any) => void>();
const dialogs: DialogView[] = [];
const invokeCalls: Array<{ channel: string; payload: any }> = [];
- const monitorEvent = vi.fn();
const warn = vi.fn();
const document = new FakeDocument((overlay) => {
dialogs.push(dialogView(overlay));
@@ -340,11 +339,9 @@ function loadHarness(
}
return text;
},
- Monitor: { event: monitorEvent },
window: {
location: { pathname: options.preview ? '/preview.html' : '/index.html' },
addEventListener() {},
- Monitor: { event: monitorEvent },
orkas: {
invoke: vi.fn(async (channel: string, payload: any) => {
invokeCalls.push({ channel, payload });
@@ -386,7 +383,6 @@ function loadHarness(
openDialogs: () => document.body.querySelectorAll('[role="dialog"]').length,
dialogs,
invokeCalls,
- monitorEvent,
warn,
};
}
@@ -448,7 +444,7 @@ describe('connector actions share local operation permissions', () => {
expect(h.openDialogs()).toBe(0);
});
- it('renders connector and operation markup as literal text and keeps it out of telemetry', async () => {
+ it('renders connector and operation markup as literal text', async () => {
const h = loadHarness('pending');
const markup = '<img src=x onerror=alert(1)>';
h.emitPush('connectors:action-confirm', { ...action, connector_id: 'custom-markup', display_name: markup, action_name: markup });
@@ -457,7 +453,6 @@ describe('connector actions share local operation permissions', () => {
expect([...h.document.body.descendants()].some((node) => node.tag === 'img')).toBe(false);
h.document.body.querySelector('[data-act="cancel"]')!.click();
await flush();
- expect(JSON.stringify(h.monitorEvent.mock.calls)).not.toContain(markup);
expect(h.invokeCalls).toContainEqual({
channel: 'connectors.action_confirm_response', payload: { request_id: action.request_id, approved: false },
});
@@ -502,9 +497,6 @@ describe('connector actions share local operation permissions', () => {
expect(h.openDialogs()).toBe(0);
expect(h.dialogs).toHaveLength(1);
expect(h.invokeCalls.every((call) => call.channel === 'permissions.getLocalExec')).toBe(true);
- const outcomes = h.monitorEvent.mock.calls.filter(([name]) => name === 'connector_action_confirmation_result');
- expect(outcomes).toHaveLength(2);
- for (const [, outcome] of outcomes) expect(outcome).toMatchObject({ decision: 'approved', result: 'success' });
});
it.each(['built-in', 'codex', 'claude'])('shows the local mode menu for %s connector calls', async (caller) => {
@@ -533,32 +525,6 @@ describe('connector actions share local operation permissions', () => {
{ channel: 'permissions.getLocalExec', payload: undefined },
{ channel: 'connectors.action_confirm_response', payload: { request_id: action.request_id, approved: true } },
]);
- expect(h.monitorEvent).toHaveBeenCalledWith('connector_action_confirmation_result', expect.objectContaining({
- result: 'success', decision: 'approved',
- }));
- expect(JSON.stringify(h.monitorEvent.mock.calls)).not.toMatch(/private-message|Work account|im\.\+messages-send/);
- });
-
- it('coarsens a custom MCP connector to `custom` and omits its tool name in confirmation telemetry', async () => {
- // Custom ids are derived from the user's display name and the tool name is
- // the server's own free text; neither belongs in analytics. Catalog
- // connectors keep both (negative control).
- const h = loadHarness('allow_once');
- h.emitPush('connectors:action-confirm', {
- ...action, request_id: 'custom-request', connector_id: 'custom-my-private-server', tool_name: 'run_private_query',
- });
- await flush();
- const custom = h.monitorEvent.mock.calls.find((call: any[]) => call[0] === 'connector_action_confirmation_result');
- expect(custom?.[1]).toMatchObject({ connector_id: 'custom', decision: 'approved' });
- expect(custom?.[1]).not.toHaveProperty('tool_name');
- expect(JSON.stringify(h.monitorEvent.mock.calls)).not.toMatch(/my-private-server|run_private_query/);
-
- h.monitorEvent.mockClear();
- h.emitPush('connectors:action-confirm', { ...action, request_id: 'catalog-request' });
- await flush();
- expect(h.monitorEvent).toHaveBeenCalledWith('connector_action_confirmation_result', expect.objectContaining({
- connector_id: 'feishu', tool_name: 'execute_high_impact',
- }));
});
it('persists Trusted before approval and does not prompt again for an already queued connector', async () => {
@@ -636,7 +602,7 @@ describe('connector actions share local operation permissions', () => {
expect(h.invokeCalls.some((call) => call.channel === 'connectors.action_confirm_response')).toBe(false);
});
- it.each(['stale', 'rejected', 'unavailable'])('reports a %s approval response without success or private errors', async (failure) => {
+ it.each(['stale', 'rejected', 'unavailable'])('handles a %s approval response without exposing private errors', async (failure) => {
const h = loadHarness('allow_once', async (channel) => {
if (channel === 'permissions.getLocalExec') return { ok: true, mode: 'all_files_approval' };
if (failure === 'unavailable') throw new Error('/private/approval-response');
@@ -644,10 +610,7 @@ describe('connector actions share local operation permissions', () => {
});
h.emitPush('connectors:action-confirm', action);
await flush();
- expect(h.monitorEvent).toHaveBeenCalledWith('connector_action_confirmation_result', expect.objectContaining({
- result: failure === 'stale' ? 'cancelled' : 'failure',
- }));
- expect(JSON.stringify([h.monitorEvent.mock.calls, h.warn.mock.calls])).not.toContain('/private/approval-response');
+ expect(JSON.stringify(h.warn.mock.calls)).not.toContain('/private/approval-response');
});
it('denies a broken dialog and still presents the next queued action', async () => {
@@ -661,11 +624,8 @@ describe('connector actions share local operation permissions', () => {
{ channel: 'connectors.action_confirm_response', payload: { request_id: action.request_id, approved: false } },
{ channel: 'connectors.action_confirm_response', payload: { request_id: 'after-ui-recovery', approved: true } },
]);
- expect(h.monitorEvent).toHaveBeenCalledWith('connector_action_confirmation_result', expect.objectContaining({
- result: 'failure', decision: 'denied',
- }));
expect(h.dialogs).toHaveLength(1);
- expect(JSON.stringify([h.monitorEvent.mock.calls, h.warn.mock.calls])).not.toContain('/private/dialog-failure');
+ expect(JSON.stringify(h.warn.mock.calls)).not.toContain('/private/dialog-failure');
});
});
@@ -773,12 +733,6 @@ describe('renderer bash permission prompt', () => {
permission_policy: 'ask',
},
}]);
- expect(h.monitorEvent).toHaveBeenCalledWith('connector_bridge_permission_result', {
- result: 'success',
- decision: 'allow_run',
- effective_decision: 'allow_run',
- duration_ms: expect.any(Number),
- });
});
it('returns a changed CLI full-access level through the native approval response', async () => {
@@ -934,13 +888,6 @@ describe('renderer bash permission prompt', () => {
{ error_type: 'Error' },
);
expect(JSON.stringify(h.warn.mock.calls)).not.toContain('/private/workspace');
- expect(h.monitorEvent).toHaveBeenCalledWith('connector_bridge_permission_result', expect.objectContaining({
- result: 'failure',
- decision: 'deny',
- effective_decision: 'deny',
- error_code: 'response_failed',
- error_type: 'ipc',
- }));
});
it('offers task-level approval when main marks the risk category eligible', async () => {
@@ -984,51 +931,6 @@ describe('renderer bash permission prompt', () => {
{ channel: 'permissions.setLocalExecMode', payload: { mode: 'all_files_auto' } },
{ channel: 'bash.permission_response', payload: { request_id: 'req-1', decision: 'allow_once' } },
]);
- expect(h.monitorEvent).toHaveBeenCalledWith('bash_risk_prompt_result', expect.objectContaining({
- result: 'success',
- decision: 'allow_once',
- effective_decision: 'allow_once',
- mode: 'all_files_auto',
- mode_changed: true,
- categories: 'network_egress',
- duration_ms: expect.any(Number),
- }));
- expect(h.monitorEvent).toHaveBeenCalledWith('bash_risk_prompt_requested', {
- categories: 'network_egress',
- visibility_state: 'unknown',
- });
- expect(h.monitorEvent).toHaveBeenCalledWith('bash_risk_prompt_presented', expect.objectContaining({
- categories: 'network_egress',
- mode: 'all_files_approval',
- visibility_state: 'unknown',
- queue_wait_ms: expect.any(Number),
- }));
- expect(h.monitorEvent.mock.calls
- .map(([name]) => name)
- .filter((name) => name.startsWith('bash_risk_prompt_'))).toEqual([
- 'bash_risk_prompt_requested',
- 'bash_risk_prompt_presented',
- 'bash_risk_prompt_result',
- ]);
- });
-
- it.each([
- ['a focused window', { state: 'visible', focused: true } as const, 'visible_focused'],
- ['an unfocused window', { state: 'visible', focused: false } as const, 'visible_unfocused'],
- ['a hidden window', { state: 'hidden', focused: true } as const, 'hidden'],
- ])('records bounded visibility when presenting in %s', async (_label, visibility, expectedState) => {
- const h = loadHarness('deny', undefined, { visibility });
-
- h.pushHandler({ request_id: `req-${expectedState}`, reasons: ['destructive'] });
- await flush();
-
- expect(h.monitorEvent).toHaveBeenCalledWith('bash_risk_prompt_requested', expect.objectContaining({
- visibility_state: expectedState,
- }));
- expect(h.monitorEvent).toHaveBeenCalledWith('bash_risk_prompt_presented', expect.objectContaining({
- visibility_state: expectedState,
- }));
- expect(h.monitorEvent.mock.calls.filter(([name]) => name === 'bash_risk_prompt_result')).toHaveLength(1);
});
// A user who deliberately turned prompts off and then sees one has to be
@@ -1093,35 +995,6 @@ describe('renderer bash permission prompt', () => {
expect(h.dialogs[0].message).not.toContain('cannot be undone');
});
- it('keeps private prompt fields and unknown categories out of telemetry', async () => {
- const privatePath = '/private/workspace/customer-secret.txt';
- const h = loadHarness('deny');
-
- h.pushHandler({
- request_id: 'req-private-identifier',
- agent_id: 'private-agent-identifier',
- agent_name: 'Private Agent Name',
- command: `rm ${privatePath}`,
- operation: 'delete_file',
- subject: privatePath,
- reasons: ['destructive', 'unbounded-private-category', 'destructive'],
- cid: 'private-conversation-identifier',
- });
- await flush();
-
- const serialized = JSON.stringify(h.monitorEvent.mock.calls);
- expect(serialized).not.toContain(privatePath);
- expect(serialized).not.toContain('private-agent-identifier');
- expect(serialized).not.toContain('Private Agent Name');
- expect(serialized).not.toContain('private-conversation-identifier');
- expect(serialized).not.toContain('req-private-identifier');
- expect(serialized).not.toContain('unbounded-private-category');
- expect(h.monitorEvent).toHaveBeenCalledWith('bash_risk_prompt_requested', {
- categories: 'destructive',
- visibility_state: 'unknown',
- });
- });
-
it.each([
'network_egress',
'destructive',
@@ -1144,13 +1017,6 @@ describe('renderer bash permission prompt', () => {
{ channel: 'permissions.getLocalExec', payload: undefined },
{ channel: 'bash.permission_response', payload: { request_id: `req-${reason}`, decision: 'allow_run' } },
]);
- expect(h.monitorEvent).toHaveBeenCalledWith('bash_risk_prompt_result', expect.objectContaining({
- result: 'success',
- decision: 'allow_run',
- effective_decision: 'allow_run',
- mode: 'all_files_approval',
- mode_changed: false,
- }));
});
// The rendered dialog is the approval boundary: a strict category gets no
@@ -1276,16 +1142,9 @@ describe('renderer bash permission prompt', () => {
{ channel: 'permissions.setLocalExecMode', payload: { mode: 'all_files_auto' } },
{ channel: 'bash.permission_response', payload: { request_id: 'req-mode-failed', decision: 'deny' } },
]);
- expect(h.monitorEvent).toHaveBeenCalledWith('bash_risk_prompt_result', expect.objectContaining({
- result: 'success',
- decision: 'allow_once',
- effective_decision: 'deny',
- mode: 'all_files_approval',
- mode_changed: false,
- }));
});
- it('marks a verdict cancelled when main reports that the request is stale', async () => {
+ it('sends the selected response even when main reports that the request is stale', async () => {
const h = loadHarness('allow_once', async (channel) => {
if (channel === 'permissions.getLocalExec') return { ok: true, mode: 'all_files_approval' };
if (channel === 'bash.permission_response') return { ok: true, handled: false };
@@ -1300,16 +1159,13 @@ describe('renderer bash permission prompt', () => {
});
await flush();
- expect(h.monitorEvent).toHaveBeenCalledWith('bash_risk_prompt_result', expect.objectContaining({
- result: 'cancelled',
- decision: 'allow_once',
- effective_decision: 'allow_once',
- error_type: 'state',
- error_code: 'stale_request',
- }));
+ expect(h.invokeCalls).toContainEqual({
+ channel: 'bash.permission_response',
+ payload: { request_id: 'req-stale', decision: 'allow_once' },
+ });
});
- it('keeps a resolved IPC rejection in the terminal failure denominator', async () => {
+ it('contains a resolved IPC rejection without exposing its private error', async () => {
const h = loadHarness('deny', async (channel) => {
if (channel === 'permissions.getLocalExec') return { ok: true, mode: 'all_files_approval' };
if (channel === 'bash.permission_response') return { ok: false, error: '/private/request' };
@@ -1324,13 +1180,11 @@ describe('renderer bash permission prompt', () => {
});
await flush();
- expect(h.monitorEvent).toHaveBeenCalledWith('bash_risk_prompt_result', expect.objectContaining({
- result: 'failure',
- decision: 'deny',
- error_type: 'ipc',
- error_code: 'response_failed',
- }));
- expect(JSON.stringify(h.monitorEvent.mock.calls)).not.toContain('/private/request');
+ expect(h.invokeCalls).toContainEqual({
+ channel: 'bash.permission_response',
+ payload: { request_id: 'req-rejected', decision: 'deny' },
+ });
+ expect(JSON.stringify(h.warn.mock.calls)).not.toContain('/private/request');
});
it('closes a cancelled prompt without sending a stale renderer response', async () => {
@@ -1350,19 +1204,9 @@ describe('renderer bash permission prompt', () => {
expect(h.invokeCalls).toEqual([
{ channel: 'permissions.getLocalExec', payload: undefined },
]);
- expect(h.monitorEvent).toHaveBeenCalledWith('bash_risk_prompt_requested', expect.any(Object));
- expect(h.monitorEvent).toHaveBeenCalledWith('bash_risk_prompt_presented', expect.any(Object));
- expect(h.monitorEvent).toHaveBeenCalledWith('bash_risk_prompt_result', expect.objectContaining({
- result: 'cancelled',
- decision: 'none',
- effective_decision: 'deny',
- error_type: 'state',
- error_code: 'request_cancelled',
- }));
- expect(h.monitorEvent.mock.calls.filter(([name]) => name === 'bash_risk_prompt_result')).toHaveLength(1);
});
- it('records cancellation during mode lookup without claiming presentation', async () => {
+ it('cancels during mode lookup without presenting or responding', async () => {
let resolveMode!: (value: { ok: boolean; mode: string }) => void;
const modeLookup = new Promise<{ ok: boolean; mode: string }>((resolve) => { resolveMode = resolve; });
const h = loadHarness('deny', async (channel) => {
@@ -1380,16 +1224,9 @@ describe('renderer bash permission prompt', () => {
expect(h.invokeCalls).toEqual([
{ channel: 'permissions.getLocalExec', payload: undefined },
]);
- expect(h.monitorEvent.mock.calls.filter(([name]) => name === 'bash_risk_prompt_requested')).toHaveLength(1);
- expect(h.monitorEvent.mock.calls.filter(([name]) => name === 'bash_risk_prompt_presented')).toHaveLength(0);
- expect(h.monitorEvent).toHaveBeenCalledWith('bash_risk_prompt_result', expect.objectContaining({
- result: 'cancelled',
- error_code: 'request_cancelled',
- }));
- expect(h.monitorEvent.mock.calls.filter(([name]) => name === 'bash_risk_prompt_result')).toHaveLength(1);
});
- it('records a queued cancellation without claiming that its dialog was presented', async () => {
+ it('drops a queued cancellation without presenting or responding', async () => {
const h = loadHarness('pending');
h.pushHandler({ request_id: 'req-open', reasons: ['destructive'] });
@@ -1398,14 +1235,10 @@ describe('renderer bash permission prompt', () => {
h.cancelHandler({ request_ids: ['req-queued'] });
await flush();
- const presented = h.monitorEvent.mock.calls.filter(([name]) => name === 'bash_risk_prompt_presented');
- expect(presented).toHaveLength(1);
- expect(h.monitorEvent).toHaveBeenCalledWith('bash_risk_prompt_result', expect.objectContaining({
- result: 'cancelled',
- categories: 'network_egress',
- error_code: 'request_cancelled',
- }));
- expect(h.monitorEvent.mock.calls.filter(([name]) => name === 'bash_risk_prompt_result')).toHaveLength(1);
+ expect(h.dialogs).toHaveLength(1);
+ expect(h.invokeCalls).toEqual([
+ { channel: 'permissions.getLocalExec', payload: undefined },
+ ]);
});
it('declines on Escape but leaves an IME composition alone', async () => {
@@ -1469,7 +1302,7 @@ describe('web assist page actions reuse the same permission dialog', () => {
});
});
- it('answers once without a grant and reports the verdict without page content', async () => {
+ it('answers once without a grant', async () => {
const h = loadHarness('allow_once');
h.emitPush('web-assist:action-confirm', handback);
await flush();
@@ -1477,11 +1310,6 @@ describe('web assist page actions reuse the same permission dialog', () => {
channel: 'webAssist.actionConfirmResponse',
payload: { request_id: handback.request_id, decision: 'once' },
});
- expect(h.monitorEvent).toHaveBeenCalledWith('web_assist_action_confirmation_result', expect.objectContaining({
- result: 'success', decision: 'approved', reason: 'high_impact_action', control_kind: 'button',
- }));
- // Origin, title and control label are user content and stay out of analytics.
- expect(JSON.stringify(h.monitorEvent.mock.calls)).not.toMatch(/chatgpt\.com|Send prompt|ChatGPT/);
});
it('declines with a deny decision the host can distinguish from an approval', async () => {
@@ -1492,9 +1320,6 @@ describe('web assist page actions reuse the same permission dialog', () => {
channel: 'webAssist.actionConfirmResponse',
payload: { request_id: handback.request_id, decision: 'deny' },
});
- expect(h.monitorEvent).toHaveBeenCalledWith('web_assist_action_confirmation_result', expect.objectContaining({
- decision: 'denied',
- }));
});
it('drops a withdrawn request without answering it', async () => {
diff --git a/test/renderer/connectors-degraded-card.test.ts b/test/renderer/connectors-degraded-card.test.ts
index 841879ee..090dc156 100644
--- a/test/renderer/connectors-degraded-card.test.ts
+++ b/test/renderer/connectors-degraded-card.test.ts
@@ -2037,7 +2037,7 @@ describe('explicit connector failure codes', () => {
[{ code: 'invalid_grant', error: 'Previous operation canceled; grant invalid' }, true],
])('shows hard failures without mistaking incidental cancel text for user cancellation: %j', (error, shouldAlert) => {
const context = loadConnectorsRenderer();
- context._handleConnectFailure({}, 0, error);
+ context._handleConnectFailure(error);
expect(context.__alerts.length).toBe(shouldAlert ? 1 : 0);
if (error.code === 'storage_unavailable') expect(context.__alerts[0]).toBe(context.t('connectors.errors.storage_unavailable'));
});
diff --git a/test/renderer/conversation-library-attach.test.ts b/test/renderer/conversation-library-attach.test.ts
index deb6c0fa..709e2473 100644
--- a/test/renderer/conversation-library-attach.test.ts
+++ b/test/renderer/conversation-library-attach.test.ts
@@ -16,7 +16,7 @@ function harness(invoke: ReturnType<typeof vi.fn>) {
const host = { innerHTML: '', style: { display: '' }, querySelectorAll: () => [] };
const apiFetch = vi.fn(async () => ({ json: async () => ({ ok: true }) }));
const uiAlert = vi.fn();
- const warn = vi.fn(), event = vi.fn(), error = vi.fn(), focus = vi.fn(), consume = vi.fn();
+ const warn = vi.fn(), conversationWarn = vi.fn(), focus = vi.fn(), consume = vi.fn();
const context: any = vm.createContext({
window: { orkas: { invoke } },
document: { getElementById: () => host },
@@ -27,10 +27,9 @@ function harness(invoke: ReturnType<typeof vi.fn>) {
_chatAttachmentRevisions: new Map(),
_chatAttachHostIdFor: () => 'chips',
_chatFileIconHtml: () => '',
- _convLog: { warn },
+ _convLog: { warn: conversationWarn }, _agentsLog: { warn },
_targetFromPickerAnchor: () => 'conversation', _resolveActiveProjectId: () => '',
_libraryPickerDraftCidFor: () => 'main_chat', _libraryPickerInputIdForTarget: () => 'input',
- _agentsTrackEvent: event, _agentsTrackError: error,
_consumeAtKeyChar: consume, _focusInput: focus,
escapeHtml: (value: string) => value,
t: (key: string, data?: { reason?: string }) => data?.reason || key,
@@ -63,7 +62,7 @@ function harness(invoke: ReturnType<typeof vi.fn>) {
beginSend: () => context._chatAttachTryBeginSend('main_chat'),
apiFetch,
uiAlert,
- warn, event, error, focus, consume,
+ warn, focus, consume,
select: (scope: string) => context._triggerLibraryFile({
libraryRel: 'PRIVATE_FILE_PATH', libraryScope: scope, projectId: scope === 'project' ? 'project-test' : '',
}, 'picker'),
@@ -140,7 +139,7 @@ describe('Library attachment draft lifecycle', () => {
['global', 'attachment_import', 'disk_full', 'attachment_import', 'disk_full'],
['project', 'attachment_import', 'operation_failed', 'attachment_import', 'operation_failed'],
['global', 'PRIVATE_STAGE', 'PRIVATE_KIND', 'ipc_request', 'operation_failed'],
- ])('preserves %s/%s/%s through IPC, local logging and picker events before recovery', async (scope, stage, kind, expectedStage, expectedKind) => {
+ ])('preserves %s/%s/%s through IPC and local logging before recovery', async (scope, stage, kind, expectedStage, expectedKind) => {
const invoke = vi.fn().mockResolvedValueOnce({
ok: false, error: 'PRIVATE_ERROR_TEXT', failure_stage: stage, failure_kind: kind,
}).mockResolvedValue(imported);
@@ -153,23 +152,16 @@ describe('Library attachment draft lifecycle', () => {
expect(fixture.consume).not.toHaveBeenCalled();
expect(fixture.uiAlert).toHaveBeenCalledExactlyOnceWith('PRIVATE_ERROR_TEXT');
const diagnosis = { failure_stage: expectedStage, failure_kind: expectedKind };
- expect(fixture.warn).toHaveBeenCalledExactlyOnceWith('library attachment failed', diagnosis);
- expect(fixture.event).toHaveBeenCalledExactlyOnceWith('chat_library_attach_result', expect.objectContaining({
- ...diagnosis, result: 'failure', scope, telemetry_version: 3,
- }));
- expect(fixture.error).toHaveBeenCalledExactlyOnceWith('chat_library_attach', expect.objectContaining({
- ...diagnosis, error_type: 'operation', error_message: 'library_attach_failed', telemetry_version: 3,
- }));
- expect(JSON.stringify([fixture.warn.mock.calls, fixture.event.mock.calls, fixture.error.mock.calls])).not.toContain('PRIVATE_');
+ expect(fixture.warn).toHaveBeenCalledExactlyOnceWith('library attachment failed', {
+ target: 'conversation', scope, ...diagnosis,
+ });
+ expect(JSON.stringify(fixture.warn.mock.calls)).not.toContain('PRIVATE_');
const release = fixture.beginSend();
expect(release).toBeTypeOf('function');
release();
await fixture.select(scope);
expect(fixture.names()).toEqual(['note.md']);
expect(fixture.readyChips()).toBe(1);
- expect(fixture.event).toHaveBeenLastCalledWith('chat_library_attach_result', expect.objectContaining({ result: 'success', scope }));
- expect(fixture.event).toHaveBeenCalledTimes(2);
- expect(fixture.error).toHaveBeenCalledTimes(1);
expect(fixture.warn).toHaveBeenCalledTimes(1);
expect(fixture.focus).toHaveBeenCalledOnce();
expect(fixture.consume).toHaveBeenCalledOnce();
diff --git a/test/renderer/delete-file-confirm.test.ts b/test/renderer/delete-file-confirm.test.ts
index f9071d39..1d85626e 100644
--- a/test/renderer/delete-file-confirm.test.ts
+++ b/test/renderer/delete-file-confirm.test.ts
@@ -191,7 +191,6 @@ function loadHarness(
elements.set(send.id, send);
const invokeCalls: Array<{ channel: string; payload: any }> = [];
- const monitor = { event: vi.fn(), error: vi.fn() };
const warn = vi.fn();
let sendClicks = 0;
send.click = async () => { sendClicks += 1; };
@@ -265,7 +264,6 @@ function loadHarness(
createElement: (tagName: string) => makeEl(tagName),
},
window: {
- Monitor: true,
orkas: {
invoke: async (channel: string, payload: any) => {
invokeCalls.push({ channel, payload });
@@ -273,7 +271,6 @@ function loadHarness(
},
},
},
- Monitor: monitor,
};
context.window.window = context.window;
vm.createContext(context);
@@ -288,7 +285,6 @@ function loadHarness(
input,
send,
invokeCalls,
- monitor,
warn,
flushTimers,
get sendClicks() { return sendClicks; },
@@ -326,18 +322,6 @@ describe('delete-file-confirm batching', () => {
expect(h.input.value).toBe('Confirmed, please continue.');
expect(card.classList.contains('is-confirmed')).toBe(true);
expect(card.querySelector('.delete-confirm-result')?.textContent).toBe('Deletion confirmed for 2 files');
- expect(h.monitor.event).toHaveBeenCalledOnce();
- expect(h.monitor.event).toHaveBeenCalledWith(
- 'delete_file_confirmation_result',
- expect.objectContaining({
- result: 'success',
- decision: 'allow',
- file_count: 2,
- failed_count: 0,
- }),
- );
- expect(JSON.stringify(h.monitor.event.mock.calls)).not.toContain('tok-a');
- expect(JSON.stringify(h.monitor.event.mock.calls)).not.toContain('a.txt');
});
it('cancels every token in the grouped card without auto-continuing', async () => {
@@ -373,7 +357,7 @@ describe('delete-file-confirm batching', () => {
expect(pathTexts(h.history.children[1])).toEqual(['new.txt']);
});
- it('aggregates response failures without leaking confirmation ids or paths', async () => {
+ it('contains response failures without leaking confirmation ids or paths', async () => {
const h = loadHarness(async (channel, payload) => {
if (channel === 'delete_file.respond' && payload.confirm_id === 'private-token-b') {
return { ok: false, error: '/Users/test/private/secret.txt' };
@@ -389,24 +373,8 @@ describe('delete-file-confirm batching', () => {
});
await h.history.children[0].querySelector('[data-delete-act="cancel"]')!.click();
- expect(h.monitor.event).toHaveBeenCalledWith(
- 'delete_file_confirmation_result',
- expect.objectContaining({
- result: 'failure',
- decision: 'deny',
- file_count: 2,
- failed_count: 1,
- error_type: 'ipc',
- error_code: 'response_failed',
- }),
- );
- expect(h.monitor.error).not.toHaveBeenCalled();
- const diagnostics = JSON.stringify([
- h.monitor.event.mock.calls,
- h.monitor.error.mock.calls,
- h.warn.mock.calls,
- ]);
- expect(diagnostics).not.toContain('/Users/alice');
+ const diagnostics = JSON.stringify(h.warn.mock.calls);
+ expect(diagnostics).not.toContain('/Users/test/private');
expect(diagnostics).not.toContain('private-token');
expect(diagnostics).not.toContain('private-cid');
});
diff --git a/test/renderer/library-transfer.test.ts b/test/renderer/library-transfer.test.ts
index 5dd4cf33..9910281b 100644
--- a/test/renderer/library-transfer.test.ts
+++ b/test/renderer/library-transfer.test.ts
@@ -8,7 +8,7 @@ const transfer = require('../../src/renderer/modules/library-transfer.js') as {
_folderRows: (nodes: unknown[]) => Array<{ path: string; name: string; depth: number }>;
_projectsFromResponse: (response: unknown) => unknown[];
_canSubmitTransfer: (state: { loading: boolean; destinationReady: boolean }) => boolean;
- _transferFailureTelemetry: (error: unknown) => Record<string, unknown>;
+ _transferFailureDetails: (error: unknown) => Record<string, unknown>;
_createLatestFolderLoader: (
loadTree: (ref: { scope: string; projectId?: string }) => Promise<unknown[]>,
handlers: {
@@ -133,8 +133,8 @@ describe('shared Library transfer dialog', () => {
expect(events.at(-1)).toBe('finish:latest');
});
- it('does not put raw IPC failures or local paths into telemetry', () => {
- const payload = transfer._transferFailureTelemetry(
+ it('does not put raw IPC failures or local paths into diagnostic details', () => {
+ const payload = transfer._transferFailureDetails(
new Error('copy failed at /Users/test/customer-plan.md'),
);
@@ -144,19 +144,19 @@ describe('shared Library transfer dialog', () => {
});
it('keeps stable transfer failures queryable without raw backend details', () => {
- expect(transfer._transferFailureTelemetry({ error: 'target_exists' })).toEqual({
+ expect(transfer._transferFailureDetails({ error: 'target_exists' })).toEqual({
error_code: 'target_exists',
error_type: 'conflict',
});
- expect(transfer._transferFailureTelemetry({ error: 'invalid_batch' })).toEqual({
+ expect(transfer._transferFailureDetails({ error: 'invalid_batch' })).toEqual({
error_code: 'invalid_batch',
error_type: 'validation',
});
- expect(transfer._transferFailureTelemetry('source_delete_failed')).toEqual({
+ expect(transfer._transferFailureDetails('source_delete_failed')).toEqual({
error_code: 'source_delete_failed',
error_type: 'operation',
});
- expect(transfer._transferFailureTelemetry({
+ expect(transfer._transferFailureDetails({
code: 'E_IPC_REQUEST',
error: 'private backend detail',
})).toEqual({
diff --git a/test/renderer/local-agents-status.test.ts b/test/renderer/local-agents-status.test.ts
index a6245798..482324c7 100644
--- a/test/renderer/local-agents-status.test.ts
+++ b/test/renderer/local-agents-status.test.ts
@@ -35,11 +35,7 @@ function loadStatusHint() {
function loadExternalSelectorHarness() {
const source = fs.readFileSync(path.join(rendererRoot, 'modules/local-agents.js'), 'utf8');
let now = 1000;
- const monitorCalls: any[] = [];
const availabilityStates: boolean[] = [];
- const monitor = {
- event: (name: string, payload: unknown) => monitorCalls.push(['event', name, payload]),
- };
const pendingInvokes: Array<{
channel: string;
payload: unknown;
@@ -87,7 +83,6 @@ function loadExternalSelectorHarness() {
},
};
const windowObject: Record<string, any> = {
- Monitor: monitor,
setExternalAgentCreateAvailability: (available: boolean) => availabilityStates.push(available),
orkas: {
invoke: (channel: string, payload: unknown) => {
@@ -100,7 +95,6 @@ function loadExternalSelectorHarness() {
};
const context = vm.createContext({
window: windowObject,
- Monitor: monitor,
document: {
getElementById: (id: string) => {
if (id === 'agent-modal-ext-cli-select') return mount;
@@ -168,7 +162,6 @@ function loadExternalSelectorHarness() {
trigger,
classes,
attributes,
- monitorCalls,
availabilityStates,
};
}
@@ -352,25 +345,9 @@ describe('external-agent unavailable status copy', () => {
]);
expect(selected).toEqual(['codex']);
expect(harness.availability()).toBe('available');
- expect(harness.monitorCalls).toEqual([
- ['event', 'external_cli_detect_result', {
- result: 'success',
- available_count: 1,
- not_found_count: 0,
- version_too_old_count: 0,
- version_timeout_count: 0,
- version_unknown_count: 0,
- available_types: 'codex',
- not_found_types: '',
- version_too_old_types: '',
- version_timeout_types: '',
- version_unknown_types: '',
- duration_ms: 0,
- }],
- ]);
});
- it('reports unavailable CLI reasons as one aggregate detection result', async () => {
+ it('renders unavailable CLI reasons after discovery', async () => {
const harness = loadExternalSelectorHarness();
const pending = harness.mount();
harness.advanceTime(40);
@@ -385,22 +362,6 @@ describe('external-agent unavailable status copy', () => {
});
await pending;
- expect(harness.monitorCalls).toEqual([
- ['event', 'external_cli_detect_result', {
- result: 'success',
- available_count: 0,
- not_found_count: 2,
- version_too_old_count: 1,
- version_timeout_count: 1,
- version_unknown_count: 1,
- available_types: '',
- not_found_types: 'claude,codex',
- version_too_old_types: 'openclaw',
- version_timeout_types: 'hermes',
- version_unknown_types: 'opencode',
- duration_ms: 40,
- }],
- ]);
expect(harness.selectState.placeholder).toBe('agent_modal.ext_cli_unavailable');
expect(harness.selectState.value).toBe('');
expect(harness.selectState.options).toEqual([
@@ -512,12 +473,9 @@ describe('external-agent unavailable status copy', () => {
'claude',
]);
expect(harness.selectState.value).toBe('claude');
- expect(harness.monitorCalls.filter(
- ([kind, name]) => kind === 'event' && name === 'external_cli_detect_result',
- )).toHaveLength(1);
});
- it('keeps one telemetry owner when another mount starts during version validation', async () => {
+ it('coalesces another mount during version validation', async () => {
const harness = loadExternalSelectorHarness();
const first = harness.mount();
harness.resolveList({
@@ -537,9 +495,7 @@ describe('external-agent unavailable status copy', () => {
});
await Promise.all([first, second]);
- expect(harness.monitorCalls.filter(
- ([kind, name]) => kind === 'event' && name === 'external_cli_detect_result',
- )).toHaveLength(1);
+ expect(harness.getInvokeCount()).toBe(3);
});
it('shows cached options immediately, resets to the first CLI, and marks the title updating', async () => {
@@ -640,23 +596,6 @@ describe('external-agent unavailable status copy', () => {
await flushPromises();
harness.rejectList(new Error('IPC unavailable'));
await first;
- expect(harness.monitorCalls).toEqual([
- ['event', 'external_cli_detect_result', {
- result: 'failure',
- available_count: 0,
- not_found_count: 0,
- version_too_old_count: 0,
- version_timeout_count: 0,
- version_unknown_count: 0,
- available_types: '',
- not_found_types: '',
- version_too_old_types: '',
- version_timeout_types: '',
- version_unknown_types: '',
- duration_ms: 0,
- error_code: 'invoke_failed',
- }],
- ]);
const retry = harness.mount();
diff --git a/test/renderer/sidebar-sections.test.ts b/test/renderer/sidebar-sections.test.ts
index a052f83f..a1de0409 100644
--- a/test/renderer/sidebar-sections.test.ts
+++ b/test/renderer/sidebar-sections.test.ts
@@ -4,7 +4,6 @@ const {
STORAGE_KEY,
readCollapsedState,
initSidebarSections,
- trackSidebarSectionToggle,
} = require('../../src/renderer/modules/sidebar-sections.js');
function createClassList() {
@@ -168,19 +167,6 @@ describe('sidebar top-level section collapse', () => {
expect(harness.tasksBody.hidden).toBe(false);
});
- it('tracks the resulting open or close state with a bounded section name', () => {
- const calls: unknown[][] = [];
- const monitor = { click: (...args: unknown[]) => calls.push(args) };
-
- trackSidebarSectionToggle({ name: 'projects', collapsed: true }, monitor);
- trackSidebarSectionToggle({ name: 'tasks', collapsed: false }, monitor);
-
- expect(calls).toEqual([
- ['sidebar_section_toggle', { section: 'projects', control_state: 'close' }],
- ['sidebar_section_toggle', { section: 'tasks', control_state: 'open' }],
- ]);
- });
-
it('treats corrupt or non-boolean stored values as expanded', () => {
const storage = { getItem: () => '{bad json', setItem() {} };
expect(readCollapsedState(storage)).toEqual({});
diff --git a/test/renderer/web-assist-wiring.test.ts b/test/renderer/web-assist-wiring.test.ts
index 34e7e3d5..3859f006 100644
--- a/test/renderer/web-assist-wiring.test.ts
+++ b/test/renderer/web-assist-wiring.test.ts
@@ -610,11 +610,10 @@ describe('Web Assist renderer wiring', () => {
const handlers = new Map<string, (state: unknown) => void>();
const showFromMain = vi.fn();
const renderState = vi.fn();
- const error = vi.fn();
const start = webAssistSource.indexOf(" window.orkas.onPushEvent('web-assist:state'");
const end = webAssistSource.indexOf(' window.WebAssist =', start);
vm.runInNewContext(webAssistSource.slice(start, end), {
- window: { Monitor: { error }, orkas: { onPushEvent: (name: string, handler: (state: unknown) => void) => handlers.set(name, handler) } },
+ window: { orkas: { onPushEvent: (name: string, handler: (state: unknown) => void) => handlers.set(name, handler) } },
showFromMain, renderState, rememberMainActiveTab() {},
});
const state = { conversation_id: 'c1', loading: true };
@@ -626,12 +625,7 @@ describe('Web Assist renderer wiring', () => {
expect(showFromMain).toHaveBeenCalledWith(activity);
handlers.get('web-assist:show')!(state);
expect(showFromMain).toHaveBeenCalledTimes(2);
- const failure = { error_code: 'renderer_gone', suppressed_count: 2 };
- handlers.get('web-assist:failure')!(failure);
- expect(error).toHaveBeenCalledExactlyOnceWith('browser', failure);
- expect(showFromMain).toHaveBeenCalledTimes(2);
- error.mockImplementationOnce(() => { throw new Error('fixture monitor unavailable'); });
- expect(() => handlers.get('web-assist:failure')!(failure)).not.toThrow();
+ expect(handlers.has('web-assist:failure')).toBe(false);
});
it.each(['close', 'switch', 'decode-failure', 'ready'])('keeps overlay capture safe during %s', async scenario => {