forked from Blendman974/faceclaw
Clean up unused worker threads for closed apps; other performance optimizations
This commit is contained in:
1 parent
9560f3ac8d
commit
2e4d20e130
20 files changed
+360
-13
No files matched your search
@@ -11,6 +11,7 @@
|
||||
* focus, tap-then-hold opens the window menu.
|
||||
*/
|
||||
import "@nativescript/core/globals";
|
||||
import { finishWorkerShutdown } from "../../ui/shell/worker-lifecycle";
|
||||
import { GrayImage } from "../../graphics/image";
|
||||
import { flattenPlanesWithDraws, planesFingerprint, type Plane } from "../../graphics/plane";
|
||||
import { prepareFrameDraws } from "../../graphics/glyph-wire";
|
||||
@@ -187,6 +188,12 @@ post({ type: "worker-ready" });
|
||||
global.onmessage = (event: { data: WorkerAppMessage }) => {
|
||||
const message = event.data;
|
||||
switch (message.type) {
|
||||
case "check-idle":
|
||||
post({ type: "worker-idle" });
|
||||
break;
|
||||
case "shutdown":
|
||||
finishWorkerShutdown();
|
||||
break;
|
||||
case "open-window": {
|
||||
const window: BlocksWindow = {
|
||||
windowId: message.windowId,
|
||||
|
||||
@@ -25,6 +25,7 @@
|
||||
* focus to the sidebar) pauses, as does backgrounding or screen-off.
|
||||
*/
|
||||
import "@nativescript/core/globals";
|
||||
import { finishWorkerShutdown } from "../../ui/shell/worker-lifecycle";
|
||||
import { GrayImage } from "../../graphics/image";
|
||||
import { flattenPlanesWithDraws, planesFingerprint, type Plane } from "../../graphics/plane";
|
||||
import { prepareFrameDraws } from "../../graphics/glyph-wire";
|
||||
@@ -180,6 +181,12 @@ post({ type: "worker-ready" });
|
||||
global.onmessage = (event: { data: WorkerAppMessage }) => {
|
||||
const message = event.data;
|
||||
switch (message.type) {
|
||||
case "check-idle":
|
||||
post({ type: "worker-idle" });
|
||||
break;
|
||||
case "shutdown":
|
||||
finishWorkerShutdown();
|
||||
break;
|
||||
case "open-window": {
|
||||
const window: FlappyWindow = {
|
||||
windowId: message.windowId,
|
||||
|
||||
@@ -18,6 +18,7 @@
|
||||
* Safe cards auto-play to the foundations after every move.
|
||||
*/
|
||||
import "@nativescript/core/globals";
|
||||
import { finishWorkerShutdown } from "../../ui/shell/worker-lifecycle";
|
||||
import { GrayImage } from "../../graphics/image";
|
||||
import { flattenPlanesWithDraws, planesFingerprint, singlePlane, type Plane } from "../../graphics/plane";
|
||||
import { prepareFrameDraws } from "../../graphics/glyph-wire";
|
||||
@@ -144,6 +145,12 @@ post({ type: "worker-ready" });
|
||||
global.onmessage = (event: { data: WorkerAppMessage }) => {
|
||||
const message = event.data;
|
||||
switch (message.type) {
|
||||
case "check-idle":
|
||||
post({ type: "worker-idle" });
|
||||
break;
|
||||
case "shutdown":
|
||||
finishWorkerShutdown();
|
||||
break;
|
||||
case "open-window": {
|
||||
const window: FreecellWindow = {
|
||||
windowId: message.windowId,
|
||||
|
||||
@@ -0,0 +1,11 @@
|
||||
import { getStringSetting } from "../../native/settings-store";
|
||||
import { QUADRANT_LAYOUT, SIX_SLOT_LAYOUT } from "./layout";
|
||||
|
||||
/** Configuration-only query usable by workers without loading widget/UI modules. */
|
||||
export function isTerminalWidgetConfigured(): boolean {
|
||||
const layout = getStringSetting("glanceboard.layout", "2x2") === "2x3" ? SIX_SLOT_LAYOUT : QUADRANT_LAYOUT;
|
||||
// Both layouts store their slots under the original quadrants key. None
|
||||
// of the default slots needs a worker, so absent keys cannot retain one.
|
||||
return layout.slots.some((_, index) =>
|
||||
getStringSetting(`glanceboard.${QUADRANT_LAYOUT.id}.slot.${index}`, "none") === "terminal");
|
||||
}
|
||||
@@ -18,6 +18,7 @@
|
||||
* launches.
|
||||
*/
|
||||
import "@nativescript/core/globals";
|
||||
import { finishWorkerShutdown } from "../../ui/shell/worker-lifecycle";
|
||||
import { GrayImage } from "../../graphics/image";
|
||||
import { flattenPlanesWithDraws, planesFingerprint, type Plane } from "../../graphics/plane";
|
||||
import { prepareFrameDraws } from "../../graphics/glyph-wire";
|
||||
@@ -152,6 +153,12 @@ post({ type: "worker-ready" });
|
||||
global.onmessage = (event: { data: WorkerAppMessage }) => {
|
||||
const message = event.data;
|
||||
switch (message.type) {
|
||||
case "check-idle":
|
||||
post({ type: "worker-idle" });
|
||||
break;
|
||||
case "shutdown":
|
||||
finishWorkerShutdown();
|
||||
break;
|
||||
case "open-window": {
|
||||
const window: MinesweeperWindow = {
|
||||
windowId: message.windowId,
|
||||
|
||||
@@ -7,6 +7,7 @@
|
||||
* guidance text (right pane) updates per GPS fix and ships as small deltas.
|
||||
*/
|
||||
import "@nativescript/core/globals";
|
||||
import { finishWorkerShutdown } from "../../ui/shell/worker-lifecycle";
|
||||
import { GrayImage } from "../../graphics/image";
|
||||
import { flattenPlanesWithDraws, planesFingerprint, type Plane } from "../../graphics/plane";
|
||||
import { prepareFrameDraws } from "../../graphics/glyph-wire";
|
||||
@@ -275,6 +276,12 @@ post({ type: "worker-ready" });
|
||||
global.onmessage = (event: { data: WorkerAppMessage }) => {
|
||||
const message = event.data;
|
||||
switch (message.type) {
|
||||
case "check-idle":
|
||||
post({ type: "worker-idle" });
|
||||
break;
|
||||
case "shutdown":
|
||||
finishWorkerShutdown();
|
||||
break;
|
||||
case "navigation-sensors":
|
||||
handleNavigationSensorEvent(message.event);
|
||||
break;
|
||||
|
||||
@@ -21,6 +21,7 @@
|
||||
* sidebar) pauses, as does backgrounding or screen-off.
|
||||
*/
|
||||
import "@nativescript/core/globals";
|
||||
import { finishWorkerShutdown } from "../../ui/shell/worker-lifecycle";
|
||||
import { GrayImage } from "../../graphics/image";
|
||||
import { flattenPlanesWithDraws, planesFingerprint, type Plane } from "../../graphics/plane";
|
||||
import { prepareFrameDraws } from "../../graphics/glyph-wire";
|
||||
@@ -290,6 +291,12 @@ post({ type: "worker-ready" });
|
||||
global.onmessage = (event: { data: WorkerAppMessage }) => {
|
||||
const message = event.data;
|
||||
switch (message.type) {
|
||||
case "check-idle":
|
||||
post({ type: "worker-idle" });
|
||||
break;
|
||||
case "shutdown":
|
||||
finishWorkerShutdown();
|
||||
break;
|
||||
case "open-window": {
|
||||
const window: PinballWindow = {
|
||||
windowId: message.windowId,
|
||||
|
||||
@@ -8,6 +8,7 @@
|
||||
* menu, via the phone app's text editor.
|
||||
*/
|
||||
import "@nativescript/core/globals";
|
||||
import { finishWorkerShutdown } from "../../ui/shell/worker-lifecycle";
|
||||
import { GrayImage } from "../../graphics/image";
|
||||
import { flattenPlanesWithDraws, planesFingerprint, singlePlane, type Plane } from "../../graphics/plane";
|
||||
import { prepareFrameDraws } from "../../graphics/glyph-wire";
|
||||
@@ -165,6 +166,12 @@ post({ type: "worker-ready" });
|
||||
global.onmessage = (event: { data: WorkerAppMessage }) => {
|
||||
const message = event.data;
|
||||
switch (message.type) {
|
||||
case "check-idle":
|
||||
post({ type: "worker-idle" });
|
||||
break;
|
||||
case "shutdown":
|
||||
finishWorkerShutdown();
|
||||
break;
|
||||
case "open-window":
|
||||
window = {
|
||||
windowId: message.windowId,
|
||||
|
||||
@@ -0,0 +1,8 @@
|
||||
import { isTerminalWidgetConfigured } from "../glanceboard/configuration";
|
||||
import { loadConnections, parseConnectionString } from "./connections";
|
||||
|
||||
/** Keep session-list connections alive for a configured widget, even while it is hidden. */
|
||||
export function hasTerminalBackgroundWork(): boolean {
|
||||
return isTerminalWidgetConfigured() &&
|
||||
loadConnections().some(connection => connection.enabled && parseConnectionString(connection.url) !== null);
|
||||
}
|
||||
@@ -31,6 +31,8 @@
|
||||
* re-attach snapshot resyncs contents and scrollback only once it's needed.
|
||||
*/
|
||||
import "@nativescript/core/globals";
|
||||
import { hasTerminalBackgroundWork } from "./background";
|
||||
import { finishWorkerShutdown } from "../../ui/shell/worker-lifecycle";
|
||||
import { GrayImage, type UiFont } from "../../graphics/image";
|
||||
import { flattenPlanesWithDraws, planesFingerprint, type Plane } from "../../graphics/plane";
|
||||
import { prepareFrameDraws } from "../../graphics/glyph-wire";
|
||||
@@ -311,6 +313,14 @@ post({ type: "worker-ready" });
|
||||
global.onmessage = (event: { data: WorkerAppMessage }) => {
|
||||
const message = event.data;
|
||||
switch (message.type) {
|
||||
case "check-idle":
|
||||
reportIdle();
|
||||
break;
|
||||
case "shutdown":
|
||||
for (const control of controls.values()) stopControl(control);
|
||||
controls.clear();
|
||||
finishWorkerShutdown();
|
||||
break;
|
||||
case "open-window":
|
||||
openWindow(message.windowId, message.surfaceId, message.title, message.viewport);
|
||||
break;
|
||||
@@ -424,12 +434,17 @@ global.onmessage = (event: { data: WorkerAppMessage }) => {
|
||||
// toggles edited in the Settings app, the Add-connection draft typed on the
|
||||
// phone).
|
||||
onSettingsStoreChanged((key) => {
|
||||
if (key.startsWith("glanceboard.")) {
|
||||
reportIdle();
|
||||
return;
|
||||
}
|
||||
if (!key.startsWith("terminal.")) return;
|
||||
switch (key) {
|
||||
case TERMINAL_CONNECTIONS_KEY:
|
||||
// Only once the app has actually been opened.
|
||||
if (controlsInitialized) syncControlsFromSettings();
|
||||
renderHubWindows();
|
||||
reportIdle();
|
||||
return;
|
||||
case NEW_CONNECTION_DRAFT_KEY:
|
||||
// Live keystrokes from the phone editor; repaint the add screen.
|
||||
@@ -438,7 +453,7 @@ onSettingsStoreChanged((key) => {
|
||||
case "terminal.autoReconnect":
|
||||
if (!terminalAutoReconnectSetting.get()) {
|
||||
cancelPendingReconnects();
|
||||
} else if (windows.size > 0) {
|
||||
} else if (windows.size > 0 || hasTerminalBackgroundWork()) {
|
||||
for (const control of controls.values()) {
|
||||
if ((control.state?.phase ?? "idle") === "failed") scheduleControlReconnect(control);
|
||||
}
|
||||
@@ -450,6 +465,10 @@ onSettingsStoreChanged((key) => {
|
||||
}
|
||||
});
|
||||
|
||||
function reportIdle(): void {
|
||||
if (windows.size === 0 && !hasTerminalBackgroundWork()) post({ type: "worker-idle" });
|
||||
}
|
||||
|
||||
/** Cancel scheduled retries (auto-reconnect turned off); stale views stay marked. */
|
||||
function cancelPendingReconnects(): void {
|
||||
for (const control of controls.values()) {
|
||||
@@ -521,8 +540,8 @@ function closeWindow(windowId: string): void {
|
||||
windows.delete(windowId);
|
||||
windowIconActivity.delete(windowId);
|
||||
updateHubAnimation();
|
||||
// Auto-reconnect only runs while at least one terminal window is open.
|
||||
if (windows.size === 0) {
|
||||
// A configured widget owns the control connections after the last window closes.
|
||||
if (windows.size === 0 && !hasTerminalBackgroundWork()) {
|
||||
for (const control of controls.values()) {
|
||||
cancelControlReconnect(control);
|
||||
}
|
||||
@@ -676,19 +695,18 @@ function noteSessionListRecency(control: ControlConnection, state: G2MirrorState
|
||||
/**
|
||||
* Retry a control connection after a backoff delay. The delay doubles per
|
||||
* scheduled attempt and resets when a connection reaches "connected" (or on
|
||||
* a manual Connect). No-op when auto-reconnect is off, no terminal window is
|
||||
* open, or the connection was disabled/removed meanwhile.
|
||||
* a manual Connect). Windows and a configured widget can both own the client.
|
||||
*/
|
||||
function scheduleControlReconnect(control: ControlConnection): void {
|
||||
if (control.reconnectTimer) return;
|
||||
if (!terminalAutoReconnectSetting.get()) return;
|
||||
if (windows.size === 0) return;
|
||||
if (windows.size === 0 && !hasTerminalBackgroundWork()) return;
|
||||
if (!control.config.enabled) return;
|
||||
const delayMs = control.reconnectDelayMs;
|
||||
control.reconnectDelayMs = Math.min(control.reconnectDelayMs * 2, RECONNECT_MAX_DELAY_MS);
|
||||
control.reconnectTimer = setTimeout(() => {
|
||||
control.reconnectTimer = null;
|
||||
if (!terminalAutoReconnectSetting.get() || windows.size === 0) return;
|
||||
if (!terminalAutoReconnectSetting.get() || (windows.size === 0 && !hasTerminalBackgroundWork())) return;
|
||||
if (controls.get(control.config.id) !== control || !control.config.enabled) return;
|
||||
if ((control.state?.phase ?? "idle") === "failed") startControl(control);
|
||||
}, delayMs);
|
||||
|
||||
@@ -2228,6 +2228,7 @@ class DashboardController {
|
||||
const host = new WorkerAppHost({
|
||||
appId,
|
||||
worker: createWorker(),
|
||||
onStopping: () => { if (this.appHosts.get(appId) === host) this.appHosts.delete(appId); },
|
||||
configureSurface: (surfaceId, visible, heightMode) =>
|
||||
this.configureWindowSurface(surfaceId, visible, heightMode),
|
||||
setSurfaceVisible: (surfaceId, visible) => this.setWindowSurfaceVisible(surfaceId, visible),
|
||||
|
||||
@@ -503,6 +503,7 @@ export class IosPreviewController {
|
||||
? new IosNavigationSensors(event => worker.postMessage({ type: 'navigation-sensors', event })) : undefined
|
||||
const host = new WorkerAppHost({
|
||||
appId, worker, navigationSensors,
|
||||
onStopping: () => { if (this.appHosts.get(appId) === host) this.appHosts.delete(appId) },
|
||||
playBuzzerSequence: payload => this.actions.playBuzzerSequence(payload),
|
||||
openUrl: url => { void Utils.openUrl(url) },
|
||||
configureSurface: async (id, visible, heightMode) => {
|
||||
|
||||
@@ -18,6 +18,12 @@ function markChanged(key: string): void {
|
||||
}
|
||||
let pollTimer: ReturnType<typeof setInterval> | null = null
|
||||
const listeners = new Set<(key: string) => void>()
|
||||
export function disposeSettingsStore(): void {
|
||||
listeners.clear()
|
||||
if (pollTimer !== null) clearInterval(pollTimer)
|
||||
pollTimer = null
|
||||
observed.clear()
|
||||
}
|
||||
function changed(key: string): void {
|
||||
setTimeout(() => { for (const listener of [...listeners]) listener(key) }, 0)
|
||||
}
|
||||
|
||||
@@ -14,6 +14,13 @@ let javaInstance: any = null;
|
||||
let retainedListenerProxy: any = null;
|
||||
const changeListeners = new Set<(key: string) => void>();
|
||||
|
||||
/** Release this isolate's native observer before its worker is terminated. */
|
||||
export function disposeSettingsStore(): void {
|
||||
changeListeners.clear();
|
||||
if (retainedListenerProxy !== null) getJava().unregisterListener(retainedListenerProxy);
|
||||
retainedListenerProxy = null;
|
||||
}
|
||||
|
||||
function getJava(): any {
|
||||
if (javaInstance === null) {
|
||||
const context = Utils.android?.getApplicationContext?.();
|
||||
|
||||
@@ -0,0 +1,7 @@
|
||||
import { disposeSettingsStore } from "../../native/settings-store";
|
||||
|
||||
/** Called on the worker after its windows and app-owned resources are closed. */
|
||||
export function finishWorkerShutdown(): void {
|
||||
disposeSettingsStore();
|
||||
global.postMessage({ type: "worker-stopped" });
|
||||
}
|
||||
@@ -15,6 +15,10 @@ import { publishWorkerState } from "./worker-state";
|
||||
* worker→Java directly on Android; iOS posts baked frames to the main host.
|
||||
*/
|
||||
export type WorkerAppMessage =
|
||||
/** Last host window closed: report worker-idle unless background work still owns the worker. */
|
||||
| { type: "check-idle" }
|
||||
/** Release app-wide resources, then acknowledge with worker-stopped. */
|
||||
| { type: "shutdown" }
|
||||
| { type: "navigation-sensors"; event: NavigationSensorEvent }
|
||||
| { type: "open-window"; windowId: string; surfaceId: string; title: string; viewport: { width: number; height: number } }
|
||||
| { type: "resize-window"; windowId: string; viewport: { width: number; height: number } }
|
||||
@@ -34,6 +38,8 @@ export type WorkerAppMessage =
|
||||
| { type: "tool-call"; callId: string; windowId: string; name: string; args: unknown };
|
||||
|
||||
export type WorkerAppReply =
|
||||
| { type: "worker-idle" }
|
||||
| { type: "worker-stopped" }
|
||||
| { type: "buzzer-sequence"; payload: number[] }
|
||||
| { type: "navigation-sensors"; request: NavigationSensorRequest }
|
||||
| { type: "open-url"; url: string }
|
||||
@@ -182,6 +188,8 @@ export type WorkerWindowSpec = {
|
||||
export type WorkerAppHostOptions = {
|
||||
appId: string;
|
||||
worker: Worker;
|
||||
/** Drop this host from the app cache as soon as shutdown begins. */
|
||||
onStopping?: () => void;
|
||||
navigationSensors?: { handle(request: NavigationSensorRequest): void; stop(): void };
|
||||
openUrl?: (url: string) => void;
|
||||
playBuzzerSequence?: (payload: Uint8Array) => Promise<void> | void;
|
||||
@@ -236,12 +244,23 @@ export class WorkerAppHost {
|
||||
*/
|
||||
private workerReady = false;
|
||||
private readonly queuedMessages: WorkerAppMessage[] = [];
|
||||
private stopping = false;
|
||||
private terminated = false;
|
||||
private shutdownTimer: ReturnType<typeof setTimeout> | null = null;
|
||||
private readonly publishedStateKeys = new Set<string>();
|
||||
|
||||
constructor(private readonly options: WorkerAppHostOptions) {
|
||||
options.worker.onmessage = (event: MessageEvent) => {
|
||||
const message = event.data as WorkerAppReply | undefined;
|
||||
if (!message) return;
|
||||
if (this.stopping) {
|
||||
if (message.type === "worker-stopped") this.terminate();
|
||||
return;
|
||||
}
|
||||
switch (message.type) {
|
||||
case "worker-idle":
|
||||
if (!this.openWindows.size) this.shutdown();
|
||||
break;
|
||||
case "buzzer-sequence":
|
||||
if (this.openWindows.size) {
|
||||
void Promise.resolve(this.options.playBuzzerSequence?.(new Uint8Array(message.payload)))
|
||||
@@ -357,6 +376,7 @@ export class WorkerAppHost {
|
||||
// Titles are informational for now (sidebar shows icons only).
|
||||
break;
|
||||
case "publish-state":
|
||||
this.publishedStateKeys.add(message.key);
|
||||
publishWorkerState(message.key, message.state);
|
||||
break;
|
||||
case "set-tools":
|
||||
@@ -392,8 +412,33 @@ export class WorkerAppHost {
|
||||
return this.openWindows.size;
|
||||
}
|
||||
|
||||
private shutdown(): void {
|
||||
if (this.stopping) return;
|
||||
this.stopping = true;
|
||||
this.options.onStopping?.();
|
||||
this.queuedMessages.length = 0;
|
||||
this.options.navigationSensors?.stop();
|
||||
shell.setTrayIcon(this.options.appId, null);
|
||||
for (const key of this.publishedStateKeys) publishWorkerState(key, undefined);
|
||||
this.publishedStateKeys.clear();
|
||||
// The idle reply follows all close-window cleanup. Allow the worker to
|
||||
// release app-wide native subscriptions/sockets before killing its isolate.
|
||||
this.shutdownTimer = setTimeout(() => this.terminate(), 5000);
|
||||
this.options.worker.postMessage({ type: "shutdown" } satisfies WorkerAppMessage);
|
||||
}
|
||||
|
||||
private terminate(): void {
|
||||
if (this.terminated) return;
|
||||
this.terminated = true;
|
||||
if (this.shutdownTimer !== null) clearTimeout(this.shutdownTimer);
|
||||
this.shutdownTimer = null;
|
||||
this.options.worker.terminate();
|
||||
}
|
||||
|
||||
/** Open a window of this app and register it with the shell. */
|
||||
openWindow(spec: WorkerWindowSpec): ShellWindow {
|
||||
if (this.stopping) throw new Error(`Worker ${this.options.appId} is shutting down`);
|
||||
let closed = false;
|
||||
const surfaceId = `window:${spec.windowId}`;
|
||||
const heightMode = spec.heightMode ?? "min";
|
||||
this.openWindows.add(spec.windowId);
|
||||
@@ -419,6 +464,8 @@ export class WorkerAppHost {
|
||||
hasAppMenu: () => this.windowGestures.get(spec.windowId)?.hasAppMenu ?? false,
|
||||
claimsLongPress: () => this.windowGestures.get(spec.windowId)?.claimsLongPress ?? false,
|
||||
close: () => {
|
||||
if (closed) return;
|
||||
closed = true;
|
||||
this.openWindows.delete(spec.windowId);
|
||||
if (!this.openWindows.size) this.options.navigationSensors?.stop();
|
||||
this.windowGestures.delete(spec.windowId);
|
||||
@@ -428,6 +475,7 @@ export class WorkerAppHost {
|
||||
this.failPendingToolCallsFor(spec.windowId);
|
||||
this.post({ type: "close-window", windowId: spec.windowId });
|
||||
this.options.removeSurface(surfaceId);
|
||||
if (!this.openWindows.size) this.post({ type: "check-idle" });
|
||||
},
|
||||
drawIcon: windowIcon(spec.icon, spec.iconLetter, spec.iconGlyph, () => this.windowIconActivity.get(spec.windowId) ?? "idle"),
|
||||
handleInput: (event, frameId) => {
|
||||
@@ -473,6 +521,7 @@ export class WorkerAppHost {
|
||||
void this.options
|
||||
.configureSurface(surfaceId, false, heightMode)
|
||||
.then(() => {
|
||||
if (closed || this.stopping) return;
|
||||
if (spec.focus) {
|
||||
shell.focusWindow(spec.windowId);
|
||||
}
|
||||
@@ -511,6 +560,7 @@ export class WorkerAppHost {
|
||||
}
|
||||
|
||||
private post(message: WorkerAppMessage): void {
|
||||
if (this.stopping) return;
|
||||
if (!this.workerReady) {
|
||||
this.queuedMessages.push(message);
|
||||
return;
|
||||
|
||||
Reference in new issue
Block a user