@agimon-ai/po-native 0.0.1-alpha.7 → 0.0.1-alpha.8

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.
@@ -62,17 +62,18 @@ import type { SealedHttpRequest } from '../adapters/remoteHttp';
62
62
  import type { NativeSocketConstructor } from '../adapters/remoteSocket';
63
63
  import { receiveGrantPause } from '../services/accountClient';
64
64
  import { hostApiPath } from '../services/apiTransport';
65
- import { createBundleCache } from '../services/bundleCache';
65
+ import {
66
+ createNativeBundleUpdates,
67
+ descriptorOf,
68
+ type NativeBundleUpdateChoice,
69
+ type NativeBundleCatalog,
70
+ } from '../services/bundleUpdates';
66
71
  import { type Connection, createConnection } from '../services/connection';
67
72
  import { fetchWithStepUp, type HostRecord, type TrustedSession } from '../services/deviceTrust';
68
73
  import { hostModules, hostModulesForHost } from '../services/hostModules';
69
74
  import { hostSnapshots, type HostSnapshot } from '../services/hostSnapshots';
70
75
  import { bindNativeLogSend } from '../services/logExport';
71
- import {
72
- createPluginRuntime,
73
- type NativeCompositionDescriptor,
74
- type PluginCompatibility,
75
- } from '../services/pluginRuntime';
76
+ import { createPluginRuntime, type PluginCompatibility } from '../services/pluginRuntime';
76
77
  import { type SessionRuntime, startSessionRuntime, whenConnected } from '../services/sessionRuntime';
77
78
  import { createHomeReader, type HomeReader } from './homeState';
78
79
  import { setNativeTemplateChoice } from './nativeTemplate';
@@ -100,45 +101,23 @@ export interface LiveRuntime {
100
101
  searchFiles(sessionId: string, query: string): Promise<string[]>;
101
102
  retryActivity(sessionId: string): void;
102
103
  readonly hasVoiceSession: boolean;
103
- close(): void;
104
+ close(options?: { preserveGlobal?: boolean }): void;
104
105
  }
105
106
 
106
107
  function isRecord(value: unknown): value is Record<string, unknown> {
107
108
  return typeof value === 'object' && value !== null && !Array.isArray(value);
108
109
  }
109
110
 
