Skip to content

Commit 6ecba3b

Browse files
EVWorthclaude
andauthored
fix(update): separate downloading from restarting, and put the refusal in the action (#573)
Closes #344, #569, #570. Three problems on one path, all of them about the app deciding something on the user's behalf at a moment nobody chose. ## The restart was not asked for installUpdate ended with an unconditional relaunch(), so a download finishing closed the app. Downloading and restarting are now separate: installUpdate stages the update and stops, and the status bar offers "Restart to finish update" for the user to take when they are ready. That is what VS Code and Slack do, and for the same reason — the download is harmless, the restart is the part that can lose work. There was no UI for the "downloaded" state at all, so a relaunch that failed or hung left the status bar showing nothing. ## The refusal lived in the button The checks for a running query and unsaved tabs were in the status bar's onClick. installUpdate itself had none. One caller today, but nothing said the next one had to bring its own — the same shape as the grid's save path before #529. Worse, they ran once, at the click, before a download that can take minutes, and the restart then happened against a state nobody had looked at since. A query started or a tab edited during the download was destroyed by a restart authorised before either existed. updateBlockers lives in src/lib/update-guard.ts, so both moments can ask without the settings store having to know about queries or editor tabs. It is checked before the download and again before the restart. It reports every reason rather than the first, so fixing one does not walk into the next. ## A failed install left the status bar lying installUpdate set "downloading" and then returned without touching it if pendingUpdate had been cleared — which any concurrent check does, including the one the status bar fires on mount. The spinner stayed forever, and the button that could retry only renders in the "available" state. It now reports what happened and leaves a state the user can act from. The same applies when relaunch fails: the update is on disk, so it says so and says to quit and reopen, rather than implying a re-download. ## Tests Five on the guard, four new on the store. Three fail against the previous version. Two existing tests changed rather than being deleted: the relaunch assertion moved to restartToApply, and the two status-bar tests that asserted the button refuses now assert the refusal itself, since that is where it moved. Co-authored-by: Claude Opus 5 <[email protected]>
1 parent 5b530c4 commit 6ecba3b

6 files changed

Lines changed: 234 additions & 35 deletions

File tree

‎src/components/layout/StatusBar.tsx‎

Lines changed: 17 additions & 24 deletions
Original file line numberDiff line numberDiff line change
@@ -85,7 +85,7 @@ export function StatusBar() {
8585
const downloadProgress = useSettingsStore((s) => s.downloadProgress);
8686
const checkForUpdates = useSettingsStore((s) => s.checkForUpdates);
8787
const installUpdate = useSettingsStore((s) => s.installUpdate);
88-
const setUpdateError = useSettingsStore((s) => s.setUpdateError);
88+
const restartToApply = useSettingsStore((s) => s.restartToApply);
8989
const updateDetailsRef = useRef<HTMLDivElement | null>(null);
9090

9191
useEffect(() => {
@@ -115,9 +115,6 @@ export function StatusBar() {
115115
return () => document.removeEventListener("mousedown", onDocClick);
116116
}, [showUpdateDetails]);
117117

118-
const dirtyTabs = tabs.filter((t) => t.isDirty);
119-
const hasDirtyTabs = dirtyTabs.length > 0;
120-
121118
const activeConn = activeConnections.find(
122119
(c) => c.id === selectedConnectionId,
123120
);
@@ -287,32 +284,28 @@ export function StatusBar() {
287284
)}
288285
{updateStatus === "available" && (
289286
<button
290-
onClick={() => {
291-
if (isExecuting) {
292-
setUpdateError(
293-
"Cannot update while a query is running. Cancel or wait for it to finish.",
294-
);
295-
useSettingsStore.setState({ updateStatus: "error" });
296-
return;
297-
}
298-
if (hasDirtyTabs) {
299-
setUpdateError(
300-
`Cannot update: ${dirtyTabs.length} editor tab${dirtyTabs.length === 1 ? "" : "s"} ${
301-
dirtyTabs.length === 1 ? "has" : "have"
302-
} unsaved changes. Save or discard first.`,
303-
);
304-
useSettingsStore.setState({ updateStatus: "error" });
305-
return;
306-
}
307-
void installUpdate();
308-
}}
287+
/* The refusal lives in the store now, so it applies to every
288+
caller and is checked again before the restart (#570). */
289+
onClick={() => void installUpdate()}
309290
className="flex items-center gap-1 text-[10px] text-green-400 hover:text-green-300 transition-colors"
310-
title={`Update v${updateVersion} available — click to install`}
291+
title={`Update v${updateVersion} available — click to download`}
311292
>
312293
<Download className="h-3 w-3" />
313294
Update to v{updateVersion}
314295
</button>
315296
)}
297+
{updateStatus === "downloaded" && (
298+
<button
299+
/* Downloading and restarting are separate: the app closing is the
300+
part that can lose work, so it waits to be asked (#344). */
301+
onClick={() => void restartToApply()}
302+
className="flex items-center gap-1 text-[10px] text-green-400 hover:text-green-300 transition-colors"
303+
title={`v${updateVersion} is installed — restart to finish`}
304+
>
305+
<RefreshCw className="h-3 w-3" />
306+
Restart to finish update
307+
</button>
308+
)}
316309
{updateStatus === "manual-update-required" && manualUpdateCommand && (
317310
<button
318311
onClick={handleCopyManualCommand}

‎src/components/layout/__tests__/StatusBar.test.tsx‎

Lines changed: 4 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -301,11 +301,12 @@ describe("StatusBar", () => {
301301
activeTabId: "tab-0",
302302
});
303303
renderStatusBar();
304-
const installSpy = vi.spyOn(useSettingsStore.getState(), "installUpdate");
305304
await user.click(screen.getByText("Update to v2.0.0"));
306-
expect(installSpy).not.toHaveBeenCalled();
305+
// The button delegates; the refusal comes from the store, so it also
306+
// applies to any other caller and is re-checked before the restart
307+
// (#570).
307308
expect(useSettingsStore.getState().updateStatus).toBe("error");
308-
expect(useSettingsStore.getState().updateError).toMatch(/query is running/i);
309+
expect(useSettingsStore.getState().updateError).toMatch(/query is still running/i);
309310
});
310311

311312
it("blocks install when an editor tab has unsaved changes", async () => {
@@ -330,9 +331,7 @@ describe("StatusBar", () => {
330331
activeTabId: "tab-0",
331332
});
332333
renderStatusBar();
333-
const installSpy = vi.spyOn(useSettingsStore.getState(), "installUpdate");
334334
await user.click(screen.getByText("Update to v2.0.0"));
335-
expect(installSpy).not.toHaveBeenCalled();
336335
expect(useSettingsStore.getState().updateStatus).toBe("error");
337336
expect(useSettingsStore.getState().updateError).toMatch(/unsaved changes/i);
338337
});
Lines changed: 53 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,53 @@
1+
import { beforeEach, describe, expect, it } from "vitest";
2+
import { useEditorStore } from "../../stores/editorStore";
3+
import { useResultStore } from "../../stores/resultStore";
4+
import { describeUpdateBlockers, updateBlockers } from "../update-guard";
5+
6+
const tab = (id: string, isDirty: boolean) => ({
7+
id,
8+
title: id,
9+
content: "",
10+
type: "query" as const,
11+
isDirty,
12+
});
13+
14+
describe("updateBlockers", () => {
15+
beforeEach(() => {
16+
useResultStore.setState({ isExecuting: false });
17+
useEditorStore.setState({ tabs: [tab("t1", false)], activeTabId: "t1" });
18+
});
19+
20+
it("finds nothing to stop an update on an idle app", () => {
21+
expect(updateBlockers()).toEqual([]);
22+
expect(describeUpdateBlockers()).toBeNull();
23+
});
24+
25+
it("stops an update while a query is running", () => {
26+
useResultStore.setState({ isExecuting: true });
27+
expect(describeUpdateBlockers()).toMatch(/query is still running/);
28+
});
29+
30+
it("stops an update with unsaved work, and counts it", () => {
31+
useEditorStore.setState({
32+
tabs: [tab("t1", true), tab("t2", true), tab("t3", false)],
33+
activeTabId: "t1",
34+
});
35+
expect(describeUpdateBlockers()).toMatch(/2 editor tabs have unsaved changes/);
36+
});
37+
38+
it("uses the singular for one tab", () => {
39+
useEditorStore.setState({ tabs: [tab("t1", true)], activeTabId: "t1" });
40+
expect(describeUpdateBlockers()).toMatch(/1 editor tab has unsaved changes/);
41+
});
42+
43+
it("names both reasons when both apply", () => {
44+
// Reporting only the first would send the user to fix one thing and
45+
// meet the same refusal again.
46+
useResultStore.setState({ isExecuting: true });
47+
useEditorStore.setState({ tabs: [tab("t1", true)], activeTabId: "t1" });
48+
49+
const message = describeUpdateBlockers();
50+
expect(message).toMatch(/query is still running/);
51+
expect(message).toMatch(/unsaved changes/);
52+
});
53+
});

‎src/lib/update-guard.ts‎

Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
import { useEditorStore } from "../stores/editorStore";
2+
import { useResultStore } from "../stores/resultStore";
3+
4+
/**
5+
* Why it would be a bad moment to restart into a new version.
6+
*
7+
* These checks used to live in the status bar's click handler, which meant
8+
* two things. The store action was reachable without them — one caller today,
9+
* but nothing said the next one had to bring its own. And they ran once, at
10+
* the click, before a download that can take minutes; the restart then
11+
* happened unconditionally against a state nobody had looked at since (#570).
12+
*
13+
* Kept out of the settings store so it can be checked at both moments without
14+
* that store having to know about queries or editor tabs.
15+
*/
16+
export function updateBlockers(): string[] {
17+
const reasons: string[] = [];
18+
19+
if (useResultStore.getState().isExecuting) {
20+
reasons.push("a query is still running");
21+
}
22+
23+
const dirty = useEditorStore.getState().tabs.filter((t) => t.isDirty);
24+
if (dirty.length > 0) {
25+
reasons.push(
26+
dirty.length === 1
27+
? "1 editor tab has unsaved changes"
28+
: `${dirty.length} editor tabs have unsaved changes`,
29+
);
30+
}
31+
32+
return reasons;
33+
}
34+
35+
/** The blockers as one sentence, or null when there are none. */
36+
export function describeUpdateBlockers(): string | null {
37+
const reasons = updateBlockers();
38+
if (reasons.length === 0) return null;
39+
return `Cannot update while ${reasons.join(" and ")}. Save or finish first.`;
40+
}

‎src/stores/__tests__/settingsStore.test.ts‎

Lines changed: 70 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -386,7 +386,7 @@ describe("settingsStore", () => {
386386
vi.clearAllMocks();
387387
});
388388

389-
it("downloads, installs, and relaunches using the cached Update", async () => {
389+
it("downloads and stages the update, but does not restart on its own", async () => {
390390
vi.resetModules();
391391
const process = await import("@tauri-apps/plugin-process");
392392
const downloadAndInstall = vi.fn();
@@ -401,10 +401,14 @@ describe("settingsStore", () => {
401401
await useSettingsStore.getState().installUpdate();
402402
expect(useSettingsStore.getState().updateStatus).toBe("downloaded");
403403
expect(downloadAndInstall).toHaveBeenCalledOnce();
404+
// Restarting closes the app, so it waits to be asked (#344).
405+
expect(process.relaunch).not.toHaveBeenCalled();
406+
407+
await useSettingsStore.getState().restartToApply();
404408
expect(process.relaunch).toHaveBeenCalledOnce();
405409
});
406410

407-
it("does nothing when no cached update is available", async () => {
411+
it("says so when the pending update has gone, rather than spinning", async () => {
408412
vi.resetModules();
409413
const process = await import("@tauri-apps/plugin-process");
410414
const { useSettingsStore } = await import("../settingsStore");
@@ -414,7 +418,12 @@ describe("settingsStore", () => {
414418
updateVersion: null,
415419
});
416420
await useSettingsStore.getState().installUpdate();
421+
417422
expect(process.relaunch).not.toHaveBeenCalled();
423+
// It used to set "downloading" and return, leaving the status bar
424+
// reporting a download that was not happening (#569).
425+
expect(useSettingsStore.getState().updateStatus).toBe("error");
426+
expect(useSettingsStore.getState().updateError).toContain("no longer available");
418427
});
419428

420429
it("updates downloadProgress as bytes stream in via the onProgress callback", async () => {
@@ -442,7 +451,8 @@ describe("settingsStore", () => {
442451
await useSettingsStore.getState().installUpdate();
443452
const final = useSettingsStore.getState().downloadProgress;
444453
expect(final).toEqual({ transferred: 1000, total: 1000 });
445-
expect(process.relaunch).toHaveBeenCalledOnce();
454+
// The download finishing is not the restart happening.
455+
expect(process.relaunch).not.toHaveBeenCalled();
446456
});
447457

448458
it("surfaces the underlying error string in updateError", async () => {
@@ -462,5 +472,62 @@ describe("settingsStore", () => {
462472
"rpm install failed: signature verification failed",
463473
);
464474
});
475+
476+
it("refuses to restart while work would be lost, and says why", async () => {
477+
// The checks that authorised the download ran before it. A query
478+
// started or a tab edited since would otherwise be destroyed by a
479+
// restart nobody re-approved (#570).
480+
vi.resetModules();
481+
const process = await import("@tauri-apps/plugin-process");
482+
const { useResultStore } = await import("../resultStore");
483+
const { useSettingsStore } = await import("../settingsStore");
484+
485+
useSettingsStore.setState({ updateStatus: "downloaded", updateVersion: "1.0.0" });
486+
useResultStore.setState({ isExecuting: true });
487+
488+
await useSettingsStore.getState().restartToApply();
489+
490+
expect(process.relaunch).not.toHaveBeenCalled();
491+
expect(useSettingsStore.getState().updateStatus).toBe("error");
492+
expect(useSettingsStore.getState().updateError).toMatch(/query is still running/);
493+
494+
useResultStore.setState({ isExecuting: false });
495+
});
496+
497+
it("says the update is installed when the restart itself fails", async () => {
498+
// Telling the user to download again would be wrong: it is already on
499+
// disk, and quitting normally finishes the job.
500+
vi.resetModules();
501+
const process = await import("@tauri-apps/plugin-process");
502+
vi.mocked(process.relaunch).mockRejectedValueOnce(new Error("no permission"));
503+
const { useSettingsStore } = await import("../settingsStore");
504+
505+
useSettingsStore.setState({ updateStatus: "downloaded", updateVersion: "1.0.0" });
506+
await useSettingsStore.getState().restartToApply();
507+
508+
expect(useSettingsStore.getState().updateStatus).toBe("error");
509+
expect(useSettingsStore.getState().updateError).toMatch(/installed but the app could not restart/);
510+
expect(useSettingsStore.getState().updateError).toMatch(/Quit and reopen/);
511+
});
512+
513+
it("refuses to start a download while work would be lost", async () => {
514+
vi.resetModules();
515+
const { useResultStore } = await import("../resultStore");
516+
const { useSettingsStore } = await import("../settingsStore");
517+
const downloadAndInstall = vi.fn();
518+
519+
useSettingsStore.setState({
520+
pendingUpdate: { version: "1.0.0", downloadAndInstall } as never,
521+
updateStatus: "available",
522+
});
523+
useResultStore.setState({ isExecuting: true });
524+
525+
await useSettingsStore.getState().installUpdate();
526+
527+
expect(downloadAndInstall).not.toHaveBeenCalled();
528+
expect(useSettingsStore.getState().updateStatus).toBe("error");
529+
530+
useResultStore.setState({ isExecuting: false });
531+
});
465532
});
466533
});

‎src/stores/settingsStore.ts‎

Lines changed: 50 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@ import { relaunch } from "@tauri-apps/plugin-process";
22
import { check, type Update } from "@tauri-apps/plugin-updater";
33
import { create } from "zustand";
44
import { api } from "../lib/tauri-api";
5+
import { describeUpdateBlockers } from "../lib/update-guard";
56
import { type StorageErrorKey, useStorageErrorStore } from "./storageErrorStore";
67

78
export interface QuerySettings {
@@ -97,6 +98,7 @@ interface SettingsState {
9798
detectPlatform: () => Promise<void>;
9899
checkForUpdates: () => Promise<void>;
99100
installUpdate: () => Promise<void>;
101+
restartToApply: () => Promise<void>;
100102
setUpdateError: (message: string | null) => void;
101103
setQuerySettings: (settings: QuerySettings) => void;
102104
setFormatterSettings: (settings: FormatterSettings) => void;
@@ -191,14 +193,32 @@ export const useSettingsStore = create<SettingsState>((set, get) => ({
191193
},
192194

193195
installUpdate: async () => {
196+
// The refusal lives here rather than in the button that calls it, so a
197+
// second caller cannot arrive without it (#570).
198+
const blocked = describeUpdateBlockers();
199+
if (blocked) {
200+
set({ updateStatus: "error", updateError: blocked });
201+
return;
202+
}
203+
204+
const cached = useSettingsStore.getState().pendingUpdate;
205+
if (!cached) {
206+
// Nothing to install — most likely a check that resolved between the
207+
// click and this read and cleared it. Saying so beats leaving the
208+
// status bar reporting a download that is not happening (#569).
209+
set({
210+
updateStatus: "error",
211+
updateError: "The pending update is no longer available. Check for updates again.",
212+
});
213+
return;
214+
}
215+
194216
set({
195217
updateStatus: "downloading",
196218
updateError: null,
197219
downloadProgress: { transferred: 0, total: null },
198220
});
199221
try {
200-
const cached = useSettingsStore.getState().pendingUpdate;
201-
if (!cached) return;
202222
await cached.downloadAndInstall((event) => {
203223
const data = (event as { data?: { contentLength?: number; chunkLength?: number } }).data;
204224
if (event.event === "Started" && data?.contentLength != null) {
@@ -213,8 +233,11 @@ export const useSettingsStore = create<SettingsState>((set, get) => ({
213233
}));
214234
}
215235
});
236+
// Downloaded and staged, but not applied. Restarting is a separate act
237+
// the user chooses, because it closes the app: the checks above ran
238+
// before a download that can take minutes, and the state they looked at
239+
// may not be the state now (#344, #570).
216240
set({ updateStatus: "downloaded" });
217-
await relaunch();
218241
} catch (e) {
219242
console.error("Update install failed:", e);
220243
set({
@@ -225,6 +248,30 @@ export const useSettingsStore = create<SettingsState>((set, get) => ({
225248
}
226249
},
227250

251+
restartToApply: async () => {
252+
// Checked again, at the moment it matters. A query started or a tab
253+
// edited during the download would otherwise be destroyed by a restart
254+
// authorised minutes earlier.
255+
const blocked = describeUpdateBlockers();
256+
if (blocked) {
257+
set({ updateStatus: "error", updateError: blocked });
258+
return;
259+
}
260+
try {
261+
await relaunch();
262+
} catch (e) {
263+
console.error("Relaunch failed:", e);
264+
// The update is on disk either way, so say that rather than implying
265+
// it needs downloading again.
266+
set({
267+
updateStatus: "error",
268+
updateError: `The update is installed but the app could not restart itself: ${
269+
e instanceof Error ? e.message : String(e)
270+
}. Quit and reopen SQLPilot to finish.`,
271+
});
272+
}
273+
},
274+
228275
setUpdateError: (message) => set({ updateError: message }),
229276

230277
setQuerySettings: (settings) => {

0 commit comments

Comments
 (0)