@shellui/core 0.3.0 → 0.4.0

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.
Files changed (75) hide show
  1. package/package.json +2 -2
  2. package/src/app.tsx +31 -3
  3. package/src/components/ui/dialog.tsx +26 -6
  4. package/src/components/ui/sonner.tsx +9 -5
  5. package/src/features/admin/AdminView.tsx +5 -49
  6. package/src/features/admin/config.ts +15 -0
  7. package/src/features/admin/index.ts +4 -0
  8. package/src/features/admin/routes.tsx +14 -0
  9. package/src/features/admin/utils.ts +79 -0
  10. package/src/features/auth/AuthProvider.tsx +68 -13
  11. package/src/features/auth/backends/shellui.ts +8 -1
  12. package/src/features/auth/components/AccessPendingView.tsx +112 -0
  13. package/src/features/auth/components/LoginButton.tsx +5 -10
  14. package/src/features/auth/components/LoginView.tsx +20 -2
  15. package/src/features/auth/components/OAuthCallbackView.tsx +211 -50
  16. package/src/features/auth/hooks/useAuth.tsx +8 -1
  17. package/src/features/auth/utils/authRequestError.spec.ts +52 -0
  18. package/src/features/auth/utils/authRequestError.ts +45 -0
  19. package/src/features/auth/utils/buildAuthUrlWithNext.spec.ts +18 -0
  20. package/src/features/auth/utils/buildAuthUrlWithNext.ts +12 -0
  21. package/src/features/auth/utils/index.ts +8 -0
  22. package/src/features/auth/utils/isTokenAutoRefreshDisabled.spec.ts +71 -0
  23. package/src/features/auth/utils/isTokenAutoRefreshDisabled.ts +18 -0
  24. package/src/features/config/ConfigProvider.ts +1 -1
  25. package/src/features/config/types.ts +46 -5
  26. package/src/features/layouts/AppLayout.tsx +3 -3
  27. package/src/features/layouts/OverlayShell.tsx +17 -28
  28. package/src/features/layouts/resolveSdkNavigatePath.spec.ts +55 -0
  29. package/src/features/layouts/resolveSdkNavigatePath.ts +68 -0
  30. package/src/features/settings/SettingsIcons.tsx +35 -0
  31. package/src/features/settings/SettingsProvider.tsx +79 -10
  32. package/src/features/settings/SettingsRoutes.tsx +14 -6
  33. package/src/features/settings/SettingsView.tsx +11 -5
  34. package/src/features/settings/components/Advanced.tsx +117 -44
  35. package/src/features/settings/components/Develop.tsx +38 -0
  36. package/src/features/settings/components/ServiceWorker.tsx +52 -25
  37. package/src/features/settings/components/Storage.tsx +138 -0
  38. package/src/features/settings/components/UpdateApp.tsx +1 -1
  39. package/src/features/settings/components/develop/StoragePickerTestButtons.tsx +148 -0
  40. package/src/features/settings/components/develop/UploadToastTestButton.tsx +29 -0
  41. package/src/features/settings/utils/buildSettingsForPropagation.spec.ts +55 -1
  42. package/src/features/settings/utils/buildSettingsForPropagation.ts +34 -0
  43. package/src/features/settings/utils/mergePreferencesIntoSettings.spec.ts +1 -1
  44. package/src/features/settings/utils/toSettingsUser.spec.ts +4 -0
  45. package/src/features/settings/utils/toSettingsUser.ts +2 -0
  46. package/src/features/sonner/SonnerContext.tsx +44 -60
  47. package/src/features/storage/StorageBridge.tsx +50 -0
  48. package/src/features/storage/StoragePickerContext.tsx +214 -0
  49. package/src/features/storage/api.spec.ts +303 -0
  50. package/src/features/storage/api.ts +414 -0
  51. package/src/features/storage/handleRequest.spec.ts +88 -0
  52. package/src/features/storage/handleRequest.ts +53 -0
  53. package/src/features/storage/quota.spec.ts +151 -0
  54. package/src/features/storage/quota.ts +104 -0
  55. package/src/features/storage/uploads/UploadToastCard.tsx +442 -0
  56. package/src/features/storage/uploads/UploadToaster.tsx +41 -0
  57. package/src/features/storage/uploads/handleTrackedUpload.spec.ts +170 -0
  58. package/src/features/storage/uploads/handleTrackedUpload.ts +97 -0
  59. package/src/features/storage/uploads/types.ts +24 -0
  60. package/src/features/storage/uploads/uploadQueue.spec.ts +118 -0
  61. package/src/features/storage/uploads/uploadQueue.ts +349 -0
  62. package/src/features/storage/uploads/useUploadQueue.ts +30 -0
  63. package/src/i18n/translations/en/common.json +33 -0
  64. package/src/i18n/translations/en/settings.json +56 -4
  65. package/src/i18n/translations/fr/common.json +33 -0
  66. package/src/i18n/translations/fr/settings.json +56 -4
  67. package/src/index.css +2 -1
  68. package/src/index.ts +2 -0
  69. package/src/lib/z-index.ts +9 -3
  70. package/src/routes/components/NavigationItemRoute.tsx +2 -1
  71. package/src/routes/routes.tsx +2 -13
  72. package/src/service-worker/register.ts +217 -101
  73. package/src/service-worker/sw-dev.ts +5 -1
  74. package/src/service-worker/sw.ts +5 -1
  75. package/src/shellui-target.d.ts +2 -0
