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.

fix: flush lifecycle event on quit

wytdac57633dce2
diff --git a/src/main/features/open_lifecycle.ts b/src/main/features/open_lifecycle.ts
index ceeeb931..563a161c 100644
--- a/src/main/features/open_lifecycle.ts
+++ b/src/main/features/open_lifecycle.ts
@@ -26,12 +26,17 @@ interface StartOptions {
getActiveUserId: () => string;
hasFocusedWindow: () => boolean;
enabled?: boolean;
- emit?: (record: OpenLifecycleRecord) => void;
+ emit?: (record: OpenLifecycleRecord) => void | Promise<void>;
setTimer?: typeof setTimeout;
clearTimer?: typeof clearTimeout;
blurSettleMs?: number;
}
+export interface OpenLifecycleTracking {
+ stop: () => void;
+ flushQuit: () => Promise<void>;
+}
+
const log = createLogger('open-lifecycle');
const REQUEST_TIMEOUT_MS = 5_000;
const BLUR_SETTLE_MS = 200;
@@ -52,12 +57,12 @@ export function openLifecycleRequestBody(
return { uid, event: record.event, trigger: record.trigger };
}
-export function reportOpenLifecycle(uid: string, record: OpenLifecycleRecord): void {
+export async function reportOpenLifecycle(uid: string, record: OpenLifecycleRecord): Promise<void> {
if (!safeId(uid) || uid.length > 50) {
warnTransport('lifecycle event skipped because the active uid is invalid', { reason: 'invalid_uid' });
return;
}
- void (async () => {
+ try {
const response = await fetchWithRetry(
'open-lifecycle',
`${apiBase()}/analytics/open-app-lifecycle`,
@@ -81,49 +86,75 @@ export function reportOpenLifecycle(uid: string, record: OpenLifecycleRecord): v
return;
}
await response.body?.cancel().catch(() => {});
- })().catch((error) => {
+ } catch (error) {
warnTransport('lifecycle event delivery failed', { error: logErrorRef(error) });
- });
+ }
}
export class OpenLifecycleState {
private started = false;
private foreground = false;
+ private quitReported = false;
- constructor(private readonly emit: (record: OpenLifecycleRecord) => void) {}
+ constructor(private readonly emit: (
+ record: OpenLifecycleRecord,
+ ) => void | Promise<void>) {}
- start(): void {
+ start(): void | Promise<void> {
if (this.started) return;
this.started = true;
this.foreground = true;
- this.emit({ event: 'enter', trigger: 'cold_start' });
+ return this.emit({ event: 'enter', trigger: 'cold_start' });
}
- enterForeground(): void {
- if (!this.started || this.foreground) return;
+ enterForeground(): void | Promise<void> {
+ if (!this.started || this.foreground || this.quitReported) return;
this.foreground = true;
- this.emit({ event: 'enter', trigger: 'foreground' });
+ return this.emit({ event: 'enter', trigger: 'foreground' });
}
- leaveForeground(trigger: 'background' | 'quit'): void {
- if (!this.started || !this.foreground) return;
+ leaveForeground(trigger: 'background' | 'quit'): void | Promise<void> {
+ if (!this.started || this.quitReported) return;
+ if (trigger === 'quit') {
+ // A process exit is a terminal application event, not another focus
+ // transition. macOS commonly blurs the last window before before-quit;
+ // suppressing quit in that state made real exits disappear entirely.
+ this.quitReported = true;
+ this.foreground = false;
+ return this.emit({ event: 'leave', trigger });
+ }
+ if (!this.foreground) return;
this.foreground = false;
- this.emit({ event: 'leave', trigger });
+ return this.emit({ event: 'leave', trigger });
}
}
-export function startOpenLifecycleTracking(options: StartOptions): () => void {
- if (options.enabled === false) return () => {};
+export function startOpenLifecycleTracking(options: StartOptions): OpenLifecycleTracking {
+ if (options.enabled === false) {
+ return {
+ stop: () => {},
+ flushQuit: async () => {},
+ };
+ }
const setTimer = options.setTimer || setTimeout;
const clearTimer = options.clearTimer || clearTimeout;
- const state = new OpenLifecycleState(options.emit || ((record) => {
+ const deliver = (record: OpenLifecycleRecord): Promise<void> => {
try {
- reportOpenLifecycle(options.getActiveUserId(), record);
+ return Promise.resolve(
+ options.emit
+ ? options.emit(record)
+ : reportOpenLifecycle(options.getActiveUserId(), record),
+ ).catch((error) => {
+ warnTransport('lifecycle event delivery failed', { error: logErrorRef(error) });
+ });
} catch (error) {
warnTransport('lifecycle event preparation failed', { error: logErrorRef(error) });
+ return Promise.resolve();
}
- }));
+ };
+ const state = new OpenLifecycleState(deliver);
let blurTimer: ReturnType<typeof setTimeout> | null = null;
+ let quitDelivery: Promise<void> | null = null;
const cancelBlurTimer = () => {
if (blurTimer === null) return;
@@ -141,20 +172,30 @@ export function startOpenLifecycleTracking(options: StartOptions): () => void {
if (!options.hasFocusedWindow()) state.leaveForeground('background');
}, options.blurSettleMs ?? BLUR_SETTLE_MS);
};
- const onBeforeQuit = () => {
+ const flushQuit = (): Promise<void> => {
cancelBlurTimer();
- state.leaveForeground('quit');
+ if (!quitDelivery) {
+ quitDelivery = Promise.resolve(state.leaveForeground('quit'));
+ }
+ return quitDelivery;
+ };
+ const onBeforeQuit = () => {
+ // The main shutdown barrier awaits the same promise. Starting it here
+ // keeps this module correct for callers with their own quit sequence too.
+ void flushQuit();
};
options.app.on('browser-window-focus', onFocus);
options.app.on('browser-window-blur', onBlur);
options.app.on('before-quit', onBeforeQuit);
- state.start();
+ void state.start();
- return () => {
+ const stop = () => {
cancelBlurTimer();
options.app.off('browser-window-focus', onFocus);
options.app.off('browser-window-blur', onBlur);
options.app.off('before-quit', onBeforeQuit);
};
+
+ return { stop, flushQuit };
}
diff --git a/src/main/index.ts b/src/main/index.ts
index 3cae2dfd..0a9a0454 100644
--- a/src/main/index.ts
+++ b/src/main/index.ts
@@ -194,7 +194,10 @@ 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 {
+ startOpenLifecycleTracking,
+ type OpenLifecycleTracking,
+} from './features/open_lifecycle';
import {
consumeColdLaunchConnectorCallback,
registerConnectorProtocol,
@@ -205,6 +208,7 @@ import * as windowState from './features/window_state';
// through the open server bridge.
let windowsTaskBadgeIcon: ReturnType<typeof nativeImage.createFromDataURL> | null = null;
+let openLifecycleTracking: OpenLifecycleTracking | null = null;
function setTaskNotificationBadgeCount(count: number): void {
const normalized = Math.max(0, Math.trunc(count));
@@ -421,7 +425,7 @@ function registerIpc(): void {
// crashes immediately due to missing packages. The shell script receives
// this process as its explicit owner, waits for it to exit, then starts the
// replacement without touching any other Electron process.
- ipcMain.handle('orkas.relaunch', () => {
+ ipcMain.handle('orkas.relaunch', async () => {
const isWindows = process.platform === 'win32';
const script = path.join(paths.PC_ROOT, isWindows ? 'run.cmd' : 'run.sh');
const resolved = isWindows
@@ -444,6 +448,7 @@ function registerIpc(): void {
});
child.unref();
log.info('relaunch via shell script');
+ await openLifecycleTracking?.flushQuit();
app.exit(0);
return { ok: true };
});
@@ -1338,7 +1343,7 @@ if (!gotLock) {
}, CONNECTORS_BOOTSTRAP_DELAY_MS);
connectorsTimer.unref?.();
createWindow();
- const stopOpenLifecycleTracking = startOpenLifecycleTracking({
+ openLifecycleTracking = startOpenLifecycleTracking({
app,
getActiveUserId: () => users.getActiveUserId(),
hasFocusedWindow: () => BrowserWindow.getAllWindows().some((win) => (
@@ -1348,7 +1353,10 @@ if (!gotLock) {
// write production analytics. Normal source and packaged runs behave alike.
enabled: !E2E_USER_DATA_DIR && !IS_PACKAGED_LAUNCH_SMOKE,
});
- app.once('will-quit', stopOpenLifecycleTracking);
+ app.once('will-quit', () => {
+ openLifecycleTracking?.stop();
+ openLifecycleTracking = null;
+ });
await consumeColdLaunchConnectorCallback();
// Boot tasks declared via util/boot_init.ts. Two phases × two modes:
@@ -1433,12 +1441,16 @@ if (!gotLock) {
app.on('before-quit', async (e) => {
if (shutdownFlushed) return;
e.preventDefault();
+ // Begin the network request before slower disk cleanup and do not release
+ // the Electron process until Server has acknowledged the lifecycle request.
+ const lifecycleFlush = openLifecycleTracking?.flushQuit();
try { await searchFeature.flushAll(); }
catch (err) { createLogger('search').warn('final flush failed', { error: (err as Error).message }); }
try {
const kb = await import('./features/kb_vector');
kb.closeAllKb();
} catch (err) { createLogger('kb_vector').warn('close failed', { error: (err as Error).message }); }
+ await lifecycleFlush;
shutdownFlushed = true;
app.quit();
});
diff --git a/test/main/features/open_lifecycle.test.ts b/test/main/features/open_lifecycle.test.ts
index c7cf112c..3fa131a2 100644
--- a/test/main/features/open_lifecycle.test.ts
+++ b/test/main/features/open_lifecycle.test.ts
@@ -48,6 +48,23 @@ describe('OpenLifecycleState', () => {
]);
});
+ it('reports one terminal quit even after the app already entered background', () => {
+ const records: OpenLifecycleRecord[] = [];
+ const state = new OpenLifecycleState((record) => records.push(record));
+
+ state.start();
+ state.leaveForeground('background');
+ state.leaveForeground('quit');
+ state.leaveForeground('quit');
+ state.enterForeground();
+
+ expect(records).toEqual([
+ { event: 'enter', trigger: 'cold_start' },
+ { event: 'leave', trigger: 'background' },
+ { event: 'leave', trigger: 'quit' },
+ ]);
+ });
+
it('keeps the public request body closed to three fields', () => {
expect(openLifecycleRequestBody('12345678', {
event: 'enter',
@@ -64,7 +81,7 @@ describe('OpenLifecycleState', () => {
const records: OpenLifecycleRecord[] = [];
const timers: Array<() => void> = [];
let focused = true;
- const stop = startOpenLifecycleTracking({
+ const tracking = startOpenLifecycleTracking({
app,
getActiveUserId: () => 'unused',
hasFocusedWindow: () => focused,
@@ -94,11 +111,43 @@ describe('OpenLifecycleState', () => {
{ event: 'leave', trigger: 'quit' },
]);
- stop();
+ tracking.stop();
app.emit('browser-window-focus');
expect(records).toHaveLength(4);
});
+ it('keeps the quit delivery awaitable while before-quit remains non-blocking', async () => {
+ const app = new FakeApp();
+ const records: OpenLifecycleRecord[] = [];
+ let releaseQuit: (() => void) | undefined;
+ const quitDelivery = new Promise<void>((resolve) => {
+ releaseQuit = resolve;
+ });
+ const tracking = startOpenLifecycleTracking({
+ app,
+ getActiveUserId: () => 'unused',
+ hasFocusedWindow: () => true,
+ emit: (record) => {
+ records.push(record);
+ return record.trigger === 'quit' ? quitDelivery : undefined;
+ },
+ });
+
+ app.emit('before-quit');
+ const flush = tracking.flushQuit();
+ let settled = false;
+ void flush.then(() => { settled = true; });
+ await Promise.resolve();
+
+ expect(settled).toBe(false);
+ expect(records.filter((record) => record.trigger === 'quit')).toHaveLength(1);
+
+ releaseQuit?.();
+ await flush;
+ expect(settled).toBe(true);
+ tracking.stop();
+ });
+
it('does not register or emit in synthetic launch modes', () => {
const app = new FakeApp();
const records: OpenLifecycleRecord[] = [];
diff --git a/test/main/index-process.test.ts b/test/main/index-process.test.ts
index d7969290..d3074591 100644
--- a/test/main/index-process.test.ts
+++ b/test/main/index-process.test.ts
@@ -40,6 +40,7 @@ describe('main process child-process ownership', () => {
expect(relaunchBlock).toContain('windowsVerbatimArguments: resolved.windowsVerbatimArguments');
expect(relaunchBlock).toContain('env: childEnv');
expect(relaunchBlock).toContain('child.unref()');
+ expect(relaunchBlock).toContain('await openLifecycleTracking?.flushQuit()');
const shellLauncher = fs.readFileSync(
path.resolve(process.cwd(), 'run.sh'),