@jini-ai/desktop-host 0.6.12 → 0.6.15-rc.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -1,5 +1,16 @@
1
1
  # @jini-ai/desktop-host
2
2
 
3
+ ## 0.6.13
4
+
5
+ ### Patch Changes
6
+
7
+ - Updated dependencies [7479159]
8
+ - Updated dependencies [c31264d]
9
+ - Updated dependencies [0728914]
10
+ - Updated dependencies [6ecbdb2]
11
+ - Updated dependencies [63bacc5]
12
+ - @jini-ai/core@0.6.13
13
+
3
14
  ## 0.6.12
4
15
 
5
16
  ### Patch Changes
@@ -0,0 +1,23 @@
1
+ /** Memory subset of Electron's app.getAppMetrics(); native values are in KiB. */
2
+ export interface ElectronProcessMemory {
3
+ pid: number;
4
+ memory: {
5
+ privateBytes?: number;
6
+ workingSetSize: number;
7
+ };
8
+ }
9
+ /** Replace OS RSS for Electron-owned PIDs with native private memory where available.
10
+ * Non-Electron children (including Electron-as-node) retain OS RSS. macOS/Linux do not expose
11
+ * privateBytes here, so their working set remains a resident-memory estimate. The rssBytes
12
+ * field is retained for wire compatibility; it now carries this mixed memory estimate.
13
+ * @returns New rows, preserving every other sampler field. No native calls or input mutation.
14
+ * @complexity O(p+e) time/O(p+e) space for p sampled and e Electron processes.
15
+ */
16
+ export declare function applyElectronMemoryReadings<T extends {
17
+ pid: number;
18
+ rssBytes: number;
19
+ }>({ processes, electronMetrics }: {
20
+ processes: readonly T[];
21
+ electronMetrics: readonly ElectronProcessMemory[];
22
+ }, _options?: {}): T[];
23
+ //# sourceMappingURL=electron-process-memory.d.ts.map
@@ -0,0 +1,12 @@
1
+ /** Replace OS RSS for Electron-owned PIDs with native private memory where available.
2
+ * Non-Electron children (including Electron-as-node) retain OS RSS. macOS/Linux do not expose
3
+ * privateBytes here, so their working set remains a resident-memory estimate. The rssBytes
4
+ * field is retained for wire compatibility; it now carries this mixed memory estimate.
5
+ * @returns New rows, preserving every other sampler field. No native calls or input mutation.
6
+ * @complexity O(p+e) time/O(p+e) space for p sampled and e Electron processes.
7
+ */
8
+ export function applyElectronMemoryReadings({ processes, electronMetrics }, _options = {}) {
9
+ const memory = new Map(electronMetrics.map(({ pid, memory }) => [pid, (memory.privateBytes ?? memory.workingSetSize) * 1024]));
10
+ return processes.map(row => ({ ...row, rssBytes: memory.get(row.pid) ?? row.rssBytes }));
11
+ }
12
+ //# sourceMappingURL=electron-process-memory.js.map
@@ -36,6 +36,11 @@ export interface ElectronWebRequestLike {
36
36
  }
37
37
  export interface ElectronSessionLike {
38
38
  webRequest: ElectronWebRequestLike;
39
+ /** URL capture requires these native operations before a pooled session can be reused. */
40
+ clearStorageData?(): Promise<void>;
41
+ clearCache?(): Promise<void>;
42
+ clearAuthCache?(): Promise<void>;
43
+ closeAllConnections?(): Promise<void>;
39
44
  }