package/src/index.ts CHANGED
@@ -19,6 +19,8 @@ export type {
19
19
  LayoutType,
20
20
  BackendType,
21
21
  BackendConfig,
22
+ AdministrationConfig,
23
+ StorageConfig,
22
24
  CookieConsentCategory,
23
25
  CookieDefinition,
24
26
  CookieConsentConfig,
@@ -1,6 +1,6 @@
1
1
  /**
2
2
  * Central z-index scale for overlay layers.
3
- * Order (bottom to top): modal/drawer → toast → alert-dialog.
3
+ * Order (bottom to top): modal/drawer → toast → tooltip → alert-dialog.
4
4
  * Use these constants everywhere so stacking stays consistent.
5
5
  */
6
6
  export const Z_INDEX = {
@@ -9,16 +9,22 @@ export const Z_INDEX = {
9
9
  /** Modal overlay and content (settings panel, etc.) */
10
10
  MODAL_OVERLAY: 10000,
11
11
  MODAL_CONTENT: 10001,
12
- /** Tooltip content (above modals so tooltips show over dialogs if needed) */
13
- TOOLTIP: 10002,
14
12
  /** Drawer overlay and content (slide-out panels; same level as modal) */
15
13
  DRAWER_OVERLAY: 10000,
16
14
  DRAWER_CONTENT: 10001,
17
15
  /** Toasts (above modals so they stay clickable when modal is open) */
18
16
  TOAST: 10100,
17
+ /** Tooltip content (above toasts so labels on the upload toaster stay visible) */
18
+ TOOLTIP: 10150,
19
19
  /** Alert dialog overlay and content (confirmations; above toasts) */
20
20
  ALERT_DIALOG_OVERLAY: 10200,
21
21
  ALERT_DIALOG_CONTENT: 10201,
22
+ /**
23
+ * Storage file/folder picker (stacks above the generic URL modal so Develop
24
+ * inside Settings can open a picker without replacing settings).
25
+ */
26
+ STORAGE_PICKER_OVERLAY: 10050,
27
+ STORAGE_PICKER_CONTENT: 10051,
22
28
  /** Cookie consent (above everything to ensure visibility) */
23
29
  COOKIE_CONSENT_OVERLAY: 10300,
24
30
  COOKIE_CONSENT_CONTENT: 10301,
@@ -3,6 +3,7 @@ import { useNavigationItems } from '../hooks/useNavigationItems';
3
3
  import { NotFoundView } from './NotFoundView';
4
4
  import { Navigate, useLocation } from 'react-router';
5
5
  import urls from '../../constants/urls';
6
+ import { buildAuthUrlWithNext } from '../../features/auth/utils';
6
7
  import { useAuth } from '../../features/auth/hooks/useAuth';
7
8
  import { RouteFallback } from './RouteFallback';
8
9
 
@@ -30,7 +31,7 @@ export const NavigationItemRoute = () => {
30
31
  }
31
32
  if (!isAuthenticated) {
32
33
  const next = `${location.pathname}${location.search}`;
33
- const loginUrl = `${urls.login}?next=${encodeURIComponent(next)}`;
34
+ const loginUrl = buildAuthUrlWithNext(urls.login, next);
34
35
  return (
35
36
  <Navigate
36
37
  to={loginUrl}
@@ -5,6 +5,7 @@ import { RouteErrorBoundary } from './components/RouteErrorBoundary';
5
5
  import { AppLayout } from '../features/layouts/AppLayout';
6
6
  import { flattenNavigationItems } from '../features/layouts/utils';
7
7
  import urls from '../constants/urls';
8
+ import { createAdminRoute } from '../features/admin/routes';
8
9
  import { RouteFallback } from './components/RouteFallback';
9
10
 
10
11
  // Lazy load route components
@@ -24,9 +25,6 @@ const OAuthCallbackView = lazy(() =>
24
25
  default: m.OAuthCallbackView,
25
26
  })),
26
27
  );
27
- const AdminView = lazy(() =>
28
- import('../features/admin/AdminView').then((m) => ({ default: m.AdminView })),
29
- );
30
28
  const LegalDocumentView = lazy(() =>
31
29
  import('../features/legal/LegalDocumentView').then((m) => ({ default: m.LegalDocumentView })),
32
30
  );
@@ -46,11 +44,6 @@ const NotFoundView = lazy(() =>
46
44
  );
47
45
 
48
46
  export const createRoutes = (config: ShellUIConfig): RouteObject[] => {
49
- const configuredAdminPathname = config.backend?.adminPathname?.trim();
50
- const adminPath =
51
- configuredAdminPathname && configuredAdminPathname.startsWith('/')
52
- ? configuredAdminPathname
53
- : urls.admin;
54
47
  const routes: RouteObject[] = [
55
48
  {
56
49
  path: '/',
@@ -133,11 +126,7 @@ export const createRoutes = (config: ShellUIConfig): RouteObject[] => {
133
126
  </Suspense>
134
127
  ),
135
128
  },
136
- {
137
- // Admin route
138
- path: `${adminPath.replace(/^\//, '')}/*`,
139
- element: <AdminView />,
140
- },
129
+ createAdminRoute(config),
141
130
  {
142
131
  // Catch-all route
143
132
  path: '*',
@@ -20,6 +20,7 @@ let isIntentionalUpdate = false; // Track if we're performing an intentional upd
20
20
  let isRegistering = false; // Track if registration is currently in progress
21
21
  let registrationStartTime = typeof window !== 'undefined' ? Date.now() : 0; // Track when registration started (initialize to page load time)
22
22
  const REGISTRATION_GRACE_PERIOD = 5000; // Don't auto-disable within 5 seconds of page load/registration start
23
+ const UPDATE_AVAILABLE_TOAST_ID = 'shellui:update-available';
23
24
 
24
25
  // Store event handler references so we can remove them if needed
25
26
  type EventHandler = (event?: unknown) => void;
@@ -31,7 +32,7 @@ let redundantHandler: EventHandler | null = null;
31
32
  let serviceWorkerErrorHandler: EventHandler | null = null;
32
33
  let messageErrorHandler: EventHandler | null = null;
33
34
 
34
- /** Global set by host or by us from config so Tauri can be forced (e.g. when __TAURI__ is not yet injected in dev). */
35
+ /** Global set by the CLI build target or from Tauri globals so desktop mode can be detected before __TAURI__ is injected in dev. */
35
36
  declare global {
36
37
  interface Window {
37
38
  __SHELLUI_TAURI__?: boolean;
@@ -62,7 +63,57 @@ export function isTauri(): boolean {
62
63
  return false;
63
64
  }
64
65
 
65
- // Cache for service worker file existence check to avoid duplicate fetches
66
+ const STORAGE_KEY = 'shellui:settings';
67
+
68
+ /**
69
+ * Read whether the service worker is enabled from persisted settings.
70
+ * Defaults to false when unset (opt-in).
71
+ */
72
+ export function isServiceWorkerEnabledInSettings(): boolean {
73
+ if (typeof window === 'undefined') {
74
+ return false;
75
+ }
76
+ try {
77
+ const stored = localStorage.getItem(STORAGE_KEY);
78
+ if (!stored) {
79
+ return false;
80
+ }
81
+ const parsed = JSON.parse(stored) as {
82
+ serviceWorker?: { enabled?: boolean };
83
+ caching?: { enabled?: boolean };
84
+ };
85
+ return parsed.serviceWorker?.enabled ?? parsed.caching?.enabled ?? false;
86
+ } catch {
87
+ return false;
88
+ }
89
+ }
90
+
91
+ /**
92
+ * Unregister the service worker when settings say it is disabled but the browser
93
+ * still has a registration or controller from a previous session.
94
+ */
95
+ export async function ensureServiceWorkerDisabledWhenOff(): Promise<void> {
96
+ if (!('serviceWorker' in navigator) || isTauri()) {
97
+ return;
98
+ }
99
+ if (isServiceWorkerEnabledInSettings()) {
100
+ return;
101
+ }
102
+
103
+ const hasController = !!navigator.serviceWorker.controller;
104
+ let hasRegistration = false;
105
+ try {
106
+ const registration = await navigator.serviceWorker.getRegistration();
107
+ hasRegistration = !!registration;
108
+ } catch {
109
+ hasRegistration = false;
110
+ }
111
+
112
+ if (hasController || hasRegistration || wb) {
113
+ await unregisterServiceWorker();
114
+ }
115
+ }
116
+
66
117
  let swFileExistsCache: Promise<boolean> | null = null;
67
118
  let swFileExistsCacheTime = 0;
68
119
  const SW_FILE_EXISTS_CACHE_TTL = 5000; // Cache for 5 seconds
@@ -77,6 +128,55 @@ async function notifyStatusListeners() {
77
128
  statusListeners.forEach((listener) => listener(status));
78
129
  }
79
130
 
131
+ function createUpdateAvailableActionHandler(): () => void {
132
+ return () => {
133
+ logger.info('Install Now clicked, updating service worker...');
134
+ updateServiceWorker().catch((error) => {
135
+ logger.error('Failed to update service worker:', { error });
136
+ });
137
+ };
138
+ }
139
+
140
+ function showUpdateAvailableNotification(): void {
141
+ shellui.toast({
142
+ id: UPDATE_AVAILABLE_TOAST_ID,
143
+ title: 'New version available',
144
+ description: 'A new version of the app is available. Install now or later?',
145
+ type: 'info',
146
+ duration: 0,
147
+ position: 'bottom-left',
148
+ action: {
149
+ label: 'Install Now',
150
+ onClick: createUpdateAvailableActionHandler(),
151
+ },
152
+ cancel: {
153
+ label: 'Later',
154
+ onClick: () => {
155
+ // User chose to install later, toast will be dismissed
156
+ },
157
+ },
158
+ });
159
+ }
160
+
161
+ /**
162
+ * Show the update-available toast for developer testing (Settings → Service Worker).
163
+ * Syncs waiting service worker state when one exists so "Install Now" works end-to-end.
164
+ */
165
+ export async function showUpdateAvailableToastForTesting(): Promise<void> {
166
+ try {
167
+ const registration = await navigator.serviceWorker.getRegistration();
168
+ if (registration?.waiting) {
169
+ waitingServiceWorker = registration.waiting;
170
+ updateAvailable = true;
171
+ await notifyStatusListeners();
172
+ }
173
+ } catch (error) {
174
+ logger.warn('Failed to sync waiting service worker for update toast test:', { error });
175
+ }
176
+
177
+ showUpdateAvailableNotification();
178
+ }
179
+
80
180
  export interface ServiceWorkerRegistrationOptions {
81
181
  enabled: boolean;
82
182
  onUpdateAvailable?: () => void;
@@ -109,7 +209,6 @@ async function disableCachingAutomatically(reason: string): Promise<void> {
109
209
  // Disable service worker in settings
110
210
  // We need to access settings through localStorage since we're in a module
111
211
  if (typeof window !== 'undefined') {
112
- const STORAGE_KEY = 'shellui:settings';
113
212
  try {
114
213
  const stored = localStorage.getItem(STORAGE_KEY);
115
214
  if (stored) {
@@ -274,7 +373,7 @@ export async function serviceWorkerFileExists(): Promise<boolean> {
274
373
  * Register the service worker and handle updates
275
374
  */
276
375
  export async function registerServiceWorker(
277
- options: ServiceWorkerRegistrationOptions = { enabled: true },
376
+ options: ServiceWorkerRegistrationOptions = { enabled: false },
278
377
  ): Promise<void> {
279
378
  if (!('serviceWorker' in navigator)) {
280
379
  return;
@@ -366,11 +465,10 @@ export async function registerServiceWorker(
366
465
  }
367
466
  }
368
467
 
468
+ let skipRegister = false;
369
469
  if (existingRegistration && wb) {
370
- // Already registered, just update
371
- isInitialRegistration = false; // This is an update check
372
- wb.update();
373
- return;
470
+ isInitialRegistration = false;
471
+ skipRegister = true;
374
472
  }
375
473
 
376
474
  // Check if there's already a service worker controlling the page
@@ -379,7 +477,6 @@ export async function registerServiceWorker(
379
477
 
380
478
  // Register the service worker
381
479
  // Only create new Workbox instance if one doesn't exist
382
- const isNewWorkbox = !wb;
383
480
  if (!wb) {
384
481
  // Use updateViaCache: 'none' to ensure service worker file changes are always detected
385
482
  // This bypasses the browser cache when checking for updates to sw.js/sw-dev.js
@@ -426,17 +523,12 @@ export async function registerServiceWorker(
426
523
  eventListenersAdded = false;
427
524
  }
428
525
 
429
- // Only add event listeners once (when creating a new Workbox instance or if they were removed)
430
- if (isNewWorkbox && !eventListenersAdded) {
526
+ // Add event listeners when missing (handles React Strict Mode remounts)
527
+ if (!eventListenersAdded) {
431
528
  // Set flag IMMEDIATELY to prevent duplicate listener registration
432
529
  eventListenersAdded = true;
433
530
 
434
531
  // Handle service worker updates
435
- // CRITICAL: Use a consistent toast ID to prevent duplicate toasts
436
- // If the handler is called multiple times (event listener + manual call),
437
- // using the same ID will update the existing toast instead of creating a new one
438
- const UPDATE_AVAILABLE_TOAST_ID = 'shellui:update-available';
439
-
440
532
  waitingHandler = async () => {
441
533
  try {
442
534
  // CRITICAL: If we're auto-activating (user refreshed), don't show toast
@@ -490,51 +582,7 @@ export async function registerServiceWorker(
490
582
  if (options.onUpdateAvailable) {
491
583
  options.onUpdateAvailable();
492
584
  } else {
493
- // CRITICAL: Use consistent toast ID so duplicate calls update the same toast
494
- // This prevents multiple toasts from appearing if the handler is called multiple times
495
- // CRITICAL: Always create fresh action handlers that reference the current waitingServiceWorker
496
- // This ensures the action handler always has the correct service worker reference
497
- // even if the toast is updated later
498
- const actionHandler = () => {
499
- logger.info('Install Now clicked, updating service worker...');
500
- // CRITICAL: Get the current waitingServiceWorker at click time, not at toast creation time
501
- // This ensures it works even if the toast was created earlier and then updated
502
- if (waitingServiceWorker) {
503
- updateServiceWorker().catch((error) => {
504
- logger.error('Failed to update service worker:', { error });
505
- });
506
- } else {
507
- logger.warn('Install Now clicked but no waiting service worker found');
508
- // Try to get it from registration as fallback
509
- navigator.serviceWorker.getRegistration().then((swRegistration) => {
510
- if (swRegistration?.waiting) {
511
- waitingServiceWorker = swRegistration.waiting;
512
- updateServiceWorker().catch((error) => {
513
- logger.error('Failed to update service worker:', { error });
514
- });
515
- }
516
- });
517
- }
518
- };
519
-
520
- shellui.toast({
521
- id: UPDATE_AVAILABLE_TOAST_ID, // Use consistent ID to prevent duplicates
522
- title: 'New version available',
523
- description: 'A new version of the app is available. Install now or later?',
524
- type: 'info',
525
- duration: 0, // Don't auto-dismiss
526
- position: 'bottom-left',
527
- action: {
528
- label: 'Install Now',
529
- onClick: actionHandler, // Use the handler function
530
- },
531
- cancel: {
532
- label: 'Later',
533
- onClick: () => {
534
- // User chose to install later, toast will be dismissed
535
- },
536
- },
537
- });
585
+ showUpdateAvailableNotification();
538
586
  }
539
587
  } catch (error) {
540
588
  logger.error('Error in waiting handler:', { error });
@@ -784,8 +832,10 @@ export async function registerServiceWorker(
784
832
  navigator.serviceWorker.addEventListener('messageerror', messageErrorHandler);
785
833
  } // End of event listeners block
786
834
 
787
- // Register the service worker
788
- await wb.register();
835
+ // Register the service worker (skip if already registered in this session)
836
+ if (!skipRegister) {
837
+ await wb.register();
838
+ }
789
839
 
790
840
  // Get the underlying registration to set updateViaCache
791
841
  // This ensures changes to sw.js/sw-dev.js are always detected (bypasses cache)
@@ -841,29 +891,36 @@ export async function registerServiceWorker(
841
891
 
842
892
  notifyStatusListeners();
843
893
 
894
+ // Check for updates immediately after registration
895
+ if (wb) {
896
+ await wb.update();
897
+ }
898
+
844
899
  // Check for updates periodically (including service worker file changes)
845
- // This ensures changes to sw.js/sw-dev.js are detected
846
- /* const _updateInterval = */ setInterval(
847
- () => {
848
- if (wb && options.enabled) {
849
- // wb.update() checks for updates to the service worker file itself
850
- // The browser will compare the byte-by-byte content of sw.js/sw-dev.js
851
- wb.update();
852
- }
853
- },
854
- 60 * 60 * 1000,
855
- ); // Check every hour
900
+ const UPDATE_CHECK_INTERVAL_MS = 5 * 60 * 1000; // every 5 minutes
901
+ setInterval(() => {
902
+ if (wb && options.enabled) {
903
+ wb.update();
904
+ }
905
+ }, UPDATE_CHECK_INTERVAL_MS);
856
906
 
857
- // Also check for updates when the page becomes visible (user returns to tab)
858
- // This helps detect service worker file changes more quickly
907
+ // Check when the tab becomes visible or the window regains focus
859
908
  let visibilityHandler: (() => void) | null = null;
909
+ let focusHandler: (() => void) | null = null;
860
910
  if (typeof document !== 'undefined') {
861
- visibilityHandler = () => {
862
- if (!document.hidden && wb && options.enabled) {
911
+ const checkForUpdate = () => {
912
+ if (wb && options.enabled) {
863
913
  wb.update();
864
914
  }
865
915
  };
916
+ visibilityHandler = () => {
917
+ if (!document.hidden) {
918
+ checkForUpdate();
919
+ }
920
+ };
921
+ focusHandler = checkForUpdate;
866
922
  document.addEventListener('visibilitychange', visibilityHandler);
923
+ window.addEventListener('focus', focusHandler);
867
924
  }
868
925
 
869
926
  // CRITICAL: Mark registration as complete only after everything is set up
@@ -911,12 +968,64 @@ export async function registerServiceWorker(
911
968
  return registrationPromise;
912
969
  }
913
970
 
971
+ /**
972
+ * Clear all service worker caches.
973
+ */
974
+ export async function clearAppCaches(): Promise<void> {
975
+ if ('caches' in window) {
976
+ const cacheNames = await caches.keys();
977
+ await Promise.all(cacheNames.map((name) => caches.delete(name)));
978
+ }
979
+ }
980
+
981
+ /**
982
+ * Reload the app (parent shell when embedded, otherwise the current page).
983
+ */
984
+ export function reloadApp(): void {
985
+ const sent = shellui.sendMessageToParent({
986
+ type: 'SHELLUI_REFRESH_PAGE',
987
+ payload: {},
988
+ });
989
+ if (!sent) {
990
+ window.location.reload();
991
+ }
992
+ }
993
+
994
+ /**
995
+ * Clear cached files and reload the app to fetch the latest version from the server.
996
+ */
997
+ export async function reloadAppToLatestVersion(): Promise<void> {
998
+ await clearAppCaches();
999
+ reloadApp();
1000
+ }
1001
+
914
1002
  /**
915
1003
  * Update the service worker immediately
916
1004
  * This will reload the page when the update is installed
917
1005
  */
918
1006
  export async function updateServiceWorker(): Promise<void> {
919
- if (!wb || !waitingServiceWorker) {
1007
+ if (!('serviceWorker' in navigator)) {
1008
+ return;
1009
+ }
1010
+
1011
+ // Resolve waiting worker from registration when Workbox was not initialized this session
1012
+ if (!waitingServiceWorker) {
1013
+ try {
1014
+ const registration = await navigator.serviceWorker.getRegistration();
1015
+ if (registration?.waiting) {
1016
+ waitingServiceWorker = registration.waiting;
1017
+ updateAvailable = true;
1018
+ }
1019
+ } catch (error) {
1020
+ logger.error('Failed to resolve waiting service worker:', { error });
1021
+ }
1022
+ }
1023
+
1024
+ if (!waitingServiceWorker) {
1025
+ logger.warn(
1026
+ 'updateServiceWorker: no waiting service worker found, clearing caches and reloading',
1027
+ );
1028
+ await reloadAppToLatestVersion();
920
1029
  return;
921
1030
  }
922
1031
 
@@ -940,7 +1049,6 @@ export async function updateServiceWorker(): Promise<void> {
940
1049
  // This prevents the service worker from being disabled after refresh
941
1050
  // The user explicitly clicked "Install Now", so we must keep the service worker enabled
942
1051
  if (typeof window !== 'undefined') {
943
- const STORAGE_KEY = 'shellui:settings';
944
1052
  try {
945
1053
  const stored = localStorage.getItem(STORAGE_KEY);
946
1054
  if (stored) {
@@ -975,39 +1083,36 @@ export async function updateServiceWorker(): Promise<void> {
975
1083
  isInitialRegistration = false;
976
1084
 
977
1085
  // Set up reload handler before sending skip waiting
978
- const reloadApp = () => {
979
- // Use shellUI refresh message if available, otherwise fallback to window.location.reload
980
- const sent = shellui.sendMessageToParent({
981
- type: 'SHELLUI_REFRESH_PAGE',
982
- payload: {},
983
- });
984
- if (!sent) {
985
- window.location.reload();
986
- }
1086
+ let reloaded = false;
1087
+ const reloadOnce = () => {
1088
+ if (reloaded) return;
1089
+ reloaded = true;
1090
+ reloadApp();
987
1091
  };
988
1092
 
989
- // Add one-time listener for controlling event
1093
+ // Add one-time listener for controlling event (Workbox or native controllerchange)
990
1094
  const updateControllingHandler = () => {
991
- reloadApp();
1095
+ reloadOnce();
992
1096
  wb?.removeEventListener('controlling', updateControllingHandler);
993
1097
  // Reset flag after reload is triggered
994
1098
  setTimeout(() => {
995
1099
  isIntentionalUpdate = false;
996
1100
  }, 1000);
997
1101
  };
998
- wb.addEventListener('controlling', updateControllingHandler);
1102
+ if (wb) {
1103
+ wb.addEventListener('controlling', updateControllingHandler);
1104
+ }
1105
+ navigator.serviceWorker.addEventListener('controllerchange', updateControllingHandler, {
1106
+ once: true,
1107
+ });
999
1108
 
1000
1109
  // Send skip waiting message to the waiting service worker
1001
1110
  waitingServiceWorker.postMessage({ type: 'SKIP_WAITING' });
1002
1111
 
1003
- // Fallback: if controlling event doesn't fire within 2 seconds, reload anyway
1112
+ // Fallback: reload if controlling event doesn't fire within 2 seconds
1004
1113
  setTimeout(() => {
1005
- if (controllingHandler) wb?.removeEventListener('controlling', controllingHandler);
1006
- // Check if service worker is now controlling
1007
- if (navigator.serviceWorker.controller) {
1008
- reloadApp();
1009
- }
1010
- // Reset flag if fallback is used
1114
+ wb?.removeEventListener('controlling', updateControllingHandler);
1115
+ reloadOnce();
1011
1116
  setTimeout(() => {
1012
1117
  isIntentionalUpdate = false;
1013
1118
  }, 1000);
@@ -1180,8 +1285,19 @@ export async function getServiceWorkerStatus(): Promise<{
1180
1285
  * Resolves when the check is complete. Listen to addStatusListener for updateAvailable changes.
1181
1286
  */
1182
1287
  export async function checkForServiceWorkerUpdate(): Promise<void> {
1183
- if (isTauri() || !wb) return;
1184
- await wb.update();
1288
+ if (isTauri() || !('serviceWorker' in navigator)) return;
1289
+ if (wb) {
1290
+ await wb.update();
1291
+ return;
1292
+ }
1293
+ try {
1294
+ const registration = await navigator.serviceWorker.getRegistration();
1295
+ if (registration) {
1296
+ await registration.update();
1297
+ }
1298
+ } catch (error) {
1299
+ logger.error('Failed to check for service worker update:', { error });
1300
+ }
1185
1301
  }
1186
1302
 
1187
1303
  /**
@@ -79,9 +79,13 @@ registerRoute(
79
79
  }),
80
80
  );
81
81
 
82
- // Skip waiting and claim clients immediately when a new service worker is installed
82
+ // Skip waiting when the page requests an update, then take control of open clients
83
83
  self.addEventListener('message', (event) => {
84
84
  if (event.data && event.data.type === 'SKIP_WAITING') {
85
85
  self.skipWaiting();
86
86
  }
87
87
  });
88
+
89
+ self.addEventListener('activate', (event) => {
90
+ event.waitUntil(self.clients.claim());
91
+ });
@@ -97,9 +97,13 @@ registerRoute(
97
97
  }),
98
98
  );
99
99
 
100
- // Skip waiting and claim clients immediately when a new service worker is installed
100
+ // Skip waiting when the page requests an update, then take control of open clients
101
101
  self.addEventListener('message', (event) => {
102
102
  if (event.data && event.data.type === 'SKIP_WAITING') {
103
103
  self.skipWaiting();
104
104
  }
105
105
  });
106
+
107
+ self.addEventListener('activate', (event) => {
108
+ event.waitUntil(self.clients.claim());
109
+ });
@@ -0,0 +1,2 @@
1
+ /** Injected by @shellui/cli at build/dev time. 'tauri' when using --app or --target tauri. */
2
+ declare const __SHELLUI_TARGET__: 'web' | 'tauri';