-
-
Notifications
You must be signed in to change notification settings - Fork 9
Expand file tree
/
Copy pathUpdateChecker.tsx
More file actions
333 lines (309 loc) · 11.2 KB
/
Copy pathUpdateChecker.tsx
File metadata and controls
333 lines (309 loc) · 11.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
import { useState, useEffect } from 'react';
import { check, Update } from '@tauri-apps/plugin-updater';
import { relaunch } from '@tauri-apps/plugin-process';
import {
Button,
Card,
CardHeader,
CardTitle,
CardDescription,
CardContent,
} from '@mcpmux/ui';
import { Download, Loader2, CheckCircle, AlertCircle, RefreshCw, RotateCcw } from 'lucide-react';
import { invoke } from '@tauri-apps/api/core';
interface DownloadEvent {
event: 'Started' | 'Progress' | 'Finished';
data?: {
contentLength?: number;
chunkLength?: number;
};
}
export function UpdateChecker() {
const [checking, setChecking] = useState(false);
const [downloading, setDownloading] = useState(false);
const [updateInfo, setUpdateInfo] = useState<Update | null>(null);
const [downloadProgress, setDownloadProgress] = useState({ downloaded: 0, total: 0 });
const [message, setMessage] = useState<{ type: 'success' | 'error'; text: string } | null>(null);
const [currentVersion, setCurrentVersion] = useState<string>('');
const [bundleVersionMismatch, setBundleVersionMismatch] = useState<string | null>(null);
// Load current version on mount
useState(() => {
invoke<string>('get_version')
.then(setCurrentVersion)
.catch((err) => console.error('Failed to get version:', err));
});
// Check if the on-disk bundle version differs from the running version (Homebrew Cask upgrades)
useEffect(() => {
if (!currentVersion) return;
invoke<string | null>('get_bundle_version')
.then((bundleVersion) => {
if (bundleVersion && bundleVersion !== currentVersion) {
console.log(
`[Updater] Bundle version mismatch: running=${currentVersion}, on-disk=${bundleVersion}`
);
setBundleVersionMismatch(bundleVersion);
}
})
.catch(() => {
// Expected to return null on non-macOS platforms
});
}, [currentVersion]);
const checkForUpdates = async () => {
setChecking(true);
setMessage(null);
setUpdateInfo(null);
try {
console.log('[Updater] Checking for updates...');
const update = await check();
if (update) {
console.log(
`[Updater] Update available: ${update.version} from ${update.date || 'N/A'}`
);
setUpdateInfo(update);
setMessage({
type: 'success',
text: `Version ${update.version} is available!`,
});
} else {
console.log('[Updater] No updates available');
setMessage({
type: 'success',
text: "You're running the latest version!",
});
}
} catch (error) {
console.error('[Updater] Check failed:', error);
setMessage({
type: 'error',
text: `Failed to check for updates: ${error}`,
});
} finally {
setChecking(false);
}
};
const installUpdate = async () => {
if (!updateInfo) return;
setDownloading(true);
setDownloadProgress({ downloaded: 0, total: 0 });
setMessage(null);
try {
console.log('[Updater] Starting download and install...');
await updateInfo.downloadAndInstall((event: DownloadEvent) => {
switch (event.event) {
case 'Started':
console.log(`[Updater] Downloading ${event.data?.contentLength || 0} bytes`);
setDownloadProgress({
downloaded: 0,
total: event.data?.contentLength || 0,
});
break;
case 'Progress':
setDownloadProgress((prev) => ({
...prev,
downloaded: prev.downloaded + (event.data?.chunkLength || 0),
}));
break;
case 'Finished':
console.log('[Updater] Download finished, installing...');
break;
}
});
console.log('[Updater] Update installed successfully, relaunching app...');
// Note: On Windows, the app will exit automatically before this point
await relaunch();
} catch (error) {
console.error('[Updater] Installation failed:', error);
setMessage({
type: 'error',
text: `Failed to install update: ${error}`,
});
setDownloading(false);
}
};
const formatBytes = (bytes: number): string => {
if (bytes === 0) return '0 B';
const k = 1024;
const sizes = ['B', 'KB', 'MB', 'GB'];
const i = Math.floor(Math.log(bytes) / Math.log(k));
return `${(bytes / Math.pow(k, i)).toFixed(2)} ${sizes[i]}`;
};
const progressPercent =
downloadProgress.total > 0
? Math.round((downloadProgress.downloaded / downloadProgress.total) * 100)
: 0;
return (
<Card data-testid="update-checker">
<CardHeader>
<CardTitle className="flex items-center gap-2">
<RefreshCw className="h-5 w-5" />
Software Updates
</CardTitle>
<CardDescription>
Keep your application up to date with the latest features and fixes.
</CardDescription>
</CardHeader>
<CardContent>
<div className="space-y-4">
{/* Current Version */}
<div>
<label className="text-sm font-medium">Current Version</label>
<p className="text-sm text-[rgb(var(--muted))] mt-1" data-testid="current-version">
v{currentVersion || '0.0.5'}
</p>
</div>
{/* Bundle version mismatch (e.g., after brew upgrade) */}
{bundleVersionMismatch && (
<div
className="border rounded-lg p-4 space-y-3 bg-surface-secondary"
data-testid="restart-required"
>
<div>
<p className="font-medium text-lg">Restart Required</p>
<p className="text-sm text-[rgb(var(--muted))] mt-1">
Version v{bundleVersionMismatch} has been installed on disk, but you are still
running v{currentVersion}. Restart to apply the update.
</p>
</div>
<Button
onClick={() => relaunch()}
variant="primary"
data-testid="restart-now-btn"
>
<RotateCcw className="h-4 w-4 mr-2" />
Restart Now
</Button>
</div>
)}
{/* Check Button */}
{!updateInfo && !bundleVersionMismatch && (
<Button
onClick={checkForUpdates}
disabled={checking || downloading}
variant="secondary"
data-testid="check-updates-btn"
>
{checking ? (
<>
<Loader2 className="h-4 w-4 animate-spin mr-2" />
Checking for Updates...
</>
) : (
<>
<RefreshCw className="h-4 w-4 mr-2" />
Check for Updates
</>
)}
</Button>
)}
{/* Status Message */}
{message && !updateInfo && (
<div
className={`flex items-start gap-2 p-3 rounded-lg text-sm ${
message.type === 'success'
? 'bg-green-500/10 text-green-600 dark:text-green-400'
: 'bg-red-500/10 text-red-600 dark:text-red-400'
}`}
data-testid="update-message"
>
{message.type === 'success' ? (
<CheckCircle className="h-4 w-4 mt-0.5 flex-shrink-0" />
) : (
<AlertCircle className="h-4 w-4 mt-0.5 flex-shrink-0" />
)}
<span>{message.text}</span>
</div>
)}
{/* Update Available Card */}
{updateInfo && (
<div className="border rounded-lg p-4 space-y-3 bg-surface-secondary" data-testid="update-available">
<div>
<p className="font-medium text-lg">
Update Available: v{updateInfo.version}
</p>
{updateInfo.date && (
<p className="text-xs text-[rgb(var(--muted))]">
Released: {new Date(updateInfo.date).toLocaleDateString()}
</p>
)}
</div>
{/* Release Notes */}
{updateInfo.body && (
<div className="text-sm">
<p className="font-medium mb-1">What's New:</p>
<div className="text-[rgb(var(--muted))] whitespace-pre-wrap max-h-32 overflow-y-auto">
{updateInfo.body}
</div>
</div>
)}
{/* Download Progress */}
{downloading && downloadProgress.total > 0 && (
<div className="space-y-2">
<div className="flex justify-between text-xs text-[rgb(var(--muted))]">
<span>Downloading...</span>
<span>
{formatBytes(downloadProgress.downloaded)} / {formatBytes(downloadProgress.total)} ({progressPercent}%)
</span>
</div>
<div className="w-full bg-surface-secondary rounded-full h-2 overflow-hidden">
<div
className="bg-primary-500 h-full transition-all duration-300"
style={{ width: `${progressPercent}%` }}
/>
</div>
</div>
)}
{/* Install Button */}
<div className="flex gap-2">
<Button
onClick={installUpdate}
disabled={downloading}
variant="primary"
data-testid="install-update-btn"
>
{downloading ? (
<>
<Loader2 className="h-4 w-4 animate-spin mr-2" />
{downloadProgress.total > 0 ? 'Downloading...' : 'Installing...'}
</>
) : (
<>
<Download className="h-4 w-4 mr-2" />
Download and Install
</>
)}
</Button>
{!downloading && (
<Button
onClick={() => {
setUpdateInfo(null);
setMessage(null);
}}
variant="secondary"
data-testid="dismiss-update-btn"
>
Remind Me Later
</Button>
)}
</div>
{downloading && (
<p className="text-xs text-[rgb(var(--muted))]">
<strong>Note:</strong> On Windows, the app will close automatically to install the update.
</p>
)}
</div>
)}
{/* Error Message for Update Available State */}
{message && updateInfo && message.type === 'error' && (
<div
className="flex items-start gap-2 p-3 rounded-lg text-sm bg-red-500/10 text-red-600 dark:text-red-400"
data-testid="update-error"
>
<AlertCircle className="h-4 w-4 mt-0.5 flex-shrink-0" />
<span>{message.text}</span>
</div>
)}
</div>
</CardContent>
</Card>
);
}