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.

feat(analytics): report app lifecycle events

wyt40efc67158e5
diff --git a/src/main/features/open_lifecycle.ts b/src/main/features/open_lifecycle.ts
new file mode 100644
index 00000000..ceeeb931
--- /dev/null
+++ b/src/main/features/open_lifecycle.ts
@@ -0,0 +1,160 @@
+/** Open-source-build application lifecycle reporting through the guarded Server API. */
+
+import { createLogger } from '../logger';
+import { logErrorRef } from '../util/log-redact';
+import { fetchWithRetry } from '../util/retry';
+import { safeId } from '../storage';
+import { withCommonHeaders } from './api_common';
+import { apiBase } from './marketplace';
+
+
+export type OpenLifecycleEvent = 'enter' | 'leave';
+export type OpenLifecycleTrigger = 'cold_start' | 'foreground' | 'background' | 'quit';
+
+export interface OpenLifecycleRecord {
+ event: OpenLifecycleEvent;
+ trigger: OpenLifecycleTrigger;
+}
+
+interface AppEventSource {
+ on(event: 'browser-window-focus' | 'browser-window-blur' | 'before-quit', listener: () => void): unknown;
+ off(event: 'browser-window-focus' | 'browser-window-blur' | 'before-quit', listener: () => void): unknown;
+}
+
+interface StartOptions {
+ app: AppEventSource;
+ getActiveUserId: () => string;
+ hasFocusedWindow: () => boolean;
+ enabled?: boolean;
+ emit?: (record: OpenLifecycleRecord) => void;
+ setTimer?: typeof setTimeout;
+ clearTimer?: typeof clearTimeout;
+ blurSettleMs?: number;
+}
+
+const log = createLogger('open-lifecycle');
+const REQUEST_TIMEOUT_MS = 5_000;
+const BLUR_SETTLE_MS = 200;
+const WARNING_INTERVAL_MS = 60_000;
+let lastWarningAt = 0;
+
+function warnTransport(message: string, detail: Record<string, unknown>): void {
+ const now = Date.now();
+ if (now - lastWarningAt < WARNING_INTERVAL_MS) return;
+ lastWarningAt = now;
+ log.warn(message, detail);
+}
+
+export function openLifecycleRequestBody(
+ uid: string,
+ record: OpenLifecycleRecord,
+): { uid: string; event: OpenLifecycleEvent; trigger: OpenLifecycleTrigger } {
+ return { uid, event: record.event, trigger: record.trigger };
+}
+
+export function reportOpenLifecycle(uid: string, record: OpenLifecycleRecord): void {
+ if (!safeId(uid) || uid.length > 50) {
+ warnTransport('lifecycle event skipped because the active uid is invalid', { reason: 'invalid_uid' });
+ return;
+ }
+ void (async () => {
+ const response = await fetchWithRetry(
+ 'open-lifecycle',
+ `${apiBase()}/analytics/open-app-lifecycle`,
+ {
+ method: 'POST',
+ headers: withCommonHeaders({
+ 'Content-Type': 'application/json',
+ Accept: 'application/json',
+ }),
+ body: JSON.stringify(openLifecycleRequestBody(uid, record)),
+ },
+ {
+ retries: 0,
+ timeoutMs: REQUEST_TIMEOUT_MS,
+ timeoutMessage: 'open lifecycle request timed out',
+ },
+ );
+ if (!response.ok) {
+ await response.body?.cancel().catch(() => {});
+ warnTransport('lifecycle event rejected', { status_code: response.status });
+ return;
+ }
+ await response.body?.cancel().catch(() => {});
+ })().catch((error) => {
+ warnTransport('lifecycle event delivery failed', { error: logErrorRef(error) });
+ });
+}
+
+export class OpenLifecycleState {
+ private started = false;
+ private foreground = false;
+
+ constructor(private readonly emit: (record: OpenLifecycleRecord) => void) {}
+
+ start(): void {
+ if (this.started) return;
+ this.started = true;
+ this.foreground = true;
+ this.emit({ event: 'enter', trigger: 'cold_start' });
+ }
+
+ enterForeground(): void {
+ if (!this.started || this.foreground) return;
+ this.foreground = true;
+ this.emit({ event: 'enter', trigger: 'foreground' });
+ }
+
+ leaveForeground(trigger: 'background' | 'quit'): void {
+ if (!this.started || !this.foreground) return;
+ this.foreground = false;
+ this.emit({ event: 'leave', trigger });
+ }
+}
+
+export function startOpenLifecycleTracking(options: StartOptions): () => void {
+ if (options.enabled === false) return () => {};
+ const setTimer = options.setTimer || setTimeout;
+ const clearTimer = options.clearTimer || clearTimeout;
+ const state = new OpenLifecycleState(options.emit || ((record) => {
+ try {
+ reportOpenLifecycle(options.getActiveUserId(), record);
+ } catch (error) {
+ warnTransport('lifecycle event preparation failed', { error: logErrorRef(error) });
+ }
+ }));
+ let blurTimer: ReturnType<typeof setTimeout> | null = null;
+
+ const cancelBlurTimer = () => {
+ if (blurTimer === null) return;
+ clearTimer(blurTimer);
+ blurTimer = null;
+ };
+ const onFocus = () => {
+ cancelBlurTimer();
+ state.enterForeground();
+ };
+ const onBlur = () => {
+ cancelBlurTimer();
+ blurTimer = setTimer(() => {
+ blurTimer = null;
+ if (!options.hasFocusedWindow()) state.leaveForeground('background');
+ }, options.blurSettleMs ?? BLUR_SETTLE_MS);
+ };
+ const onBeforeQuit = () => {
+ cancelBlurTimer();
+ state.leaveForeground('quit');
+ };
+
+ options.app.on('browser-window-focus', onFocus);
+ options.app.on('browser-window-blur', onBlur);
+ options.app.on('before-quit', onBeforeQuit);
+ state.start();
+
+ return () => {
+ cancelBlurTimer();
+ options.app.off('browser-window-focus', onFocus);
+ options.app.off('browser-window-blur', onBlur);
+ options.app.off('before-quit', onBeforeQuit);
+ };
+}
diff --git a/src/main/features/users.ts b/src/main/features/users.ts
index 6b0b0440..7038a6d9 100644
--- a/src/main/features/users.ts
+++ b/src/main/features/users.ts
@@ -12,7 +12,7 @@
* - the server account uid while logged in.
*
* the open-source build still calls `initActiveUser()` without options, so first boot
- * keeps the original 8-digit local id.
+ * creates a random 32-character local id.
*
* Boot sequence:
* 1. Read users.json; if absent, create the first profile id and point the
@@ -66,7 +66,7 @@ interface UsersRegistry {
}
export interface InitActiveUserOptions {
- /** Hosted Orkas passes `anonymous`; the open-source build omits this and gets a generated 8-digit uid. */
+ /** Hosted Orkas passes `anonymous`; the open-source build omits this and gets a generated 32-character uid. */
defaultLocalId?: string;
}
@@ -430,7 +430,7 @@ export function activateUser(uid: string): void {
/**
* Boot-time entrypoint — read users.json and activate this environment's
* current-user pointer. If none exists, activate `defaultLocalId` (hosted:
- * anonymous) or generate the legacy 8-digit uid (the open-source build).
+ * anonymous) or generate a random 32-character uid (the open-source build).
*/
export function initActiveUser(opts: InitActiveUserOptions = {}): UserRecord {
const reg = readRegistry();
diff --git a/src/main/index.ts b/src/main/index.ts
index 30062562..8eab8f49 100644
--- a/src/main/index.ts
+++ b/src/main/index.ts
@@ -192,6 +192,7 @@ import * as clientConfigFeature from './features/client_config';
import * as connectorsFeature from './features/connectors';
import * as taskNotifications from './features/task_notifications';
import * as notificationPermissions from './features/notification_permissions';
+import { startOpenLifecycleTracking } from './features/open_lifecycle';
import {
consumeColdLaunchConnectorCallback,
registerConnectorProtocol,
@@ -1193,6 +1194,17 @@ if (!gotLock) {
}, CONNECTORS_BOOTSTRAP_DELAY_MS);
connectorsTimer.unref?.();
createWindow();
+ const stopOpenLifecycleTracking = startOpenLifecycleTracking({
+ app,
+ getActiveUserId: () => users.getActiveUserId(),
+ hasFocusedWindow: () => BrowserWindow.getAllWindows().some((win) => (
+ !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.
+ enabled: !E2E_USER_DATA_DIR && !IS_PACKAGED_LAUNCH_SMOKE,
+ });
+ app.once('will-quit', stopOpenLifecycleTracking);
await consumeColdLaunchConnectorCallback();
// Boot tasks declared via util/boot_init.ts. Two phases × two modes:
diff --git a/src/main/smoke.ts b/src/main/smoke.ts
index 3adb11a4..07800f6b 100644
--- a/src/main/smoke.ts
+++ b/src/main/smoke.ts
@@ -51,7 +51,7 @@ async function section(name: string, fn: () => void | Promise<void>): Promise<vo
console.log('[smoke] storage');
await section('nowIso matches YYYY-MM-DDTHH:MM:SS', () =>
assert.ok(/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}$/.test(storage.nowIso())));
- await section('genUserId is 8 digits', () => assert.ok(/^\d{8}$/.test(storage.genUserId())));
+ await section('genUserId is 32 lowercase hex characters', () => assert.ok(/^[0-9a-f]{32}$/.test(storage.genUserId())));
await section('genId12 is 12 hex', () => assert.ok(/^[0-9a-f]{12}$/.test(storage.genId12())));
await section('safeId rejects traversal', () => assert.ok(!storage.safeId('../evil')));
await section('safeId accepts normal', () => assert.ok(storage.safeId('abc-123_XYZ')));
diff --git a/src/main/storage.ts b/src/main/storage.ts
index 1574b627..53cabe90 100644
--- a/src/main/storage.ts
+++ b/src/main/storage.ts
@@ -22,11 +22,9 @@ export function nowIso(): string {
return `${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())}T${pad(d.getHours())}:${pad(d.getMinutes())}:${pad(d.getSeconds())}`;
}
-/** 8-digit numeric user id. */
+/** UUID v4 local user id: 32 lowercase hexadecimal characters without hyphens. */
export function genUserId(): string {
- let out = '';
- for (let i = 0; i < 8; i++) out += Math.floor(Math.random() * 10);
- return out;
+ return crypto.randomUUID().replace(/-/g, '');
}
/** 12-hex-char id (agents + conversations). */
diff --git a/test/main/features/open_lifecycle.test.ts b/test/main/features/open_lifecycle.test.ts
new file mode 100644
index 00000000..c7cf112c
--- /dev/null
+++ b/test/main/features/open_lifecycle.test.ts
@@ -0,0 +1,117 @@
+import { describe, expect, it } from 'vitest';
+
+import {
+ OpenLifecycleState,
+ openLifecycleRequestBody,
+ startOpenLifecycleTracking,
+ type OpenLifecycleRecord,
+} from '../../../src/main/features/open_lifecycle';
+
+
+class FakeApp {
+ private readonly listeners = new Map<string, Set<() => void>>();
+
+ on(event: string, listener: () => void): void {
+ const group = this.listeners.get(event) || new Set<() => void>();
+ group.add(listener);
+ this.listeners.set(event, group);
+ }
+
+ off(event: string, listener: () => void): void {
+ this.listeners.get(event)?.delete(listener);
+ }
+
+ emit(event: string): void {
+ for (const listener of this.listeners.get(event) || []) listener();
+ }
+}
+
+describe('OpenLifecycleState', () => {
+ it('emits only real cold-start, foreground, background, and quit transitions', () => {
+ const records: OpenLifecycleRecord[] = [];
+ const state = new OpenLifecycleState((record) => records.push(record));
+
+ state.start();
+ state.start();
+ state.enterForeground();
+ state.leaveForeground('background');
+ state.leaveForeground('background');
+ state.enterForeground();
+ state.enterForeground();
+ state.leaveForeground('quit');
+
+ expect(records).toEqual([
+ { event: 'enter', trigger: 'cold_start' },
+ { event: 'leave', trigger: 'background' },
+ { event: 'enter', trigger: 'foreground' },
+ { event: 'leave', trigger: 'quit' },
+ ]);
+ });
+
+ it('keeps the public request body closed to three fields', () => {
+ expect(openLifecycleRequestBody('12345678', {
+ event: 'enter',
+ trigger: 'cold_start',
+ })).toEqual({
+ uid: '12345678',
+ event: 'enter',
+ trigger: 'cold_start',
+ });
+ });
+
+ it('settles blur before leaving and removes every listener on stop', () => {
+ const app = new FakeApp();
+ const records: OpenLifecycleRecord[] = [];
+ const timers: Array<() => void> = [];
+ let focused = true;
+ const stop = startOpenLifecycleTracking({
+ app,
+ getActiveUserId: () => 'unused',
+ hasFocusedWindow: () => focused,
+ emit: (record) => records.push(record),
+ setTimer: ((callback: () => void) => {
+ timers.push(callback);
+ return timers.length as unknown as ReturnType<typeof setTimeout>;
+ }) as typeof setTimeout,
+ clearTimer: (() => {}) as typeof clearTimeout,
+ });
+
+ app.emit('browser-window-blur');
+ timers.shift()?.();
+ expect(records).toEqual([{ event: 'enter', trigger: 'cold_start' }]);
+
+ focused = false;
+ app.emit('browser-window-blur');
+ timers.shift()?.();
+ app.emit('browser-window-focus');
+ app.emit('before-quit');
+ app.emit('before-quit');
+
+ expect(records).toEqual([
+ { event: 'enter', trigger: 'cold_start' },
+ { event: 'leave', trigger: 'background' },
+ { event: 'enter', trigger: 'foreground' },
+ { event: 'leave', trigger: 'quit' },
+ ]);
+
+ stop();
+ app.emit('browser-window-focus');
+ expect(records).toHaveLength(4);
+ });
+
+ it('does not register or emit in synthetic launch modes', () => {
+ const app = new FakeApp();
+ const records: OpenLifecycleRecord[] = [];
+ startOpenLifecycleTracking({
+ app,
+ getActiveUserId: () => 'unused',
+ hasFocusedWindow: () => true,
+ enabled: false,
+ emit: (record) => records.push(record),
+ });
+
+ app.emit('browser-window-focus');
+ app.emit('before-quit');
+ expect(records).toEqual([]);
+ });
+});
diff --git a/test/main/features/users.test.ts b/test/main/features/users.test.ts
index 1b7a34c8..b2794254 100644
--- a/test/main/features/users.test.ts
+++ b/test/main/features/users.test.ts
@@ -149,7 +149,7 @@ describe('features/users › initActiveUser', () => {
it('first boot: generates a uid and writes users.json', async () => {
const users = await import('../../../src/main/features/users');
const rec = users.initActiveUser();
- expect(/^\d{8}$/.test(rec.user_id)).toBe(true);
+ expect(/^[0-9a-f]{32}$/.test(rec.user_id)).toBe(true);
expect(users.getActiveUserId()).toBe(rec.user_id);
expect(fs.existsSync(path.join(tmpDir, 'users.json'))).toBe(true);
});
@@ -162,18 +162,18 @@ describe('features/users › initActiveUser', () => {
expect(fs.existsSync(path.join(tmpDir, 'anonymous', 'local', 'config'))).toBe(true);
});
- it('subsequent boot: reuses current_user_id from users.json', async () => {
+ it('subsequent boot: preserves an existing legacy 8-digit uid', async () => {
fs.writeFileSync(
path.join(tmpDir, 'users.json'),
JSON.stringify({
- current_user_id: 'u1',
- users: [{ user_id: 'u1', created_at: '2026-01-01T00:00:00' }],
+ current_user_id: '12345678',
+ users: [{ user_id: '12345678', created_at: '2026-01-01T00:00:00' }],
}),
'utf-8',
);
const users = await import('../../../src/main/features/users');
const rec = users.initActiveUser();
- expect(rec.user_id).toBe('u1');
+ expect(rec.user_id).toBe('12345678');
expect(rec.created_at).toBe('2026-01-01T00:00:00');
});
});
diff --git a/test/main/storage.test.ts b/test/main/storage.test.ts
index c1214b58..42b67dda 100644
--- a/test/main/storage.test.ts
+++ b/test/main/storage.test.ts
@@ -30,9 +30,9 @@ describe('storage › timestamps & ids', () => {
expect(nowIso()).toMatch(/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}$/);
});
- it('genUserId returns 8 decimal digits', () => {
+ it('genUserId returns a lowercase UUID v4 without hyphens', () => {
for (let i = 0; i < 50; i++) {
- expect(genUserId()).toMatch(/^\d{8}$/);
+ expect(genUserId()).toMatch(/^[0-9a-f]{12}4[0-9a-f]{3}[89ab][0-9a-f]{15}$/);
}
});