Implemented self-updating

This commit is contained in:
patben8 committed 2026-10-16 17:38:35 +02:00
1 parent 422297d890
commit 0eac972173
12 files changed
+1016 -80

No files matched your search

+204 -44
View File
@@ -1,5 +1,5 @@
import { createPortal } from 'react-dom'
import { useState } from 'react'
import { useEffect, useState } from 'react'
import { useQuery, useQueryClient } from '@tanstack/react-query'
import { api } from '../api'
@@ -12,8 +12,20 @@ import { api } from '../api'
* Failures are silent: an update check must never nag about itself.
* "Skip this version" persists `skippedUpdateVersion` to userprefs.json via
* the prefs API, keyed by the semver part, so a later version re-triggers.
*
* In the desktop app, Update installs it (decided 2026-10-16,
* .claude/discussions/discuss-self-update-2026-10-16.md): the shell
* (src-tauri/src/lib.rs) downloads THIS release's `latest.json` package with
* progress, verifies and stages it, then quits through the ordinary quit
* request — so unsaved edits are asked about by QuitGuard — and installs at
* exit, after the backend is dead, and relaunches. Cancel in that prompt
* leaves it staged for the next quit. A failure says why and offers the
* release page (what Download did before); an install that failed at exit is
* reported by the next launch. A plain browser keeps Download.
*/
const IN_TAURI = '__TAURI_INTERNALS__' in window
const REPO = 'MrPatben8/konduktor'
interface GithubRelease {
@@ -118,10 +130,31 @@ function ChangelogLine({ text }: { text: string }) {
)
}
type Phase =
| { kind: 'offer' }
| { kind: 'downloading'; downloaded: number; total: number | null }
| { kind: 'restarting' }
| { kind: 'deferred' }
| { kind: 'failed'; error: string }
interface UpdateFailure {
version: string
error: string
}
const mb = (bytes: number) => (bytes / 1e6).toFixed(0)
async function lastInstallFailure(): Promise<UpdateFailure | null> {
if (!IN_TAURI) return null
const { invoke } = await import('@tauri-apps/api/core')
return (await invoke<UpdateFailure | null>('update_take_failure')) ?? null
}
export function UpdateCheck() {
const qc = useQueryClient()
const [dismissed, setDismissed] = useState(false)
const [skipVersion, setSkipVersion] = useState(false)
const [phase, setPhase] = useState<Phase>({ kind: 'offer' })
const release = useQuery({
queryKey: ['latestRelease'],
@@ -129,20 +162,50 @@ export function UpdateCheck() {
staleTime: Infinity,
retry: false,
})
// Read (and cleared) once: the shell writes it when an install fails at exit.
const lastFailure = useQuery({
queryKey: ['updateFailure'],
queryFn: lastInstallFailure,
staleTime: Infinity,
retry: false,
})
// Shares App's ['prefs'] cache entry.
const prefs = useQuery({ queryKey: ['prefs'], queryFn: api.getPrefs })
// Cancel in QuitGuard's Save / Discard prompt: the update waits for the next quit.
useEffect(() => {
if (phase.kind !== 'restarting') return
let unlisten: (() => void) | undefined
let cancelled = false
void import('@tauri-apps/api/event').then(async ({ listen }) => {
const off = await listen('konduktor://update-deferred', () => setPhase({ kind: 'deferred' }))
if (cancelled) off()
else unlisten = off
})
return () => {
cancelled = true
unlisten?.()
}
}, [phase.kind])
const latest = release.data
const latestVer = latest ? parseVersion(latest.tag_name) : null
const currentVer = parseVersion(__APP_VERSION__)
const latestSemver = latestVer?.join('.')
const updateAvailable = !!(latestVer && currentVer && isNewer(latestVer, currentVer))
const skipped = !!latestSemver && prefs.data?.skippedUpdateVersion === latestSemver
const failedBefore = lastFailure.data ?? null
const releasePage = latest?.html_url ?? `https://github.com/${REPO}/releases`
if (dismissed) return null
// Wait for prefs before showing so a skipped version never flashes the dialog.
if (dismissed || !updateAvailable || !latest || !prefs.isSuccess || skipped) return null
const offering = updateAvailable && !!latest && prefs.isSuccess && !skipped
if (!offering && !failedBefore) return null
const busy = phase.kind === 'downloading' || phase.kind === 'restarting'
const close = () => {
if (busy) return
if (skipVersion && latestSemver) {
api
.patchPrefs({ skippedUpdateVersion: latestSemver })
@@ -152,12 +215,47 @@ export function UpdateCheck() {
setDismissed(true)
}
const download = () => {
openExternal(latest.html_url)
const openReleasePage = () => {
openExternal(releasePage)
setDismissed(true)
}
const changes = whatsChanged(latest.body)
const update = async () => {
if (!latest) return
setPhase({ kind: 'downloading', downloaded: 0, total: null })
try {
const { invoke, Channel } = await import('@tauri-apps/api/core')
const onProgress = new Channel<{ downloaded: number; total: number | null }>()
onProgress.onmessage = (p) => setPhase({ kind: 'downloading', ...p })
await invoke('update_download', { tag: latest.tag_name, onProgress })
setPhase({ kind: 'restarting' })
await invoke('update_restart')
} catch (e) {
setPhase({ kind: 'failed', error: e instanceof Error ? e.message : String(e) })
}
}
// An install that failed at the last exit, with no newer offer to make.
const reportOnly = !offering && !!failedBefore
const failure =
phase.kind === 'failed'
? phase.error
: reportOnly || (failedBefore && phase.kind === 'offer')
? `The update to v${failedBefore!.version} didn't install: ${failedBefore!.error}`
: null
const title =
phase.kind === 'downloading'
? 'Downloading update…'
: phase.kind === 'restarting'
? 'Installing update…'
: phase.kind === 'deferred'
? 'Update ready'
: phase.kind === 'failed' || reportOnly
? "Update didn't install"
: 'Update available'
const changes = latest ? whatsChanged(latest.body) : []
return createPortal(
<div
@@ -169,54 +267,116 @@ export function UpdateCheck() {
onClick={(e) => e.stopPropagation()}
>
<div className="border-b border-line px-5 py-4">
<div className="text-[15px] font-semibold tracking-tight">Update available</div>
<div className="text-xs text-muted">
Konduktor <span className="text-accent">{latest.tag_name}</span> is out — you have v
{__APP_VERSION__}.
</div>
<div className="text-[15px] font-semibold tracking-tight">{title}</div>
{latest && !reportOnly && (
<div className="text-xs text-muted">
Konduktor <span className="text-accent">{latest.tag_name}</span> is out — you have v
{__APP_VERSION__}.
</div>
)}
</div>
<div className="min-h-0 flex-1 overflow-y-auto px-5 py-4">
<div className="mb-2 text-xs font-medium text-muted">What's changed</div>
{changes.length ? (
<ul className="space-y-1.5">
{changes.map((line, i) => (
<li key={i} className="flex gap-2 text-sm text-text">
<span className="text-faint">•</span>
<span className="min-w-0 break-words">
<ChangelogLine text={line} />
</span>
</li>
))}
</ul>
{failure && <p className="mb-3 text-sm text-pink">{failure}</p>}
{phase.kind === 'downloading' ? (
<div className="space-y-2">
<div className="well h-2 overflow-hidden rounded-full">
<div
className="h-full rounded-full bg-accent transition-[width] duration-150"
style={{
width: phase.total ? `${Math.min(100, (phase.downloaded / phase.total) * 100)}%` : '0%',
}}
/>
</div>
<div className="text-xs tabular-nums text-muted">
{mb(phase.downloaded)}
{phase.total ? ` / ${mb(phase.total)}` : ''} MB
</div>
</div>
) : phase.kind === 'restarting' ? (
<div className="text-sm text-muted">Konduktor will quit, install the update and reopen.</div>
) : phase.kind === 'deferred' ? (
<div className="text-sm text-muted">
The update will install the next time you quit Konduktor.
</div>
) : reportOnly ? (
<div className="text-sm text-muted">
You can download the installer from the release page instead.
</div>
) : (
<div className="text-sm text-faint">No release notes.</div>
<>
<div className="mb-2 text-xs font-medium text-muted">What's changed</div>
{changes.length ? (
<ul className="space-y-1.5">
{changes.map((line, i) => (
<li key={i} className="flex gap-2 text-sm text-text">
<span className="text-faint">•</span>
<span className="min-w-0 break-words">
<ChangelogLine text={line} />
</span>
</li>
))}
</ul>
) : (
<div className="text-sm text-faint">No release notes.</div>
)}
</>
)}
</div>
<div className="flex items-center gap-3 border-t border-line px-5 py-3">
<label className="flex cursor-pointer items-center gap-2 text-xs text-muted">
<input
type="checkbox"
checked={skipVersion}
onChange={(e) => setSkipVersion(e.target.checked)}
className="accent-accent"
/>
Skip this version
</label>
{phase.kind === 'offer' && !reportOnly && (
<label className="flex cursor-pointer items-center gap-2 text-xs text-muted">
<input
type="checkbox"
checked={skipVersion}
onChange={(e) => setSkipVersion(e.target.checked)}
className="accent-accent"
/>
Skip this version
</label>
)}
<div className="flex-1" />
<button
onClick={close}
className="rounded-md px-3 py-1.5 text-sm text-muted hover:bg-ink-800 hover:text-text"
>
Skip
</button>
<button
onClick={download}
className="rounded-full btn-primary px-3 py-1.5 text-sm font-semibold"
>
Download
</button>
{phase.kind === 'offer' && !reportOnly && (
<>
<button
onClick={close}
className="rounded-md px-3 py-1.5 text-sm text-muted hover:bg-ink-800 hover:text-text"
>
Skip
</button>
<button
onClick={IN_TAURI ? () => void update() : openReleasePage}
className="rounded-full btn-primary px-3 py-1.5 text-sm font-semibold"
>
{IN_TAURI ? 'Update' : 'Download'}
</button>
</>
)}
{(phase.kind === 'failed' || reportOnly) && (
<>
<button
onClick={close}
className="rounded-md px-3 py-1.5 text-sm text-muted hover:bg-ink-800 hover:text-text"
>
Close
</button>
<button
onClick={openReleasePage}
className="rounded-full btn-primary px-3 py-1.5 text-sm font-semibold"
>
Open release page
</button>
</>
)}
{phase.kind === 'deferred' && (
<button
onClick={() => setDismissed(true)}
className="rounded-full btn-primary px-3 py-1.5 text-sm font-semibold"
>
OK
</button>
)}
</div>
</div>
</div>,