110
- function descriptorOf(value: unknown): NativeCompositionDescriptor | undefined {
111
- if (!isRecord(value) || typeof value.id !== 'string' || typeof value.revision !== 'number') return undefined;
112
- const plugins = Array.isArray(value.plugins) ? value.plugins.filter((id) => typeof id === 'string') : undefined;
113
- const pluginEntries = Array.isArray(value.pluginEntries)
114
- ? value.pluginEntries.filter(
115
- (entry): entry is [string, string] =>
116
- Array.isArray(entry) && entry.length === 2 && typeof entry[0] === 'string' && typeof entry[1] === 'string',
117
- )
118
- : [];
119
- if (
120
- value.uiEntry !== undefined &&
121
- (typeof value.uiEntry !== 'string' || !/^\/(?!\/)[^?#\\]+\.js$/u.test(value.uiEntry))
122
- )
123
- return undefined;
124
- return {
125
- id: value.id,
126
- revision: value.revision,
127
- plugins,
128
- pluginEntries,
129
- ...(typeof value.uiEntry === 'string' ? { uiEntry: value.uiEntry } : {}),
130
- };
131
- }
132
-
133
111
  /** Wires connection, hub frames, session runtime and native compositions for one trusted session. */
134
112
  export function startLiveRuntime(
135
- session: TrustedSession,
113
+ session: TrustedSession | Promise<TrustedSession>,
136
114
  host: HostRecord,
137
115
  onReconnectNeeded: () => void,
138
116
  receiveActivityLoad: (owner: string, state: ActivityLoadState) => void = () => {},
139
117
  options: {
140
118
  observeCompositions?: (body: unknown, request: (request: SealedHttpRequest) => Promise<Response>) => void;
141
119
  onUpdateRequired?: () => void;
120
+ onBundleUpdate?: (choice: NativeBundleUpdateChoice) => void;
142
121
  onSummariesLoaded?: () => void;
143
122
  onPluginCompatibility?: (issues: readonly PluginCompatibility[]) => void;
144
123
  /** Network-authenticated host id, not the phone's local pairing record id. */
@@ -191,7 +170,7 @@ export function startLiveRuntime(
191
170
  };
192
171
  const readHome: Parameters<typeof createHomeReader>[0] = (request, signal) => {
193
172
  if (!ready) throw new Error('Home summaries are not connected.');
194
- return connection.hub.readHome(request, signal);
173
+ return connection!.hub.readHome(request, signal);
195
174
  };
196
175
  const home = createHomeReader(readHome);
197
176
  const attentionHome = createHomeReader(readHome);
@@ -237,7 +216,7 @@ export function startLiveRuntime(
237
216
  if (focused !== null) watched.add(focused);
238
217
  for (const sessionId of subscribed) if (!watched.has(sessionId)) endSessionReplay(sessionId);
239
218
  subscribed = watched;
240
- connection.hub.watchSessions(watched);
219
+ connection!.hub.watchSessions(watched);
241
220
  };
242
221
 
243
222
  const dropSession = (sessionId: string) => {
@@ -250,6 +229,7 @@ export function startLiveRuntime(
250
229
  if (focused === sessionId) openSession(null);
251
230
  const target = sessionMounts.get(sessionId);
252
231
  sessionMounts.delete(sessionId);
232
+ selectedSessions.delete(sessionId);
253
233
  if (target) plugins.unmount(target);
254
234
  removeSessionWebPlugins(sessionId);
255
235
  subscribed.delete(sessionId);
@@ -257,10 +237,33 @@ export function startLiveRuntime(
257
237
 
258
238
  // Phones have no browser WebMCP, so plugin tools (such as Author's canvas) register on the in-app simulator.
259
239
  const modelContext = createWebMcpSimulator();
240
+ const updates = createNativeBundleUpdates({
241
+ hostId: host.id,
242
+ signerPublicKey: host.signer.publicKey,
243
+ async fetchComposition(descriptor, entryPath) {
244
+ const manifest = await request({ method: 'GET', target: descriptor.manifestUrl });
245
+ if (!manifest.ok) throw new Error(`Composition ${descriptor.id} manifest is unavailable.`);
246
+ const asset = await request({
247
+ method: 'GET',
248
+ target: `${descriptor.rawAssetBaseUrl.replace(/\/+$/u, '')}${entryPath}`,
249
+ });
250
+ if (!asset.ok) throw new Error(`Composition ${descriptor.id} module ${entryPath} is unavailable.`);
251
+ return { signed: await manifest.json(), source: new Uint8Array(await asset.arrayBuffer()) };
252
+ },
253
+ onError(error) {
254
+ if (!closed)
255
+ onActivityLoad('catalog', {
256
+ loading: false,
257
+ error: error instanceof Error ? error.message : 'Cached activity is unavailable.',
258
+ });
259
+ reportMountFailure(error);
260
+ },
261
+ });
262
+ const selectedSessions = new Map<string, unknown>();
260
263
  const plugins = createPluginRuntime({
261
264
  hostId: host.id,
262
- cache: createBundleCache({ signerPublicKey: host.signer.publicKey, hostId: host.id }),
263
- hostModules: host.id === undefined ? hostModules : hostModulesForHost(host.id),
265
+ cache: updates.cache,
266
+ hostModules: host.id === undefined ? hostModules : hostModulesForHost(host.id, host.signer.publicKey),
264
267
  onCompatibility(issues) {
265
268
  if (closed) return;
266
269
  options.onPluginCompatibility?.(issues);
@@ -294,112 +297,126 @@ export function startLiveRuntime(
294
297
  async fetchComposition(descriptor, entryPath) {
295
298
  const composition = compositions.get(descriptor.id);
296
299
  if (!composition) throw new Error(`Composition ${descriptor.id} is not advertised by the host.`);
297
- const manifest = await connection.request({ method: 'GET', target: composition.manifestUrl });
300
+ const manifest = await request({ method: 'GET', target: composition.manifestUrl });
298
301
  if (!manifest.ok) throw new Error(`Composition ${descriptor.id} manifest is unavailable.`);
299
302
  const base = composition.rawAssetBaseUrl.replace(/\/+$/u, '');
300
- const asset = await connection.request({ method: 'GET', target: `${base}${entryPath}` });
303
+ const asset = await request({ method: 'GET', target: `${base}${entryPath}` });
301
304
  if (!asset.ok) throw new Error(`Composition ${descriptor.id} module ${entryPath} is unavailable.`);
302
305
  return { signed: await manifest.json(), source: new Uint8Array(await asset.arrayBuffer()) };
303
306
  },
304
307
  });
305
308
 
306
- const connection: Connection = createConnection({
307
- hostId: host.id,
308
- http: session.http,
309
- channels: session.channels,
310
- sealed: session.sealed,
311
- // React Native's WebSocket takes (url, protocols, { headers }); the DOM lib typing omits the third argument.
312
- Socket: WebSocket as unknown as NativeSocketConstructor,
313
- onSessions(sessions) {
314
- if (closed) return;
315
- clearVoiceReconnect();
316
- lastKnown.sessions = sessions;
317
- persist();
318
- const present = new Set(sessions.map((summary) => summary.id));
319
- for (const sessionId of Object.keys(sessionsStore.state.byId))
320
- if (owned(sessionId) && !present.has(sessionId)) dropSession(sessionId);
321
- applySessionsSnapshot({ sessions }, host.id);
322
- options.onSummariesLoaded?.();
323
- if (!ready) {
324
- ready = true;
325
- home.setSupported(true);
326
- attentionHome.setSupported(true);
327
- resubscribeThreads();
328
- }
329
- // Session metadata may arrive after navigation, or change when a session wakes.
330
- if (focused !== null) applyFocus();
331
- syncSubscription();
332
- },
333
- // The session list groups by workspace.
334
- onWorkspaces(workspaces) {
335
- if (closed) return;
336
- lastKnown.workspaces = workspaces;
337
- persist();
338
- const present = new Set(workspaces.map((workspace) => workspace.id));
339
- for (const workspaceId of workspaceIds) {
340
- if (present.has(workspaceId)) continue;
341
- home.clear();
342
- attentionHome.clear();
343
- plugins.unmount({ scope: 'workspace', workspaceId });
344
- mountedWorkspaces.delete(workspaceId);
345
- }
346
- workspaceIds = present;
347
- applyWorkspacesSnapshot({ workspaces }, host.id);
348
- },
349
- onNotice(sessionId, frame) {
350
- if (
351
- (options.federationHostId ?? host.federationHostId) &&
352
- frame.type === 'po/federation/work-paused' &&
353
- typeof frame.workId === 'string' &&
354
- typeof frame.grantId === 'string' &&
355
- (frame.reason === 'refresh-refused' || frame.reason === 'grant-expired')
356
- ) {
357
- void receiveGrantPause(
358
- frame as unknown as FederationWorkPaused,
359
- (options.federationHostId ?? host.federationHostId)!,
360
- ).catch((error: unknown) => console.warn('Shared work notice unavailable:', error));
361
- }
362
- if (frame.type !== 'extension_ui_request' && sessionId !== sessionsStore.state.activeId)
363
- applyPresentationFrame(sessionId, frame, false);
364
- },
365
- onThreadFrame(sessionId, threadId, frame) {
366
- if (!applyThreadTranscriptFrame(sessionId, threadId, frame))
367
- applySessionFrame(threadStoreKey(sessionId, threadId), frame);
368
- },
369
- // Any other channel frame may belong to a plugin.
370
- onChannel: (frame) => plugins.dispatch(frame),
371
- // A republished global or workspace composition swaps in place; the app itself is not reloaded.
372
- onCompositions() {
373
- if (!closed) void loadCompositions();
374
- },
375
- onReconnectNeeded() {
376
- ready = false;
377
- home.setSupported(null);
378
- attentionHome.setSupported(null);
379
- markSocketClosed(host.id);
380
- if (closed) return;
381
- if (!hasVoiceSession()) {
382
- replaceConnection();
383
- return;
384
- }
385
- // ponytail: In-place recovery has a 15-second ceiling, the voice lease, before full replacement.
386
- if (voiceReconnect === undefined) voiceReconnect = setTimeout(replaceConnection, 15_000);
387
- },
388
- // Re-authenticating cannot help an app older than the server, so this shows the notice and stays down.
389
- onUpdateRequired() {
390
- clearVoiceReconnect();
391
- ready = false;
392
- home.setSupported(null);
393
- attentionHome.setSupported(null);
394
- markUpdateRequired(host.id);
395
- disconnectHostCaptures();
396
- options.onUpdateRequired?.();
397
- },
398
- });
309
+ const connect = (session: TrustedSession): Connection =>
310
+ createConnection({
311
+ hostId: host.id,
312
+ http: session.http,
313
+ channels: session.channels,
314
+ sealed: session.sealed,
315
+ // React Native's WebSocket takes (url, protocols, { headers }); the DOM lib typing omits the third argument.
316
+ Socket: WebSocket as unknown as NativeSocketConstructor,
317
+ onSessions(sessions) {
318
+ if (closed) return;
319
+ clearVoiceReconnect();
320
+ lastKnown.sessions = sessions;
321
+ persist();
322
+ const present = new Set(sessions.map((summary) => summary.id));
323
+ for (const sessionId of Object.keys(sessionsStore.state.byId))
324
+ if (owned(sessionId) && !present.has(sessionId)) dropSession(sessionId);
325
+ applySessionsSnapshot({ sessions }, host.id);
326
+ options.onSummariesLoaded?.();
327
+ if (!ready) {
328
+ ready = true;
329
+ home.setSupported(true);
330
+ attentionHome.setSupported(true);
331
+ resubscribeThreads();
332
+ }
333
+ // Session metadata may arrive after navigation, or change when a session wakes.
334
+ if (focused !== null) applyFocus();
335
+ syncSubscription();
336
+ },
337
+ // The session list groups by workspace.
338
+ onWorkspaces(workspaces) {
339
+ if (closed) return;
340
+ lastKnown.workspaces = workspaces;
341
+ persist();
342
+ const present = new Set(workspaces.map((workspace) => workspace.id));
343
+ for (const workspaceId of workspaceIds) {
344
+ if (present.has(workspaceId)) continue;
345
+ home.clear();
346
+ attentionHome.clear();
347
+ plugins.unmount({ scope: 'workspace', workspaceId });
348
+ mountedWorkspaces.delete(workspaceId);
349
+ }
350
+ workspaceIds = present;
351
+ applyWorkspacesSnapshot({ workspaces }, host.id);
352
+ },
353
+ onNotice(sessionId, frame) {
354
+ if (
355
+ (options.federationHostId ?? host.federationHostId) &&
356
+ frame.type === 'po/federation/work-paused' &&
357
+ typeof frame.workId === 'string' &&
358
+ typeof frame.grantId === 'string' &&
359
+ (frame.reason === 'refresh-refused' || frame.reason === 'grant-expired')
360
+ ) {
361
+ void receiveGrantPause(
362
+ frame as unknown as FederationWorkPaused,
363
+ (options.federationHostId ?? host.federationHostId)!,
364
+ ).catch((error: unknown) => console.warn('Shared work notice unavailable:', error));
365
+ }
366
+ if (frame.type !== 'extension_ui_request' && sessionId !== sessionsStore.state.activeId)
367
+ applyPresentationFrame(sessionId, frame, false);
368
+ },
369
+ onThreadFrame(sessionId, threadId, frame) {
370
+ if (!applyThreadTranscriptFrame(sessionId, threadId, frame))
371
+ applySessionFrame(threadStoreKey(sessionId, threadId), frame);
372
+ },
373
+ // Any other channel frame may belong to a plugin.
374
+ onChannel: (frame) => plugins.dispatch(frame),
375
+ // A republished global or workspace composition swaps in place; the app itself is not reloaded.
376
+ onCompositions() {
377
+ if (!closed) void loadCompositions();
378
+ },
379
+ onReconnectNeeded() {
380
+ ready = false;
381
+ home.setSupported(null);
382
+ attentionHome.setSupported(null);
383
+ markSocketClosed(host.id);
384
+ if (closed) return;
385
+ if (!hasVoiceSession()) {
386
+ replaceConnection();
387
+ return;
388
+ }
389
+ // ponytail: In-place recovery has a 15-second ceiling, the voice lease, before full replacement.
390
+ if (voiceReconnect === undefined) voiceReconnect = setTimeout(replaceConnection, 15_000);
391
+ },
392
+ // Re-authenticating cannot help an app older than the server, so this shows the notice and stays down.
393
+ onUpdateRequired() {
394
+ clearVoiceReconnect();
395
+ ready = false;
396
+ home.setSupported(null);
397
+ attentionHome.setSupported(null);
398
+ markUpdateRequired(host.id);
399
+ disconnectHostCaptures();
400
+ options.onUpdateRequired?.();
401
+ },
402
+ });
403
+ let connection: Connection | undefined;
404
+ const connectionReady =
405
+ session instanceof Promise
406
+ ? session.then((trusted) => {
407
+ if (closed) throw new Error('The host connection was closed.');
408
+ connection = connect(trusted);
409
+ return connection;
410
+ })
411
+ : Promise.resolve((connection = connect(session)));
412
+ const request: Connection['request'] = async (...args) => {
413
+ const connected = await connectionReady;
414
+ if (closed) throw new Error('The host connection was closed.');
415
+ return connected.request(...args);
416
+ };
399
417
  // The phone's warnings and errors go to this host's log sink while it is connected.
400
418
  const unbindLogs = bindNativeLogSend(
401
- (target, body) =>
402
- connection.request({ method: 'POST', target, headers: [['content-type', 'application/json']], body }),
419
+ (target, body) => request({ method: 'POST', target, headers: [['content-type', 'application/json']], body }),
403
420
  host.id,
404
421
  );
405
422
  const mountedWorkspaces = new Set<string>();
@@ -411,6 +428,18 @@ export function startLiveRuntime(
411
428
  : target.scope === 'workspace'
412
429
  ? `workspace:${target.workspaceId}`
413
430
  : 'global';
431
+ if (target.scope === 'session') {
432
+ const previous = selectedSessions.get(target.sessionId);
433
+ if (previous) composition = previous;
434
+ else {
435
+ const candidate = descriptorOf(composition);
436
+ if (!candidate) return;
437
+ const selected = await updates.selectSession(candidate);
438
+ if (!selected || closed || sessionMounts.get(target.sessionId) !== target) return;
439
+ composition = { ...(composition as SessionNativeComposition), ...selected };
440
+ selectedSessions.set(target.sessionId, composition);
441
+ }
442
+ }
414
443
  const descriptor = descriptorOf(composition);
415
444
  if (!descriptor) {
416
445
  plugins.unmount(target);
@@ -447,58 +476,113 @@ export function startLiveRuntime(
447
476
  }
448
477
  };
449
478
 
450
- const runtime: SessionRuntime = startSessionRuntime(
451
- connection.client,
452
- applyPresentationFrame,
453
- host.id,
454
- applyToolFrame,
455
- () => AppState.currentState === 'active' || hasVoiceSession(),
456
- (error) => {
457
- if (voiceReconnect === undefined) return;
458
- const message = error instanceof Error ? error.message : String(error);
459
- if (/\b(?:401|403)\b|unauthori[sz]ed|forbidden|paired sealed protocol channel/iu.test(message))
460
- replaceConnection();
461
- },
462
- );
479
+ let runtime: SessionRuntime | undefined;
480
+ const attachRuntime = () => {
481
+ if (closed) return;
482
+ runtime = startSessionRuntime(
483
+ connection!.client,
484
+ applyPresentationFrame,
485
+ host.id,
486
+ applyToolFrame,
487
+ () => AppState.currentState === 'active' || hasVoiceSession(),
488
+ (error) => {
489
+ if (voiceReconnect === undefined) return;
490
+ const message = error instanceof Error ? error.message : String(error);
491
+ if (/\b(?:401|403)\b|unauthori[sz]ed|forbidden|paired sealed protocol channel/iu.test(message))
492
+ replaceConnection();
493
+ },
494
+ );
495
+ if (focused !== null) applyFocus();
496
+ };
497
+ if (connection) attachRuntime();
498
+ else void connectionReady.then(attachRuntime).catch(reportMountFailure);
463
499
 
500
+ const applyCatalog = async (catalog: NativeBundleCatalog) => {
501
+ if (closed) return;
502
+ await mount({ scope: 'global' }, catalog.nativeGlobal);
503
+ if (closed) return;
504
+ const present = new Set(
505
+ catalog.workspaces.map((w) => (host.id === undefined ? w.id : qualifyHostId(host.id, w.id))),
506
+ );
507
+ for (const workspaceId of mountedWorkspaces) {
508
+ if (present.has(workspaceId)) continue;
509
+ plugins.unmount({ scope: 'workspace', workspaceId });
510
+ mountedWorkspaces.delete(workspaceId);
511
+ home.clear();
512
+ attentionHome.clear();
513
+ }
514
+ for (const workspace of catalog.workspaces) {
515
+ if (closed) return;
516
+ const workspaceId = host.id === undefined ? workspace.id : qualifyHostId(host.id, workspace.id);
517
+ mountedWorkspaces.add(workspaceId);
518
+ await mount({ scope: 'workspace', workspaceId }, workspace.nativeComposition);
519
+ }
520
+ };
521
+ const startup = updates
522
+ .startup()
523
+ .then(async (catalog) => {
524
+ if (catalog && !closed) {
525
+ await applyCatalog(catalog);
526
+ if (!closed) applyFocus();
527
+ }
528
+ })
529
+ .catch((error: unknown) => {
530
+ if (!closed) reportMountFailure(error);
531
+ });
464
532
  const loadCompositions = async () => {
465
533
  const epoch = (loadEpochs.get('catalog') ?? 0) + 1;
466
534
  loadEpochs.set('catalog', epoch);
467
535
  const current = () => !closed && loadEpochs.get('catalog') === epoch;
468
536
  onActivityLoad('catalog', { loading: true });
469
537
  try {
470
- const response = await connection.request({ method: 'GET', target: COMPOSITIONS_ROUTE });
538
+ await startup;
539
+ if (!current()) return;
540
+ const response = await request({ method: 'GET', target: COMPOSITIONS_ROUTE });
471
541
  const body: unknown = await response.json();
472
542
  if (!current()) return;
473
543
  if (!response.ok || !isRecord(body)) throw new Error('Activity extensions are unavailable.');
474
- if (options.observeCompositions) options.observeCompositions(body, connection.request);
475
- setNativeTemplateChoice(body.nativeTemplate, host.id);
476
- await mount({ scope: 'global' }, body.nativeGlobal);
477
- if (!Array.isArray(body.workspaces)) {
478
- if (current()) onActivityLoad('catalog', { loading: false });
479
- return;
480
- }
481
- const workspaceIds = new Set(
482
- body.workspaces.flatMap((workspace) =>
483
- isRecord(workspace) && typeof workspace.id === 'string'
484
- ? [host.id === undefined ? workspace.id : qualifyHostId(host.id, workspace.id)]
485
- : [],
486
- ),
487
- );
488
- for (const workspaceId of mountedWorkspaces) {
489
- if (workspaceIds.has(workspaceId)) continue;
490
- plugins.unmount({ scope: 'workspace', workspaceId });
491
- mountedWorkspaces.delete(workspaceId);
492
- home.clear();
493
- attentionHome.clear();
544
+ options.observeCompositions?.(body, request);
545
+ const result = await updates.check(body);
546
+ if (!current()) return;
547
+ if (result.catalog) {
548
+ setNativeTemplateChoice(body.nativeTemplate, host.id);
549
+ await applyCatalog(result.catalog);
550
+ if (current()) applyFocus();
494
551
  }
495
- for (const workspace of body.workspaces) {
496
- if (!current()) return;
497
- if (isRecord(workspace) && typeof workspace.id === 'string') {
498
- const workspaceId = host.id === undefined ? workspace.id : qualifyHostId(host.id, workspace.id);
499
- mountedWorkspaces.add(workspaceId);
500
- await mount({ scope: 'workspace', workspaceId }, workspace.nativeComposition);
501
- }
552
+ if (result.update) {
553
+ const run = async (install: () => Promise<void>, now: boolean) => {
554
+ try {
555
+ if (closed) return;
556
+ await install();
557
+ if (closed) return;
558
+ if (now) {
559
+ const catalog = await updates.catalog();
560
+ if (catalog && !closed) {
561
+ selectedSessions.clear();
562
+ await applyCatalog(catalog);
563
+ if (!closed) applyFocus();
564
+ }
565
+ }
566
+ } catch (error) {
567
+ if (current())
568
+ onActivityLoad('catalog', {
569
+ loading: false,
570
+ error: error instanceof Error ? error.message : 'Activity update failed.',
571
+ });
572
+ reportMountFailure(error);
573
+ throw error;
574
+ }
575
+ };
576
+ const choice: NativeBundleUpdateChoice = {
577
+ installNow: () => run(result.update!.installNow, true),
578
+ installOnNextStart: () => run(result.update!.installOnNextStart, false),
579
+ };
580
+ if (options.onBundleUpdate) options.onBundleUpdate(choice);
581
+ else
582
+ onActivityLoad('bundle-update', {
583
+ loading: false,
584
+ error: 'An activity update is available. Reconnect to choose when to install it.',
585
+ });
502
586
  }
503
587
  if (current()) onActivityLoad('catalog', { loading: false });
504
588
  } catch (error) {
@@ -516,10 +600,10 @@ export function startLiveRuntime(
516
600
  /** A stopped session has no runtime to attach to: its history is read from disk, as the cockpit does. */
517
601
  let dormant: { sessionId: string; dispose: () => void } | undefined;
518
602
 
519
- const readDormantPage = async (sessionId: string, request: TranscriptPageRequest): Promise<TranscriptPage> => {
520
- const response = await connection.request({
603
+ const readDormantPage = async (sessionId: string, pageRequest: TranscriptPageRequest): Promise<TranscriptPage> => {
604
+ const response = await request({
521
605
  method: 'GET',
522
- target: `${hostPath(sessionId, '/transcript')}${transcriptPageQuery(request)}`,
606
+ target: `${hostPath(sessionId, '/transcript')}${transcriptPageQuery(pageRequest)}`,
523
607
  });
524
608
  const body: unknown = await response.json().catch(() => undefined);
525
609
  if (!response.ok) {
@@ -557,10 +641,10 @@ export function startLiveRuntime(
557
641
  }
558
642
  if (dormant && (dormant.sessionId !== sessionId || !isDormant)) disposeDormant();
559
643
  if (!isDormant || sessionId === null) {
560
- runtime.focus(sessionId);
644
+ runtime?.focus(sessionId);
561
645
  return;
562
646
  }
563
- runtime.focus(null);
647
+ runtime?.focus(null);
564
648
  if (dormant) return;
565
649
  const transcript = createPagedTranscript(
566
650
  sessionId,
@@ -643,7 +727,7 @@ export function startLiveRuntime(
643
727
  },
644
728
  async searchFiles(sessionId, query) {
645
729
  try {
646
- const response = await connection.request({
730
+ const response = await request({
647
731
  method: 'GET',
648
732
  target: `${hostPath(sessionId, '/plugins/files')}?q=${encodeURIComponent(query)}`,
649
733
  });
@@ -656,14 +740,16 @@ export function startLiveRuntime(
656
740
  return []; // Completion is a convenience; a failed lookup just shows nothing, as in the cockpit.
657
741
  }
658
742
  },
659
- close() {
743
+ close({ preserveGlobal = false } = {}) {
660
744
  if (closed) return;
661
745
  closed = true;
746
+ updates.close();
662
747
  clearVoiceReconnect();
663
748
  stopHeldChannels.unsubscribe();
664
749
  stopVoiceSessions.unsubscribe();
665
750
  stopTransientTabs.unsubscribe();
666
751
  sessionMounts.clear();
752
+ selectedSessions.clear();
667
753
  completionTabs.dispose();
668
754
  if (--liveHosts === 0) {
669
755
  stopFileLinkModes?.();
@@ -681,11 +767,11 @@ export function startLiveRuntime(
681
767
  activateWebPluginSession(null);
682
768
  activateWebPluginWorkspace(null);
683
769
  }
684
- plugins.stop();
770
+ plugins.stop(preserveGlobal);
685
771
  modelContext.dispose();
686
- runtime.stop();
772
+ runtime?.stop();
687
773
  unbindLogs();
688
- connection.close();
774
+ connection?.close();
689
775
  },
690
776
  };
691
777
  }