Skip to content

Commit eeaac49

Browse files
t3dotggclaude
andauthored
fix: update all no longer runs agents twice or loses background work (#19291)
Co-authored-by: Claude Opus 5.5 <[email protected]>
1 parent 3bbfdc7 commit eeaac49

46 files changed

Lines changed: 2059 additions & 366 deletions

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

‎apps/desktop/src/backend/DesktopBackendManager.test.ts‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -264,7 +264,7 @@ describe("DesktopBackendManager", () => {
264264
assert.equal(spawnedCommand.options.additionalFds?.fd5?.type, "output");
265265
assert.equal(
266266
Duration.toMillis(Duration.fromInputUnsafe(spawnedCommand.options.forceKillAfter)),
267-
2_000,
267+
5_000,
268268
);
269269

270270
assert.deepEqual(yield* decodeBootstrap(bootstrapJson), configWithObservability);

‎apps/desktop/src/backend/DesktopBackendManager.ts‎

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -65,7 +65,9 @@ const MAX_PREFLIGHT_FAILURE_ATTEMPTS = 5;
6565
const DEFAULT_BACKEND_READINESS_TIMEOUT = Duration.minutes(1);
6666
const DEFAULT_BACKEND_READINESS_INTERVAL = Duration.millis(100);
6767
const DEFAULT_BACKEND_READINESS_REQUEST_TIMEOUT = Duration.seconds(1);
68-
const DEFAULT_BACKEND_TERMINATE_GRACE = Duration.seconds(2);
68+
// Same as the service launcher. A killed backend leaves its agents running,
69+
// and a busy one needs a few seconds to stop every provider session.
70+
const DEFAULT_BACKEND_TERMINATE_GRACE = Duration.seconds(5);
6971
const DEFAULT_BACKEND_OUTPUT_DRAIN_TIMEOUT = Duration.seconds(5);
7072
const BACKEND_READINESS_PATH = "/.well-known/t3/environment";
7173
const { logWarning: logBackendProcessWarning } =

‎apps/desktop/src/updates/DesktopUpdates.test.ts‎

Lines changed: 63 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -652,6 +652,67 @@ describe("DesktopUpdates", () => {
652652
).pipe(Effect.provide(Layer.merge(TestClock.layer(), harness.layer)));
653653
});
654654

655+
it.effect("records the version an install hands to the installer", () => {
656+
let recordsAtStop: ReadonlyArray<string> = [];
657+
const harness = makeHarness({
658+
stopBackend: Effect.sync(() => {
659+
recordsAtStop = [...harness.installRecords.values()];
660+
}),
661+
});
662+
663+
return Effect.scoped(
664+
Effect.gen(function* () {
665+
const updates = yield* DesktopUpdates.DesktopUpdates;
666+
yield* updates.configure;
667+
harness.emit("update-downloaded", { version: "1.2.4" });
668+
yield* flushCallbacks;
669+
670+
assert.isTrue((yield* updates.install).accepted);
671+
assert.deepEqual(
672+
recordsAtStop.map((record) => JSON.parse(record)),
673+
[{ fromVersion: "1.2.3", targetVersion: "1.2.4" }],
674+
);
675+
}),
676+
).pipe(Effect.provide(Layer.merge(TestClock.layer(), harness.layer)));
677+
});
678+
679+
it.effect("flags an install that did not apply and keeps the flag through checks", () => {
680+
const harness = makeHarness({
681+
installRecord: JSON.stringify({ fromVersion: "1.2.3", targetVersion: "1.2.4" }),
682+
});
683+
684+
return Effect.scoped(
685+
Effect.gen(function* () {
686+
const updates = yield* DesktopUpdates.DesktopUpdates;
687+
yield* updates.configure;
688+
assert.equal((yield* updates.getState).notAppliedVersion, "1.2.4");
689+
// Kept, so the next start on 1.2.3 still knows 1.2.4 did not apply.
690+
assert.isDefined(harness.previousInstallRecord());
691+
692+
harness.emit("update-available", { version: "1.2.4" });
693+
yield* flushCallbacks;
694+
const state = yield* updates.getState;
695+
assert.equal(state.status, "available");
696+
assert.equal(state.notAppliedVersion, "1.2.4");
697+
}),
698+
).pipe(Effect.provide(Layer.merge(TestClock.layer(), harness.layer)));
699+
});
700+
701+
it.effect("does not flag an install that applied", () => {
702+
const harness = makeHarness({
703+
installRecord: JSON.stringify({ fromVersion: "1.2.2", targetVersion: "1.2.3" }),
704+
});
705+
706+
return Effect.scoped(
707+
Effect.gen(function* () {
708+
const updates = yield* DesktopUpdates.DesktopUpdates;
709+
yield* updates.configure;
710+
assert.isUndefined((yield* updates.getState).notAppliedVersion);
711+
assert.isUndefined(harness.previousInstallRecord());
712+
}),
713+
).pipe(Effect.provide(Layer.merge(TestClock.layer(), harness.layer)));
714+
});
715+
655716
it.effect("drops the update restart marker when an install is interrupted", () =>
656717
Effect.gen(function* () {
657718
const stopping = yield* Deferred.make<void>();
@@ -703,6 +764,8 @@ describe("DesktopUpdates", () => {
703764
assert.deepEqual(harness.installSteps, ["quitAndInstall", "startBackend"]);
704765
// The restarted old backend must release its tunnel on a later quit.
705766
assert.equal(harness.updateRestartMarkers.size, 0);
767+
// The app never quit, so the next start must not report an unapplied install.
768+
assert.equal(harness.installRecords.size, 0);
706769
}),
707770
).pipe(Effect.provide(Layer.merge(TestClock.layer(), harness.layer)));
708771
});

‎apps/desktop/src/updates/DesktopUpdates.ts‎

Lines changed: 70 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -46,6 +46,7 @@ import {
4646
reduceDesktopUpdateStateOnInstallFailure,
4747
reduceDesktopUpdateStateOnNoUpdate,
4848
reduceDesktopUpdateStateOnUpdateAvailable,
49+
resolveNotAppliedInstallVersion,
4950
} from "./updateMachine.ts";
5051

5152
const AUTO_UPDATE_STARTUP_DELAY = "15 seconds";
@@ -72,6 +73,14 @@ const UpdateInfo = Schema.Struct({
7273
const DownloadProgressInfo = Schema.Struct({
7374
percent: Schema.Number,
7475
});
76+
/** Saved in the runtime folder before an install quits the app, read on the next start. */
77+
export const DESKTOP_UPDATE_INSTALL_RECORD_FILE = "desktop-update-install.json";
78+
const DesktopUpdateInstallRecord = Schema.fromJsonString(
79+
Schema.Struct({ fromVersion: Schema.String, targetVersion: Schema.String }),
80+
);
81+
const decodeInstallRecord = Schema.decodeUnknownEffect(DesktopUpdateInstallRecord);
82+
const encodeInstallRecord = Schema.encodeEffect(DesktopUpdateInstallRecord);
83+
7584
const decodeAppUpdateYmlConfig = Schema.decodeUnknownEffect(AppUpdateYmlConfig);
7685
const decodeUpdateInfo = Schema.decodeUnknownEffect(UpdateInfo);
7786
const decodeDownloadProgressInfo = Schema.decodeUnknownEffect(DownloadProgressInfo);
@@ -347,6 +356,7 @@ export const make = Effect.gen(function* () {
347356
const finishedUpdateActions = yield* PubSub.unbounded<UpdateAction>();
348357
const updaterConfiguredRef = yield* Ref.make(false);
349358
const lastLoggedDownloadMilestoneRef = yield* Ref.make(-1);
359+
const notAppliedVersionRef = yield* Ref.make(Option.none<string>());
350360
const updateStateRef = yield* Ref.make<DesktopUpdateState>(
351361
createInitialDesktopUpdateState(
352362
environment.appVersion,
@@ -600,11 +610,57 @@ export const make = Effect.gen(function* () {
600610
.remove(updateRestartMarkerPath, { force: true })
601611
.pipe(Effect.ignore);
602612

613+
// Records the version an install hands to the OS installer, so the next
614+
// start can tell whether it applied. Best effort, like the restart marker.
615+
const installRecordPath = environment.path.join(
616+
updateRestartMarkerDir,
617+
DESKTOP_UPDATE_INSTALL_RECORD_FILE,
618+
);
619+
const writeInstallRecord = (targetVersion: string) =>
620+
encodeInstallRecord({ fromVersion: environment.appVersion, targetVersion }).pipe(
621+
Effect.flatMap((text) => fileSystem.writeFileString(installRecordPath, text)),
622+
Effect.catch((error) =>
623+
logUpdaterWarning("Could not record the update install.", { errorTag: error._tag }),
624+
),
625+
);
626+
const removeInstallRecord = fileSystem
627+
.remove(installRecordPath, { force: true })
628+
.pipe(Effect.ignore);
629+
630+
// Reads the record of the last install. Returns the version it did not
631+
// apply, when the app came back on the version it installed from. That
632+
// record stays through later starts, until the version changes or a new
633+
// install replaces it, so no restart forgets the failed version.
634+
const readNotAppliedInstallVersion = fileSystem.readFileString(installRecordPath).pipe(
635+
Effect.flatMap(decodeInstallRecord),
636+
Effect.option,
637+
Effect.map((record) =>
638+
Option.flatMap(record, (value) =>
639+
Option.fromNullishOr(resolveNotAppliedInstallVersion(value, environment.appVersion)),
640+
),
641+
),
642+
Effect.tap((notAppliedVersion) =>
643+
Option.isNone(notAppliedVersion) ? removeInstallRecord : Effect.void,
644+
),
645+
);
646+
647+
const baseUpdateState = (channel: DesktopUpdateChannel, enabled: boolean) =>
648+
Ref.get(notAppliedVersionRef).pipe(
649+
Effect.map((notAppliedVersion) => ({
650+
...createBaseUpdateState(channel, enabled, environment),
651+
...Option.match(notAppliedVersion, {
652+
onNone: () => ({}),
653+
onSome: (version) => ({ notAppliedVersion: version }),
654+
}),
655+
})),
656+
);
657+
603658
const resetInstallAction = Effect.all(
604659
[
605660
finishUpdateAction("install"),
606661
Ref.set(desktopState.quitting, false),
607662
removeUpdateRestartMarker,
663+
removeInstallRecord,
608664
],
609665
{ discard: true },
610666
);
@@ -621,6 +677,7 @@ export const make = Effect.gen(function* () {
621677

622678
yield* Ref.set(desktopState.quitting, false);
623679
yield* removeUpdateRestartMarker;
680+
yield* removeInstallRecord;
624681
yield* Effect.gen(function* () {
625682
const instances = yield* pool.list;
626683
const restartExit = yield* Effect.forEach(instances, (instance) => instance.start, {
@@ -691,6 +748,8 @@ export const make = Effect.gen(function* () {
691748

692749
return yield* Effect.gen(function* () {
693750
yield* writeUpdateRestartMarker;
751+
const { downloadedVersion } = yield* Ref.get(updateStateRef);
752+
if (downloadedVersion !== null) yield* writeInstallRecord(downloadedVersion);
694753
// Stop every backend in the pool, not just the primary. With
695754
// parallel WSL + Windows backends, leaving the WSL instance up
696755
// means quitAndInstall's app.quit() exits before the pool's
@@ -985,6 +1044,15 @@ export const make = Effect.gen(function* () {
9851044
const appUpdateYmlConfig = yield* readAppUpdateYml;
9861045
yield* Ref.set(appUpdateYmlConfigRef, appUpdateYmlConfig);
9871046

1047+
const notAppliedVersion = yield* readNotAppliedInstallVersion;
1048+
yield* Ref.set(notAppliedVersionRef, notAppliedVersion);
1049+
if (Option.isSome(notAppliedVersion)) {
1050+
yield* logUpdaterWarning("the last update install did not apply", {
1051+
version: environment.appVersion,
1052+
targetVersion: notAppliedVersion.value,
1053+
});
1054+
}
1055+
9881056
if (config.mockUpdates) {
9891057
yield* electronUpdater.setFeedURL({
9901058
provider: "generic",
@@ -994,7 +1062,7 @@ export const make = Effect.gen(function* () {
9941062

9951063
const settings = yield* desktopSettings.get;
9961064
const enabled = yield* shouldEnableAutoUpdates;
997-
yield* setState(createBaseUpdateState(settings.updateChannel, enabled, environment));
1065+
yield* setState(yield* baseUpdateState(settings.updateChannel, enabled));
9981066
if (!enabled) {
9991067
return;
10001068
}
@@ -1065,7 +1133,7 @@ export const make = Effect.gen(function* () {
10651133
);
10661134

10671135
const enabled = yield* shouldEnableAutoUpdates;
1068-
yield* setState(createBaseUpdateState(nextChannel, enabled, environment));
1136+
yield* setState(yield* baseUpdateState(nextChannel, enabled));
10691137

10701138
if (!enabled || !(yield* Ref.get(updaterConfiguredRef))) {
10711139
return yield* Ref.get(updateStateRef);

‎apps/desktop/src/updates/remoteUpdateFlow.test.ts‎

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -34,6 +34,24 @@ function makeState(overrides: Partial<DesktopUpdateState> = {}): DesktopUpdateSt
3434
}
3535

3636
describe("nextRemoteDesktopUpdateStep", () => {
37+
it("does not install again a version that did not apply on this machine", () => {
38+
const step = nextRemoteDesktopUpdateStep(
39+
makeState({ status: "available", availableVersion: "1.2.4", notAppliedVersion: "1.2.4" }),
40+
NO_ATTEMPTS,
41+
null,
42+
);
43+
assert.equal(step.action, "done");
44+
assert.include(step.action === "done" ? step.reason : "", "1.2.4 did not apply");
45+
assert.deepEqual(
46+
nextRemoteDesktopUpdateStep(
47+
makeState({ status: "available", availableVersion: "1.2.5", notAppliedVersion: "1.2.4" }),
48+
NO_ATTEMPTS,
49+
null,
50+
),
51+
{ action: "download" },
52+
);
53+
});
54+
3755
it("fails immediately when updates are disabled, preferring the known reason", () => {
3856
const state = makeState({ enabled: false, status: "disabled" });
3957
assert.deepEqual(nextRemoteDesktopUpdateStep(state, NO_ATTEMPTS, "dev build"), {

‎apps/desktop/src/updates/remoteUpdateFlow.ts‎

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -52,6 +52,19 @@ export function nextRemoteDesktopUpdateStep(
5252
reason: disabledReason ?? "Automatic updates are disabled on this machine.",
5353
};
5454
}
55+
// An install of this version already failed to apply here. Installing it
56+
// again from afar would stop the app's threads for nothing, so only the user
57+
// on this machine retries it.
58+
if (
59+
state.notAppliedVersion !== undefined &&
60+
(state.downloadedVersion ?? state.availableVersion) === state.notAppliedVersion
61+
) {
62+
return {
63+
action: "done",
64+
outcome: "failed",
65+
reason: `Update ${state.notAppliedVersion} did not apply on this machine. Retry it from the desktop app there.`,
66+
};
67+
}
5568
// Mirror installDownloadedUpdate's own admission rule exactly, so the run
5669
// never reports an install that the updater then refuses. A download
5770
// survives an unrelated background updater error (errorContext null) and

‎apps/desktop/src/updates/updateMachine.test.ts‎

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,7 @@ import {
1111
reduceDesktopUpdateStateOnInstallFailure,
1212
reduceDesktopUpdateStateOnNoUpdate,
1313
reduceDesktopUpdateStateOnUpdateAvailable,
14+
resolveNotAppliedInstallVersion,
1415
} from "./updateMachine.ts";
1516

1617
const runtimeInfo = {
@@ -255,3 +256,16 @@ describe("updateMachine", () => {
255256
expect(state.omittedReleaseCount).toBe(0);
256257
});
257258
});
259+
260+
describe("resolveNotAppliedInstallVersion", () => {
261+
const record = { fromVersion: "1.2.3", targetVersion: "1.2.4" };
262+
263+
it("flags the target when the app came back on the version it installed from", () => {
264+
expect(resolveNotAppliedInstallVersion(record, "1.2.3")).toBe("1.2.4");
265+
});
266+
267+
it("stays quiet when the install applied or the app runs another version", () => {
268+
expect(resolveNotAppliedInstallVersion(record, "1.2.4")).toBeNull();
269+
expect(resolveNotAppliedInstallVersion(record, "1.2.5")).toBeNull();
270+
});
271+
});

‎apps/desktop/src/updates/updateMachine.ts‎

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -211,3 +211,23 @@ export function reduceDesktopUpdateStateOnInstallFailure(
211211
canRetry: true,
212212
};
213213
}
214+
215+
/** The install this app handed to the OS installer, saved right before it quits. */
216+
export interface DesktopUpdateInstallRecord {
217+
readonly fromVersion: string;
218+
readonly targetVersion: string;
219+
}
220+
221+
/**
222+
* Read on the next start: the version an install did not apply, because the
223+
* app came back on the version it installed from. Null when the install
224+
* applied, or when the app now runs some other version.
225+
*/
226+
export function resolveNotAppliedInstallVersion(
227+
record: DesktopUpdateInstallRecord,
228+
appVersion: string,
229+
): string | null {
230+
return record.fromVersion === appVersion && record.targetVersion !== appVersion
231+
? record.targetVersion
232+
: null;
233+
}

‎apps/desktop/src/updates/updatesTestHarness.ts‎

Lines changed: 25 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -37,6 +37,8 @@ export interface UpdatesHarnessOptions {
3737
readonly platform?: NodeJS.Platform;
3838
/** Contents of the resources/package-type marker a Linux package ships. */
3939
readonly packageType?: string | undefined;
40+
/** Contents of the install record a previous run left behind. */
41+
readonly installRecord?: string | undefined;
4042
}
4143

4244
export function makeHarness(options: UpdatesHarnessOptions = {}) {
@@ -208,12 +210,21 @@ export function makeHarness(options: UpdatesHarnessOptions = {}) {
208210
} satisfies DesktopAppSettings.DesktopAppSettings["Service"])
209211
: DesktopAppSettings.layer;
210212

211-
// Tracks the restart markers installs leave, so installs stay free of real
212-
// disk I/O that would outrun the tests' settle loops.
213+
// Tracks the restart markers and install records installs leave, so
214+
// installs stay free of real disk I/O that would outrun the tests' settle loops.
213215
const updateRestartMarkers = new Set<string>();
216+
// Contents of the install record, by path once an install writes one.
217+
const installRecords = new Map<string, string>();
218+
let previousInstallRecord = options.installRecord;
219+
const isInstallRecord = (path: string) =>
220+
path.endsWith(DesktopUpdates.DESKTOP_UPDATE_INSTALL_RECORD_FILE);
214221
const layerFileSystem = FileSystem.layerNoop({
215-
readFileString: (path) =>
216-
path === "/missing/resources/package-type" && options.packageType !== undefined
222+
readFileString: (path) => {
223+
const installRecord = isInstallRecord(path)
224+
? (installRecords.get(path) ?? previousInstallRecord)
225+
: undefined;
226+
if (installRecord !== undefined) return Effect.succeed(installRecord);
227+
return path === "/missing/resources/package-type" && options.packageType !== undefined
217228
? Effect.succeed(options.packageType)
218229
: Effect.fail(
219230
PlatformError.systemError({
@@ -222,15 +233,19 @@ export function makeHarness(options: UpdatesHarnessOptions = {}) {
222233
_tag: "NotFound",
223234
pathOrDescriptor: path,
224235
}),
225-
),
236+
);
237+
},
226238
makeDirectory: () => Effect.void,
227-
writeFileString: (path) =>
239+
writeFileString: (path, data) =>
228240
Effect.sync(() => {
229-
updateRestartMarkers.add(path);
241+
if (isInstallRecord(path)) installRecords.set(path, data);
242+
else updateRestartMarkers.add(path);
230243
}),
231244
remove: (path) =>
232245
Effect.sync(() => {
233246
updateRestartMarkers.delete(path);
247+
installRecords.delete(path);
248+
if (isInstallRecord(path)) previousInstallRecord = undefined;
234249
}),
235250
});
236251

@@ -259,6 +274,9 @@ export function makeHarness(options: UpdatesHarnessOptions = {}) {
259274
quitAndInstalls: () => quitAndInstallCount,
260275
installSteps,
261276
updateRestartMarkers,
277+
installRecords,
278+
/** The record the test started with, until the app removes it. */
279+
previousInstallRecord: () => previousInstallRecord,
262280
downloadCount: () => downloadCount,
263281
feedUrls: (): ElectronUpdater.ElectronUpdaterFeedUrl[] => feedUrls,
264282
fullChangelog: () => fullChangelog,

0 commit comments

Comments
 (0)