40
45
  export interface ElectronWebContentsLike {
41
46
  session: ElectronSessionLike;
@@ -6,6 +6,7 @@ export interface ElectronUrlCaptureOptions {
6
6
  }
7
7
  /** Capture a validated own-origin page, bounded in time, CSS pixels and encoded PNG bytes.
8
8
  * The host factory denies popups, downloads and permissions on the private session.
9
+ * FIFO lease waiting and rendering share one deadline; cleanup has its own bounded wait.
9
10
  * @throws RenderServiceError on refusal, timeout or native renderer failure.
10
11
  * @complexity O(pixels), capped at 1280×8000 CSS pixels and device scale 2.
11
12
  */
@@ -1,12 +1,76 @@
1
1
  /** URL extension of RenderService: native Chromium, never a second browser installation.
2
- * Shares the existing render-window lifetime; each URL capture has a private memory session.
2
+ * Shares the existing render-window lifetime and two exclusive, memory-only capture sessions.
3
3
  */
4
- import { randomUUID } from 'node:crypto';
5
- import { RenderServiceError } from '../render-service.js';
4
+ import { RenderServiceError, withRenderTimeout } from '../render-service.js';
6
5
  import { isCaptureUrlAllowed, readUrlCaptureRequest, URL_CAPTURE_MAX_BYTES, URL_CAPTURE_TIMEOUT_MS } from '../url-capture.js';
7
6
  import { withRenderWindow } from './render-window.js';
7
+ // Electron retains partitions for the process lifetime. The leases must therefore span every
8
+ // render service/bridge in this process, without a per-site partition registry.
9
+ const captureSlots = [false, false];
10
+ const captureWaiters = new Set();
11
+ const CAPTURE_CLEANUP_TIMEOUT_MS = 1_000;
12
+ /** Lease a partition in arrival order, charging queued time to the caller's deadline.
13
+ * Timed-out/aborted waiters are removed; a simultaneous handoff returns its lease.
14
+ * @throws RenderServiceError on timeout/abort. @complexity O(1) time/space per waiter.
15
+ */
16
+ async function acquireCaptureSlot({ deadline }, { signal } = {}) {
17
+ if (signal?.aborted)
18
+ throw new RenderServiceError({ code: 'aborted', message: 'render aborted before starting' });
19
+ const slot = captureSlots.indexOf(false);
20
+ if (slot >= 0) {
21
+ captureSlots[slot] = true;
22
+ return slot;
23
+ }
24
+ let assigned;
25
+ let receive;
26
+ const promise = new Promise(resolve => {
27
+ receive = ({ slot }, _options = {}) => { assigned = slot; resolve(slot); };
28
+ captureWaiters.add(receive);
29
+ });
30
+ try {
31
+ return await withRenderTimeout({ promise }, { timeoutMs: Math.max(0, deadline - Date.now()), signal });
32
+ }
33
+ catch (error) {
34
+ if (assigned !== undefined)
35
+ returnCaptureSlot({ slot: assigned });
36
+ throw error;
37
+ }
38
+ finally {
39
+ captureWaiters.delete(receive);
40
+ }
41
+ }
42
+ /** Hand a clean partition straight to the oldest waiter, keeping it exclusive during handoff.
43
+ * @complexity O(1) time/space; the Set preserves insertion order and supports cancellation.
44
+ */
45
+ function returnCaptureSlot({ slot }, _options = {}) {
46
+ const receive = captureWaiters.values().next().value;
47
+ if (!receive) {
48
+ captureSlots[slot] = false;
49
+ return;
50
+ }
51
+ captureWaiters.delete(receive);
52
+ receive({ slot });
53
+ }
54
+ /** Clear native credentials, storage and network state before reuse; failures deny capture.
55
+ * @throws RenderServiceError if the host cannot reset a session. @complexity O(1) native calls.
56
+ */
57
+ async function resetCaptureSession({ session }, _options = {}) {
58
+ if (!session.clearStorageData || !session.clearCache || !session.clearAuthCache || !session.closeAllConnections) {
59
+ throw new RenderServiceError({ code: 'not-implemented', message: 'native capture session cleanup unavailable' });
60
+ }
61
+ try {
62
+ await session.closeAllConnections();
63
+ await session.clearStorageData();
64
+ await session.clearCache();
65
+ await session.clearAuthCache();
66
+ }
67
+ catch {
68
+ throw new RenderServiceError({ code: 'load-failed', message: 'native capture session cleanup failed' });
69
+ }
70
+ }
8
71
  /** Capture a validated own-origin page, bounded in time, CSS pixels and encoded PNG bytes.
9
72
  * The host factory denies popups, downloads and permissions on the private session.
73
+ * FIFO lease waiting and rendering share one deadline; cleanup has its own bounded wait.
10
74
  * @throws RenderServiceError on refusal, timeout or native renderer failure.
11
75
  * @complexity O(pixels), capped at 1280×8000 CSS pixels and device scale 2.
12
76
  */
@@ -15,21 +79,35 @@ export async function captureElectronUrl({ createBrowserWindow, request: input }
15
79
  if (!isCaptureUrlAllowed({ url: request.url, allowedOrigins })) {
16
80
  throw new RenderServiceError({ code: 'navigation-blocked', message: 'capture URL must stay on the site origin' });
17
81
  }
82
+ const deadline = Date.now() + URL_CAPTURE_TIMEOUT_MS;
83
+ const slot = await acquireCaptureSlot({ deadline }, { signal });
84
+ let captureSession;
85
+ let initialReset;
18
86
  let blockedRequests = 0;
19
87
  const factory = (required, options) => {
20
- return createBrowserWindow(required, { ...options, useContentSize: true,
88
+ const window = createBrowserWindow(required, { ...options, useContentSize: true,
21
89
  webPreferences: { ...options?.webPreferences, sandbox: true, nodeIntegration: false,
22
90
  contextIsolation: true, webSecurity: true, backgroundThrottling: false,
23
- partition: `capture-${randomUUID()}` },
91
+ partition: `jini-url-capture-${slot}` },
24
92
  });
93
+ captureSession = window.webContents.session;
94
+ return window;
25
95
  };
26
96
  try {
97
+ if (Date.now() >= deadline)
98
+ throw new RenderServiceError({ code: 'timeout', message: `render timed out after ${URL_CAPTURE_TIMEOUT_MS}ms` });
27
99
  return await withRenderWindow({ createBrowserWindow: factory, url: request.url,
28
- options: { viewport: request.viewport, timeoutMs: URL_CAPTURE_TIMEOUT_MS, ...(signal ? { signal } : {}) },
100
+ options: { viewport: request.viewport, timeoutMs: deadline - Date.now(), ...(signal ? { signal } : {}) },
29
101
  prepare: async (window) => {
102
+ initialReset = resetCaptureSession({ session: window.webContents.session });
103
+ await initialReset;
104
+ if (window.isDestroyed())
105
+ return;
30
106
  // Electron can crash the main process if device emulation targets an unloaded webContents.
31
107
  // Bootstrap before the strict request policy; emulation still precedes site navigation.
32
108
  await window.loadURL({ url: 'about:blank' });
109
+ if (window.isDestroyed())
110
+ return;
33
111
  window.webContents.session.webRequest.onBeforeRequest({ listener: ({ details, callback }) => {
34
112
  const cancel = details.method !== 'GET' || !isCaptureUrlAllowed({ url: details.url, allowedOrigins });
35
113
  if (cancel)
@@ -68,6 +146,28 @@ export async function captureElectronUrl({ createBrowserWindow, request: input }
68
146
  throw error;
69
147
  throw new RenderServiceError({ code: 'load-failed', message: 'native page capture failed' });
70
148
  }
149
+ finally {
150
+ // A stuck reset keeps its lease but must not hold the caller beyond the cleanup budget.
151
+ // Cleanup must not replace a completed capture or its original error near the render deadline.
152
+ await withRenderTimeout({ promise: releaseCaptureSlot({ slot, session: captureSession, initialReset }) }, { timeoutMs: CAPTURE_CLEANUP_TIMEOUT_MS }).catch(() => { });
153
+ }
154
+ }
155
+ /** Return a lease only once its session is reset; the next capture resets again before use.
156
+ * @throws RenderServiceError when the reset fails (the lease is still returned). @complexity O(1).
157
+ */
158
+ async function releaseCaptureSlot({ slot, session, initialReset }, _options = {}) {
159
+ try {
160
+ // Destruction stops navigation first. A timed-out preparation must settle before its
161
+ // cleanup or a new capture can touch the same session.
162
+ await initialReset?.catch(() => { });
163
+ if (session) {
164
+ session.webRequest.onBeforeRequest({ listener: null });
165
+ await resetCaptureSession({ session });
166
+ }
167
+ }
168
+ finally {
169
+ returnCaptureSlot({ slot });
170
+ }
71
171
  }
72
172
  function readPageHeight({ request, rawHeight }, _options = {}) {
73
173
  return request.fullPage && typeof rawHeight === 'number' && Number.isFinite(rawHeight)
@@ -11,6 +11,7 @@ export * from './electron-single-instance.js';
11
11
  export * from './electron-window-lifecycle.js';
12
12
  export * from './electron-protocol.js';
13
13
  export * from './electron-render-service.js';
14
+ export * from './electron-process-memory.js';
14
15
  export * from './electron-shell.js';
15
16
  export * from './create-electron-desktop-host.js';
16
17
  export * from './testing.js';
@@ -11,6 +11,7 @@ export * from './electron-single-instance.js';
11
11
  export * from './electron-window-lifecycle.js';
12
12
  export * from './electron-protocol.js';
13
13
  export * from './electron-render-service.js';
14
+ export * from './electron-process-memory.js';
14
15
  export * from './electron-shell.js';
15
16
  export * from './create-electron-desktop-host.js';
16
17
  export * from './testing.js';
@@ -3,14 +3,19 @@ interface GuestWebPreferences {
3
3
  preload?: string;
4
4
  nodeIntegration?: boolean;
5
5
  contextIsolation?: boolean;
6
+ sandbox?: boolean;
7
+ webSecurity?: boolean;
8
+ allowRunningInsecureContent?: boolean;
9
+ nodeIntegrationInSubFrames?: boolean;
10
+ experimentalFeatures?: boolean;
6
11
  }
7
12
  interface GuestPolicyOptions {
8
13
  preloadPath: string;
9
14
  }
10
- /** Overwrite the supplied guest preferences with the required preload, disabled Node and enabled isolation. Mutates the event object; throws for an empty preload. @complexity O(1). */
15
+ /** Enforce the trusted preload, sandbox, isolation and web security; disable Node and insecure/experimental features. Mutates the event object; throws for an empty preload. @complexity O(1). */
11
16
  declare function applyGuestWebPreferences({ webPreferences, ...options }: GuestPolicyOptions & {
12
17
  webPreferences: GuestWebPreferences;
13
- }): void;
18
+ }, _optionalArgs?: Record<string, never>): void;
14
19
  interface GuestAttachEvent {
15
20
  preventDefault(): void;
16
21
  }
@@ -1,5 +1,5 @@
1
- /** Overwrite the supplied guest preferences with the required preload, disabled Node and enabled isolation. Mutates the event object; throws for an empty preload. @complexity O(1). */
2
- function applyGuestWebPreferences({ webPreferences, ...options }) {
1
+ /** Enforce the trusted preload, sandbox, isolation and web security; disable Node and insecure/experimental features. Mutates the event object; throws for an empty preload. @complexity O(1). */
2
+ function applyGuestWebPreferences({ webPreferences, ...options }, _optionalArgs = {}) {
3
3
  // The page chooses webview attributes before this main-process callback. Unconditionally replace
4
4
  // its preferences; merging its requested values would let the page choose its own privilege grant.
5
5
  // Assign a trusted preload rather than deleting it: embedded admin guests need the same narrow
@@ -10,6 +10,11 @@ function applyGuestWebPreferences({ webPreferences, ...options }) {
10
10
  webPreferences.preload = options.preloadPath;
11
11
  webPreferences.nodeIntegration = false;
12
12
  webPreferences.contextIsolation = true;
13
+ webPreferences.sandbox = true;
14
+ webPreferences.webSecurity = true;
15
+ webPreferences.allowRunningInsecureContent = false;
16
+ webPreferences.nodeIntegrationInSubFrames = false;
17
+ webPreferences.experimentalFeatures = false;
13
18
  }
14
19
  /** Admit only string sources approved by the host predicate. Missing sources and predicate failures prevent attachment. @complexity O(1) beyond the predicate. */
15
20
  function admitGuestSource({ event, params, ...options }) {
@@ -148,8 +148,11 @@ export function createAutoUpdateController(deps, options = {}) {
148
148
  if (shouldCheckNow({ isOwner, lastCheckAt, now: time, busy: checking || readyVersion !== null, intervalMs: timing.checkIntervalMs }))
149
149
  check();
150
150
  }
151
+ /** Request a restart only before staging; a second quit could interrupt Squirrel's handoff.
152
+ * @complexity O(n) live presence records; effects are explanation or a quit request.
153
+ */
151
154
  function requestRestart() {
152
- if (stopped)
155
+ if (stopped || installStarted)
153
156
  return;
154
157
  const count = otherInstances();
155
158
  const action = decideRestartClick({ updateReady: readyVersion !== null, otherInstances: count });
@@ -160,7 +163,10 @@ export function createAutoUpdateController(deps, options = {}) {
160
163
  restartRequested = true;
161
164
  deps.quit();
162
165
  }
163
- function startInstall(silent, relaunch) {
166
+ /** Hand off installation with native flags; false lets the current quit proceed on a sync failure.
167
+ * Logs failures and cancels their fallback; successful handoffs retain it. @complexity O(1).
168
+ */
169
+ function startInstall({ silent, relaunch }, _options = {}) {
164
170
  installStarted = true;
165
171
  updater.autoRunAppAfterInstall = relaunch;
166
172
  // Arm before the handoff so a synchronous failure cannot leave the held quit hanging.
@@ -175,8 +181,10 @@ export function createAutoUpdateController(deps, options = {}) {
175
181
  updater.quitAndInstall({}, { isSilent: silent, isForceRunAfter: relaunch });
176
182
  }
177
183
  catch (error) {
184
+ timers.clear({ timer: fallback });
185
+ handles.splice(handles.indexOf(fallback), 1);
178
186
  log({ message: messages.error({ message: messageOf(error) }) });
179
- deps.quit();
187
+ return false;
180
188
  }
181
189
  return true;
182
190
  }
@@ -204,9 +212,9 @@ export function createAutoUpdateController(deps, options = {}) {
204
212
  if (platform === 'win32' && !installStarted)
205
213
  updater.autoInstallOnAppQuit = action === 'install-on-quit';
206
214
  if (action === 'stage-then-quit')
207
- return startInstall(false, false);
215
+ return startInstall({ silent: false, relaunch: false });
208
216
  if (action === 'install-and-relaunch')
209
- return startInstall(true, true);
217
+ return startInstall({ silent: true, relaunch: true });
210
218
  return false;
211
219
  },
212
220
  willQuit() {
package/dist/sidecar.js CHANGED
@@ -10,7 +10,7 @@
10
10
  * caller-supplied readiness probe until it reports ready — racing the
11
11
  * child's own exit so a sidecar that crashes at startup fails fast instead
12
12
  * of hanging out the full timeout — then, on shutdown, ask the child to
13
- * stop gracefully with a caller-supplied request and fall back to a signal
13
+ * stop gracefully with a caller-supplied request (or SIGTERM by default) and fall back to a signal
14
14
  * kill if it doesn't exit in time. This file rebuilds exactly that,
15
15
  * transport-agnostic (the probe/shutdown-request functions are the
16
16
  * caller's business, not a specific IPC wire format this package invents).
@@ -84,7 +84,10 @@ async function waitUntilReady(child, logPath, options) {
84
84
  child.off('exit', onExit);
85
85
  }
86
86
  }
87
- async function shutdownChild(child, options = {}) {
87
+ /** Use the host's shutdown request or SIGTERM, then bound the wait before SIGKILL. */
88
+ async function shutdownChild({ child }, options = {}) {
89
+ if (child.exitCode !== null || child.signalCode !== null)
90
+ return;
88
91
  if (options.requestShutdown != null) {
89
92
  try {
90
93
  await options.requestShutdown();
@@ -93,6 +96,9 @@ async function shutdownChild(child, options = {}) {
93
96
  // Fall through to process-level termination below.
94
97
  }
95
98
  }
99
+ else {
100
+ child.kill('SIGTERM');
101
+ }
96
102
  const gracefulTimeoutMs = options.gracefulTimeoutMs ?? DEFAULT_GRACEFUL_SHUTDOWN_TIMEOUT_MS;
97
103
  if (await waitForProcessExit(child, gracefulTimeoutMs))
98
104
  return;
@@ -134,7 +140,7 @@ export function createNodeSidecarLauncher(_requiredArgs) {
134
140
  waitUntilReady: (requiredArgs, optionalArgs = {}) => waitUntilReady(child, options.logPath ?? null, { ...optionalArgs, ...requiredArgs }),
135
141
  async shutdown(_requiredArgs, shutdownOptions) {
136
142
  try {
137
- await shutdownChild(child, shutdownOptions);
143
+ await shutdownChild({ child }, shutdownOptions);
138
144
  }
139
145
  finally {
140
146
  await logHandle?.close().catch(() => undefined);
@@ -1,6 +1,7 @@
1
1
  import type { SidecarLauncherPort } from '../sidecar.js';
2
2
  import type { TauriSidecarCommandApi } from './tauri-surfaces.js';
3
+ /** Launch through the injected Tauri API and retain exit status for readiness and teardown. */
3
4
  export declare function createTauriSidecarLauncher({ api }: {
4
5
  api: TauriSidecarCommandApi;
5
- }): SidecarLauncherPort;
6
+ }, _optionalArgs?: Record<string, never>): SidecarLauncherPort;
6
7
  //# sourceMappingURL=tauri-sidecar.d.ts.map
@@ -13,36 +13,35 @@ import { setTimeout as sleep } from 'node:timers/promises';
13
13
  const DEFAULT_READY_TIMEOUT_MS = 35_000;
14
14
  const DEFAULT_POLL_INTERVAL_MS = 150;
15
15
  const DEFAULT_GRACEFUL_SHUTDOWN_TIMEOUT_MS = 5_000;
16
- async function waitForProcessExit(child, timeoutMs) {
17
- return await new Promise((resolve) => {
18
- let exited = false;
19
- child.onExit({ listener: () => {
20
- exited = true;
21
- resolve(true);
22
- } });
23
- setTimeout(() => {
24
- if (!exited)
25
- resolve(false);
26
- }, timeoutMs);
27
- });
16
+ /** Observe the launch-time exit record; clear the deadline when the process exits first. */
17
+ async function waitForProcessExit({ exit }, { timeoutMs = DEFAULT_GRACEFUL_SHUTDOWN_TIMEOUT_MS } = {}) {
18
+ if (exit.info !== null)
19
+ return true;
20
+ let timer;
21
+ try {
22
+ return await Promise.race([
23
+ exit.exited.then(() => true),
24
+ new Promise((resolve) => { timer = setTimeout(() => resolve(false), timeoutMs); }),
25
+ ]);
26
+ }
27
+ finally {
28
+ clearTimeout(timer);
29
+ }
28
30
  }
29
- async function waitUntilReady(child, options) {
31
+ /** Poll readiness while retaining crashes delivered before this call. */
32
+ async function waitUntilReady({ exit, probe, isReady }, options = {}) {
30
33
  const timeoutMs = options.timeoutMs ?? DEFAULT_READY_TIMEOUT_MS;
31
34
  const pollIntervalMs = options.pollIntervalMs ?? DEFAULT_POLL_INTERVAL_MS;
32
35
  const startedAt = Date.now();
33
36
  let lastError;
34
- let exited = null;
35
- child.onExit({ listener: ({ code, signal }) => {
36
- exited = { code, signal };
37
- } });
38
37
  while (Date.now() - startedAt < timeoutMs) {
39
- if (exited !== null) {
40
- const info = exited;
38
+ if (exit.info !== null) {
39
+ const info = exit.info;
41
40
  throw new Error(`sidecar exited before reporting ready (code=${info.code}, signal=${info.signal ?? 'none'})`);
42
41
  }
43
42
  try {
44
- const status = await options.probe();
45
- if (options.isReady({ status }))
43
+ const status = await probe();
44
+ if (isReady({ status }))
46
45
  return status;
47
46
  }
48
47
  catch (error) {
@@ -52,7 +51,10 @@ async function waitUntilReady(child, options) {
52
51
  }
53
52
  throw new Error(`timed out waiting for sidecar to become ready${lastError instanceof Error ? ` (${lastError.message})` : ''}`);
54
53
  }
55
- async function shutdownChild(child, options = {}) {
54
+ /** Use the host's shutdown request or SIGTERM, then bound the wait before SIGKILL. */
55
+ async function shutdownChild({ child, exit }, options = {}) {
56
+ if (exit.info !== null)
57
+ return;
56
58
  if (options.requestShutdown != null) {
57
59
  try {
58
60
  await options.requestShutdown();
@@ -61,17 +63,28 @@ async function shutdownChild(child, options = {}) {
61
63
  // Fall through to process-level termination below.
62
64
  }
63
65
  }
66
+ else {
67
+ child.kill({}, { signal: 'SIGTERM' });
68
+ }
64
69
  const gracefulTimeoutMs = options.gracefulTimeoutMs ?? DEFAULT_GRACEFUL_SHUTDOWN_TIMEOUT_MS;
65
- if (await waitForProcessExit(child, gracefulTimeoutMs))
70
+ if (await waitForProcessExit({ exit }, { timeoutMs: gracefulTimeoutMs }))
66
71
  return;
67
72
  child.kill({}, { signal: 'SIGKILL' });
68
- await waitForProcessExit(child, gracefulTimeoutMs);
73
+ await waitForProcessExit({ exit }, { timeoutMs: gracefulTimeoutMs });
69
74
  }
70
- export function createTauriSidecarLauncher({ api }) {
75
+ /** Launch through the injected Tauri API and retain exit status for readiness and teardown. */
76
+ export function createTauriSidecarLauncher({ api }, _optionalArgs = {}) {
71
77
  return {
72
78
  async launch(requiredArgs, optionalArgs = {}) {
73
79
  const options = { ...optionalArgs, ...requiredArgs };
74
80
  const child = await api.spawnSidecar({ binaryName: options.command, args: options.args ?? [] }, { env: options.env });
81
+ let resolveExit;
82
+ const exit = { info: null, exited: new Promise((resolve) => { resolveExit = resolve; }) };
83
+ // Tauri does not expose exitCode/signalCode: subscribe before handing the child to callers.
84
+ child.onExit({ listener: (info) => {
85
+ exit.info = info;
86
+ resolveExit();
87
+ } });
75
88
  const processHandle = {
76
89
  pid: child.pid,
77
90
  onExit: ({ listener }) => child.onExit({ listener: ({ code, signal }) => listener({ code, signal }) }),
@@ -80,8 +93,8 @@ export function createTauriSidecarLauncher({ api }) {
80
93
  return {
81
94
  process: processHandle,
82
95
  logPath: null,
83
- waitUntilReady: (requiredArgs, optionalArgs = {}) => waitUntilReady(child, { ...optionalArgs, ...requiredArgs }),
84
- shutdown: (_requiredArgs, shutdownOptions) => shutdownChild(child, shutdownOptions),
96
+ waitUntilReady: (requiredArgs, optionalArgs = {}) => waitUntilReady({ exit, ...requiredArgs }, optionalArgs),
97
+ shutdown: (_requiredArgs, shutdownOptions) => shutdownChild({ child, exit }, shutdownOptions),
85
98
  };
86
99
  },
87
100
  };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@jini-ai/desktop-host",
3
- "version": "0.6.12",
3
+ "version": "0.6.15-rc.1",
4
4
  "description": "Shell-agnostic desktop-host ports: single-instance lock, window lifecycle, protocol handling, sidecar launch, paths, and config. Electron and Tauri assemblies live behind ./electron and ./tauri.",
5
5
  "license": "Apache-2.0",
6
6
  "repository": {
@@ -113,10 +113,10 @@
113
113
  },
114
114
  "devDependencies": {
115
115
  "@vitest/coverage-v8": "^2.1.9",
116
- "@jini-ai/core": "^0.6.12"
116
+ "@jini-ai/core": "^0.6.15-rc.1"
117
117
  },
118
118
  "dependencies": {
119
- "@jini-ai/core": "^0.6.12"
119
+ "@jini-ai/core": "^0.6.15-rc.1"
120
120
  },
121
121
  "peerDependencies": {},
122
122
  "peerDependenciesMeta": {},