Compare commits
5
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
159021e95e | ||
|
|
4b35ac856d | ||
|
|
efb25b1596 | ||
|
|
f6022f33d0 | ||
|
|
7d233d93ad |
No files matched your search
@@ -26,6 +26,7 @@ import * as DesktopServerExposure from "../backend/DesktopServerExposure.ts";
|
||||
import * as DesktopAppSettings from "../settings/DesktopAppSettings.ts";
|
||||
import * as DesktopShellEnvironment from "../shell/DesktopShellEnvironment.ts";
|
||||
import * as DesktopState from "./DesktopState.ts";
|
||||
import * as DesktopRemoteUpdates from "../updates/DesktopRemoteUpdates.ts";
|
||||
import * as DesktopUpdates from "../updates/DesktopUpdates.ts";
|
||||
import * as DesktopWslBackend from "../wsl/DesktopWslBackend.ts";
|
||||
|
||||
@@ -286,6 +287,7 @@ const startup = Effect.gen(function* () {
|
||||
yield* appIdentity.configure;
|
||||
yield* applicationMenu.configure;
|
||||
yield* updates.configure;
|
||||
yield* DesktopRemoteUpdates.listen;
|
||||
yield* linuxUrlHandler.register;
|
||||
yield* bootstrap.pipe(Effect.catchCause((cause) => fatalStartupCause("bootstrap", cause)));
|
||||
}).pipe(Effect.withSpan("desktop.startup"));
|
||||
|
||||
@@ -165,6 +165,8 @@ function makeTestInstance(input: MakeInstanceInput) {
|
||||
handleControlForSource: (_sourceId, message) =>
|
||||
(input.desktopTelemetryPublisher?.handleControl ?? (() => Effect.void))(message),
|
||||
removeControlSource: () => Effect.void,
|
||||
publishUpdateReport: () => Effect.void,
|
||||
updateRequests: Stream.empty,
|
||||
...input.desktopTelemetryPublisher,
|
||||
}),
|
||||
);
|
||||
|
||||
@@ -72,6 +72,8 @@ function makePoolLayer(
|
||||
handleControl: () => Effect.void,
|
||||
handleControlForSource: () => Effect.void,
|
||||
removeControlSource: () => Effect.void,
|
||||
publishUpdateReport: () => Effect.void,
|
||||
updateRequests: Stream.empty,
|
||||
}),
|
||||
Layer.succeed(DesktopBackendConfiguration.DesktopBackendConfiguration, {
|
||||
resolvePrimary: Effect.die("unexpected primary config resolve"),
|
||||
|
||||
@@ -156,8 +156,11 @@ describe("DesktopTelemetryPublisher", () => {
|
||||
decodeMessage(decoder.decode(bytes).trim()),
|
||||
);
|
||||
|
||||
assert.equal(messages[0]?.type, "desktopTelemetryHello");
|
||||
assert.equal(messages[0]?.electronPid, process.pid);
|
||||
const hello = messages[0];
|
||||
if (hello?.type !== "desktopTelemetryHello") {
|
||||
return assert.fail("Expected the first telemetry message to be the hello.");
|
||||
}
|
||||
assert.equal(hello.electronPid, process.pid);
|
||||
const initialSnapshot = messages[1];
|
||||
if (initialSnapshot?.type !== "desktopTelemetry") {
|
||||
return assert.fail("Expected the second telemetry message to be a snapshot.");
|
||||
@@ -385,4 +388,80 @@ describe("DesktopTelemetryPublisher", () => {
|
||||
}).pipe(Effect.provide(layer));
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("routes requestDesktopUpdate control messages and replays update reports", () =>
|
||||
Effect.gen(function* () {
|
||||
const powerLayer = Layer.succeed(
|
||||
ElectronPowerMonitor.ElectronPowerMonitor,
|
||||
ElectronPowerMonitor.ElectronPowerMonitor.of({
|
||||
isOnBatteryPower: Effect.succeed(false),
|
||||
getSystemIdleTime: Effect.succeed(0),
|
||||
getSystemIdleState: () => Effect.succeed("active"),
|
||||
getCurrentThermalState: Effect.succeed("nominal"),
|
||||
onSimpleEvent: () => Effect.void,
|
||||
onThermalStateChange: () => Effect.void,
|
||||
onSpeedLimitChange: () => Effect.void,
|
||||
}),
|
||||
);
|
||||
const layer = DesktopTelemetryPublisher.layer.pipe(
|
||||
Layer.provide(Layer.mergeAll(makeElectronAppLayer([]), powerLayer)),
|
||||
);
|
||||
|
||||
yield* Effect.gen(function* () {
|
||||
const publisher = yield* DesktopTelemetryPublisher.DesktopTelemetryPublisher;
|
||||
|
||||
const requestFiber = yield* Stream.runHead(publisher.updateRequests).pipe(Effect.forkChild);
|
||||
yield* Effect.yieldNow;
|
||||
yield* publisher.handleControlForSource("test", {
|
||||
version: 1,
|
||||
type: "requestDesktopUpdate",
|
||||
requestId: "req-9",
|
||||
});
|
||||
const received = yield* Fiber.join(requestFiber);
|
||||
assert.equal(Option.getOrThrow(received).requestId, "req-9");
|
||||
|
||||
const report = {
|
||||
version: 1,
|
||||
type: "desktopUpdateStatus",
|
||||
outcome: "up-to-date",
|
||||
state: {
|
||||
enabled: true,
|
||||
status: "up-to-date",
|
||||
channel: "latest",
|
||||
currentVersion: "1.2.3",
|
||||
hostArch: "arm64",
|
||||
appArch: "arm64",
|
||||
runningUnderArm64Translation: false,
|
||||
availableVersion: null,
|
||||
downloadedVersion: null,
|
||||
releaseNotes: [],
|
||||
downloadPercent: null,
|
||||
checkedAt: null,
|
||||
message: null,
|
||||
errorContext: null,
|
||||
canRetry: false,
|
||||
},
|
||||
} as const;
|
||||
yield* publisher.publishUpdateReport(report);
|
||||
|
||||
// A subscriber that attaches after the publish (the backend spawned
|
||||
// by a relaunch) still sees the latest report replayed.
|
||||
const decoder = new TextDecoder();
|
||||
const decodeMessage = Schema.decodeUnknownEffect(
|
||||
Schema.fromJsonString(DesktopHostTelemetryMessage),
|
||||
);
|
||||
const replayed = yield* publisher.encoded.pipe(
|
||||
Stream.mapEffect((bytes) => decodeMessage(decoder.decode(bytes).trim())),
|
||||
Stream.filter((message) => message.type === "desktopUpdateStatus"),
|
||||
Stream.runHead,
|
||||
);
|
||||
const replayedReport = Option.getOrThrow(replayed);
|
||||
if (replayedReport.type !== "desktopUpdateStatus") {
|
||||
return assert.fail("Expected a desktop update status report.");
|
||||
}
|
||||
assert.equal(replayedReport.outcome, "up-to-date");
|
||||
assert.equal(replayedReport.state.currentVersion, "1.2.3");
|
||||
}).pipe(Effect.provide(layer));
|
||||
}),
|
||||
);
|
||||
});
|
||||
@@ -2,6 +2,8 @@ import {
|
||||
DesktopHostTelemetryMessage,
|
||||
type DesktopHostTelemetrySnapshot,
|
||||
type DesktopTelemetryControlMessage,
|
||||
type DesktopTelemetryRequestDesktopUpdate,
|
||||
type DesktopUpdateStatusReport,
|
||||
type HostPowerSnapshot,
|
||||
} from "@t3tools/contracts";
|
||||
import * as Cause from "effect/Cause";
|
||||
@@ -65,6 +67,12 @@ export class DesktopTelemetryPublisher extends Context.Service<
|
||||
message: DesktopTelemetryControlMessage,
|
||||
) => Effect.Effect<void>;
|
||||
readonly removeControlSource: (sourceId: string) => Effect.Effect<void>;
|
||||
/** Sends the report to the attached backend and replays the latest one
|
||||
to backends that attach later (including the one spawned after a
|
||||
relaunch). */
|
||||
readonly publishUpdateReport: (report: DesktopUpdateStatusReport) => Effect.Effect<void>;
|
||||
/** Update requests received over the control channel. Single consumer. */
|
||||
readonly updateRequests: Stream.Stream<DesktopTelemetryRequestDesktopUpdate>;
|
||||
}
|
||||
>()("@t3tools/desktop/telemetry/DesktopTelemetryPublisher") {}
|
||||
|
||||
@@ -160,6 +168,9 @@ export const make = Effect.fn("desktop.telemetryPublisher.make")(function* () {
|
||||
const latest = yield* Ref.make(Option.none<DesktopHostTelemetrySnapshot>());
|
||||
const changes = yield* PubSub.sliding<DesktopHostTelemetrySnapshot>(8);
|
||||
const sequence = yield* Ref.make(0);
|
||||
const latestUpdateReport = yield* Ref.make(Option.none<DesktopUpdateStatusReport>());
|
||||
const updateReportChanges = yield* PubSub.sliding<DesktopUpdateStatusReport>(16);
|
||||
const updateRequestQueue = yield* Queue.unbounded<DesktopTelemetryRequestDesktopUpdate>();
|
||||
|
||||
const offer = (event: PowerEvent): void => {
|
||||
Queue.offerUnsafe(powerEvents, event);
|
||||
@@ -324,6 +335,8 @@ export const make = Effect.fn("desktop.telemetryPublisher.make")(function* () {
|
||||
active: Duration.millis(message.activeIntervalMs),
|
||||
idle: Duration.millis(message.idleIntervalMs),
|
||||
}).pipe(Effect.andThen(Queue.offer(sampleTriggers, undefined)), Effect.asVoid);
|
||||
case "requestDesktopUpdate":
|
||||
return Queue.offer(updateRequestQueue, message).pipe(Effect.asVoid);
|
||||
}
|
||||
};
|
||||
const removeControlSource: DesktopTelemetryPublisher["Service"]["removeControlSource"] = (
|
||||
@@ -357,15 +370,36 @@ export const make = Effect.fn("desktop.telemetryPublisher.make")(function* () {
|
||||
);
|
||||
}),
|
||||
);
|
||||
const updateReports = Stream.unwrap(
|
||||
Effect.gen(function* () {
|
||||
const subscription = yield* PubSub.subscribe(updateReportChanges);
|
||||
const initial = yield* Ref.get(latestUpdateReport);
|
||||
return Stream.concat(
|
||||
Option.match(initial, {
|
||||
onNone: () => Stream.empty,
|
||||
onSome: Stream.make,
|
||||
}),
|
||||
Stream.fromSubscription(subscription),
|
||||
);
|
||||
}),
|
||||
);
|
||||
const encoded = Stream.concat(
|
||||
Stream.make({
|
||||
version: 1,
|
||||
type: "desktopTelemetryHello",
|
||||
electronPid: process.pid,
|
||||
} as const),
|
||||
snapshots,
|
||||
Stream.merge(snapshots, updateReports),
|
||||
).pipe(Stream.map((message) => textEncoder.encode(`${encodeMessage(message)}\n`)));
|
||||
|
||||
const publishUpdateReport: DesktopTelemetryPublisher["Service"]["publishUpdateReport"] = (
|
||||
report,
|
||||
) =>
|
||||
Ref.set(latestUpdateReport, Option.some(report)).pipe(
|
||||
Effect.andThen(PubSub.publish(updateReportChanges, report)),
|
||||
Effect.asVoid,
|
||||
);
|
||||
|
||||
return DesktopTelemetryPublisher.of({
|
||||
latest: Ref.get(latest),
|
||||
changes: Stream.fromPubSub(changes),
|
||||
@@ -373,6 +407,8 @@ export const make = Effect.fn("desktop.telemetryPublisher.make")(function* () {
|
||||
handleControl,
|
||||
handleControlForSource,
|
||||
removeControlSource,
|
||||
publishUpdateReport,
|
||||
updateRequests: Stream.fromQueue(updateRequestQueue),
|
||||
});
|
||||
});
|
||||
|
||||
|
||||
@@ -0,0 +1,221 @@
|
||||
import { assert, describe, it } from "@effect/vitest";
|
||||
import type {
|
||||
DesktopTelemetryRequestDesktopUpdate,
|
||||
DesktopUpdateStatusReport,
|
||||
} from "@t3tools/contracts";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as Queue from "effect/Queue";
|
||||
import * as Stream from "effect/Stream";
|
||||
import * as TestClock from "effect/testing/TestClock";
|
||||
|
||||
import * as ElectronUpdater from "../electron/ElectronUpdater.ts";
|
||||
import * as DesktopTelemetryPublisher from "../telemetry/DesktopTelemetryPublisher.ts";
|
||||
import * as DesktopRemoteUpdates from "./DesktopRemoteUpdates.ts";
|
||||
import * as DesktopUpdates from "./DesktopUpdates.ts";
|
||||
import { makeHarness } from "./updatesTestHarness.ts";
|
||||
|
||||
// The remote flow hops between the test runtime's fibers and the updater's
|
||||
// runPromise-driven event handlers, so settling needs real microtask turns,
|
||||
// not just fiber yields.
|
||||
const settle = Effect.gen(function* () {
|
||||
for (let i = 0; i < 20; i += 1) {
|
||||
yield* Effect.yieldNow;
|
||||
yield* Effect.promise(() => Promise.resolve());
|
||||
}
|
||||
});
|
||||
|
||||
const request = (requestId: string): DesktopTelemetryRequestDesktopUpdate => ({
|
||||
version: 1,
|
||||
type: "requestDesktopUpdate",
|
||||
requestId,
|
||||
});
|
||||
|
||||
function runRemoteUpdatesTest(
|
||||
harness: ReturnType<typeof makeHarness>,
|
||||
body: (context: {
|
||||
readonly reports: DesktopUpdateStatusReport[];
|
||||
readonly requests: Queue.Queue<DesktopTelemetryRequestDesktopUpdate>;
|
||||
}) => Effect.Effect<void, never, DesktopUpdates.DesktopUpdates>,
|
||||
) {
|
||||
return Effect.scoped(
|
||||
Effect.gen(function* () {
|
||||
const requests = yield* Queue.unbounded<DesktopTelemetryRequestDesktopUpdate>();
|
||||
const reports: DesktopUpdateStatusReport[] = [];
|
||||
const publisher = DesktopTelemetryPublisher.DesktopTelemetryPublisher.of({
|
||||
latest: Effect.succeedNone,
|
||||
changes: Stream.empty,
|
||||
encoded: Stream.empty,
|
||||
handleControl: () => Effect.void,
|
||||
handleControlForSource: () => Effect.void,
|
||||
removeControlSource: () => Effect.void,
|
||||
publishUpdateReport: (report) =>
|
||||
Effect.sync(() => {
|
||||
reports.push(report);
|
||||
}),
|
||||
updateRequests: Stream.fromQueue(requests),
|
||||
});
|
||||
|
||||
const updates = yield* DesktopUpdates.DesktopUpdates;
|
||||
yield* updates.configure;
|
||||
yield* DesktopRemoteUpdates.listen.pipe(
|
||||
Effect.provideService(DesktopTelemetryPublisher.DesktopTelemetryPublisher, publisher),
|
||||
);
|
||||
yield* settle;
|
||||
yield* body({ reports, requests });
|
||||
}),
|
||||
).pipe(Effect.provide(Layer.merge(TestClock.layer(), harness.layer)));
|
||||
}
|
||||
|
||||
function terminalReports(reports: DesktopUpdateStatusReport[]): DesktopUpdateStatusReport[] {
|
||||
return reports.filter((report) => report.outcome !== undefined);
|
||||
}
|
||||
|
||||
describe("DesktopRemoteUpdates", () => {
|
||||
it.effect("drives check, download, and install with no local confirmation", () => {
|
||||
const harness = makeHarness();
|
||||
|
||||
return runRemoteUpdatesTest(harness, ({ reports, requests }) =>
|
||||
Effect.gen(function* () {
|
||||
yield* Queue.offer(requests, request("req-1"));
|
||||
yield* settle;
|
||||
assert.equal(harness.checkCount(), 1);
|
||||
|
||||
harness.emit("update-available", { version: "1.2.4" });
|
||||
yield* settle;
|
||||
harness.emit("update-downloaded", { version: "1.2.4" });
|
||||
yield* settle;
|
||||
|
||||
const terminals = terminalReports(reports);
|
||||
assert.equal(terminals.length, 1);
|
||||
assert.equal(terminals[0]?.outcome, "installing");
|
||||
assert.equal(terminals[0]?.requestId, "req-1");
|
||||
assert.equal(harness.quitAndInstalls(), 1);
|
||||
|
||||
// The mirror stamped the in-run state changes with the request id.
|
||||
const statuses = reports
|
||||
.filter((report) => report.requestId === "req-1")
|
||||
.map((report) => report.state.status);
|
||||
assert.include(statuses, "available");
|
||||
assert.include(statuses, "downloaded");
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
it.effect("reports a failed outcome when quitAndInstall fails", () => {
|
||||
const harness = makeHarness({
|
||||
quitAndInstall: Effect.fail(
|
||||
new ElectronUpdater.ElectronUpdaterQuitAndInstallError({
|
||||
channel: "latest",
|
||||
isSilent: true,
|
||||
isForceRunAfter: true,
|
||||
cause: new Error("spawn failed"),
|
||||
}),
|
||||
),
|
||||
});
|
||||
|
||||
return runRemoteUpdatesTest(harness, ({ reports, requests }) =>
|
||||
Effect.gen(function* () {
|
||||
yield* Queue.offer(requests, request("req-4"));
|
||||
yield* settle;
|
||||
harness.emit("update-available", { version: "1.2.4" });
|
||||
yield* settle;
|
||||
harness.emit("update-downloaded", { version: "1.2.4" });
|
||||
yield* settle;
|
||||
|
||||
// Install failures reduce to status "downloaded" + errorContext
|
||||
// "install"; the run must still end with a failed report after the
|
||||
// premature "installing" one.
|
||||
const terminals = terminalReports(reports);
|
||||
assert.deepEqual(
|
||||
terminals.map((report) => report.outcome),
|
||||
["installing", "failed"],
|
||||
);
|
||||
assert.equal(terminals[1]?.state.errorContext, "install");
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
it.effect("does not misread a lingering install error as a failed retry", () => {
|
||||
let installAttempts = 0;
|
||||
const harness = makeHarness({
|
||||
quitAndInstall: Effect.suspend(() => {
|
||||
installAttempts += 1;
|
||||
return installAttempts === 1
|
||||
? Effect.fail(
|
||||
new ElectronUpdater.ElectronUpdaterQuitAndInstallError({
|
||||
channel: "latest",
|
||||
isSilent: true,
|
||||
isForceRunAfter: true,
|
||||
cause: new Error("first attempt failed"),
|
||||
}),
|
||||
)
|
||||
: Effect.void;
|
||||
}),
|
||||
});
|
||||
|
||||
return runRemoteUpdatesTest(harness, ({ reports, requests }) =>
|
||||
Effect.gen(function* () {
|
||||
yield* Queue.offer(requests, request("req-5"));
|
||||
yield* settle;
|
||||
harness.emit("update-available", { version: "1.2.4" });
|
||||
yield* settle;
|
||||
harness.emit("update-downloaded", { version: "1.2.4" });
|
||||
yield* settle;
|
||||
// First run failed; state is "downloaded" with a lingering
|
||||
// errorContext "install". The retry succeeds and must not report
|
||||
// that leftover as a fresh failure.
|
||||
yield* Queue.offer(requests, request("req-6"));
|
||||
yield* settle;
|
||||
|
||||
const retryTerminals = terminalReports(reports).filter(
|
||||
(report) => report.requestId === "req-6",
|
||||
);
|
||||
assert.deepEqual(
|
||||
retryTerminals.map((report) => report.outcome),
|
||||
["installing"],
|
||||
);
|
||||
assert.equal(harness.quitAndInstalls(), 2);
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
it.effect("reports up-to-date without installing when there is no update", () => {
|
||||
const harness = makeHarness();
|
||||
|
||||
return runRemoteUpdatesTest(harness, ({ reports, requests }) =>
|
||||
Effect.gen(function* () {
|
||||
yield* Queue.offer(requests, request("req-2"));
|
||||
yield* settle;
|
||||
harness.emit("update-not-available");
|
||||
yield* settle;
|
||||
|
||||
const terminals = terminalReports(reports);
|
||||
assert.equal(terminals.length, 1);
|
||||
assert.equal(terminals[0]?.outcome, "up-to-date");
|
||||
assert.equal(terminals[0]?.requestId, "req-2");
|
||||
assert.equal(harness.quitAndInstalls(), 0);
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
it.effect("fails fast with the disabled reason when updates are off", () => {
|
||||
const harness = makeHarness({ env: { T3CODE_DISABLE_AUTO_UPDATE: "true" } });
|
||||
|
||||
return runRemoteUpdatesTest(harness, ({ reports, requests }) =>
|
||||
Effect.gen(function* () {
|
||||
yield* Queue.offer(requests, request("req-3"));
|
||||
yield* settle;
|
||||
|
||||
const terminals = terminalReports(reports);
|
||||
assert.equal(terminals.length, 1);
|
||||
assert.equal(terminals[0]?.outcome, "failed");
|
||||
assert.equal(
|
||||
terminals[0]?.reason,
|
||||
"Automatic updates are disabled by the T3CODE_DISABLE_AUTO_UPDATE setting.",
|
||||
);
|
||||
assert.equal(harness.quitAndInstalls(), 0);
|
||||
}),
|
||||
);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,148 @@
|
||||
import type {
|
||||
DesktopTelemetryRequestDesktopUpdate,
|
||||
DesktopUpdateRemoteOutcome,
|
||||
DesktopUpdateState,
|
||||
} from "@t3tools/contracts";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Option from "effect/Option";
|
||||
import * as Ref from "effect/Ref";
|
||||
import type * as Scope from "effect/Scope";
|
||||
import * as Stream from "effect/Stream";
|
||||
|
||||
import * as DesktopObservability from "../app/DesktopObservability.ts";
|
||||
import * as DesktopTelemetryPublisher from "../telemetry/DesktopTelemetryPublisher.ts";
|
||||
import * as DesktopUpdates from "./DesktopUpdates.ts";
|
||||
import {
|
||||
nextRemoteDesktopUpdateStep,
|
||||
type RemoteDesktopUpdateAttempts,
|
||||
} from "./remoteUpdateFlow.ts";
|
||||
|
||||
const { logInfo, logError } = DesktopObservability.makeComponentLogger("desktop-remote-updates");
|
||||
|
||||
/**
|
||||
* Server-triggered desktop updates. Forks two fibers into the surrounding
|
||||
* scope: one mirrors every updater state change to the attached backend (so
|
||||
* the server always knows the desktop's update state), one consumes
|
||||
* requestDesktopUpdate control messages and drives check -> download ->
|
||||
* quit-and-install with no local confirmation. The remote click that caused
|
||||
* the request is the consent.
|
||||
*/
|
||||
export const listen: Effect.Effect<
|
||||
void,
|
||||
never,
|
||||
DesktopUpdates.DesktopUpdates | DesktopTelemetryPublisher.DesktopTelemetryPublisher | Scope.Scope
|
||||
> = Effect.gen(function* () {
|
||||
const updates = yield* DesktopUpdates.DesktopUpdates;
|
||||
const publisher = yield* DesktopTelemetryPublisher.DesktopTelemetryPublisher;
|
||||
const activeRequestIdRef = yield* Ref.make(Option.none<string>());
|
||||
|
||||
const publishReport = (
|
||||
state: DesktopUpdateState,
|
||||
terminal?: { readonly outcome: DesktopUpdateRemoteOutcome; readonly reason?: string },
|
||||
): Effect.Effect<void> =>
|
||||
Ref.get(activeRequestIdRef).pipe(
|
||||
Effect.flatMap((requestId) =>
|
||||
publisher.publishUpdateReport({
|
||||
version: 1,
|
||||
type: "desktopUpdateStatus",
|
||||
...(Option.isSome(requestId) ? { requestId: requestId.value } : {}),
|
||||
...(terminal === undefined ? {} : { outcome: terminal.outcome }),
|
||||
...(terminal?.reason === undefined ? {} : { reason: terminal.reason }),
|
||||
state,
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
yield* Effect.scoped(
|
||||
Effect.gen(function* () {
|
||||
const { latest, changes } = yield* updates.subscribe;
|
||||
yield* publishReport(latest);
|
||||
yield* Stream.runForEach(changes, (state) => publishReport(state));
|
||||
}),
|
||||
).pipe(Effect.forkScoped);
|
||||
|
||||
const handleRequest = (request: DesktopTelemetryRequestDesktopUpdate): Effect.Effect<void> =>
|
||||
Effect.scoped(
|
||||
Effect.gen(function* () {
|
||||
yield* Ref.set(activeRequestIdRef, Option.some(request.requestId));
|
||||
yield* logInfo("remote update requested", { requestId: request.requestId });
|
||||
const { latest, changes } = yield* updates.subscribe;
|
||||
const disabledReason = Option.getOrNull(yield* updates.disabledReason);
|
||||
let attempts: RemoteDesktopUpdateAttempts = { checks: 0, downloads: 0 };
|
||||
|
||||
// Returns true when the run reached a terminal outcome.
|
||||
const step = (state: DesktopUpdateState): Effect.Effect<boolean, never, Scope.Scope> =>
|
||||
Effect.gen(function* () {
|
||||
const next = nextRemoteDesktopUpdateStep(state, attempts, disabledReason);
|
||||
switch (next.action) {
|
||||
case "wait":
|
||||
return false;
|
||||
case "check":
|
||||
attempts = { ...attempts, checks: attempts.checks + 1 };
|
||||
yield* Effect.forkScoped(updates.check("remote-update"));
|
||||
return false;
|
||||
case "download":
|
||||
attempts = { ...attempts, downloads: attempts.downloads + 1 };
|
||||
yield* Effect.forkScoped(updates.download);
|
||||
return false;
|
||||
case "install": {
|
||||
// The terminal report must go out BEFORE installing:
|
||||
// install stops the backend server first, so anything
|
||||
// published after this point never reaches the requester.
|
||||
yield* publishReport(state, { outcome: "installing" });
|
||||
yield* logInfo("remote update installing", { requestId: request.requestId });
|
||||
const before = yield* updates.getState;
|
||||
const result = yield* updates.install;
|
||||
if (!result.accepted) {
|
||||
yield* publishReport(result.state, {
|
||||
outcome: "failed",
|
||||
reason: "The desktop app could not start the install.",
|
||||
});
|
||||
} else if (result.state !== before) {
|
||||
// During an accepted install the only state writes are the
|
||||
// failure reducers, so a transition means this attempt
|
||||
// failed. Field checks cannot tell a fresh failure from a
|
||||
// lingering errorContext left by a previous attempt, which
|
||||
// success does not clear.
|
||||
yield* publishReport(result.state, {
|
||||
outcome: "failed",
|
||||
reason: result.state.message ?? "The desktop app failed to install the update.",
|
||||
});
|
||||
}
|
||||
return true;
|
||||
}
|
||||
case "done":
|
||||
yield* publishReport(state, {
|
||||
outcome: next.outcome,
|
||||
...(next.reason === undefined ? {} : { reason: next.reason }),
|
||||
});
|
||||
yield* logInfo("remote update finished", {
|
||||
requestId: request.requestId,
|
||||
outcome: next.outcome,
|
||||
reason: next.reason ?? null,
|
||||
});
|
||||
return true;
|
||||
}
|
||||
});
|
||||
|
||||
if (yield* step(latest)) return;
|
||||
yield* changes.pipe(
|
||||
Stream.mapEffect(step),
|
||||
Stream.takeUntil((done) => done),
|
||||
Stream.runDrain,
|
||||
);
|
||||
}),
|
||||
).pipe(
|
||||
Effect.ensuring(Ref.set(activeRequestIdRef, Option.none())),
|
||||
Effect.catchCause((cause) =>
|
||||
logError("remote update request failed unexpectedly", {
|
||||
requestId: request.requestId,
|
||||
cause: String(cause),
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
// Sequential by construction: a second remote request queued mid-run is
|
||||
// handled after the current one, when the state machine resolves it fast.
|
||||
yield* Stream.runForEach(publisher.updateRequests, handleRequest).pipe(Effect.forkScoped);
|
||||
});
|
||||
@@ -1,6 +1,4 @@
|
||||
import { assert, describe, it } from "@effect/vitest";
|
||||
import * as NodeServices from "@effect/platform-node/NodeServices";
|
||||
import type { DesktopUpdateState } from "@t3tools/contracts";
|
||||
import * as Cause from "effect/Cause";
|
||||
import * as Deferred from "effect/Deferred";
|
||||
import * as Duration from "effect/Duration";
|
||||
@@ -11,201 +9,14 @@ import * as Logger from "effect/Logger";
|
||||
import * as Option from "effect/Option";
|
||||
import * as References from "effect/References";
|
||||
import * as Ref from "effect/Ref";
|
||||
import * as Stream from "effect/Stream";
|
||||
import * as TestClock from "effect/testing/TestClock";
|
||||
|
||||
import * as DesktopBackendPool from "../backend/DesktopBackendPool.ts";
|
||||
import * as DesktopConfig from "../app/DesktopConfig.ts";
|
||||
import * as DesktopEnvironment from "../app/DesktopEnvironment.ts";
|
||||
import * as ElectronUpdater from "../electron/ElectronUpdater.ts";
|
||||
import * as ElectronWindow from "../electron/ElectronWindow.ts";
|
||||
import * as DesktopAppSettings from "../settings/DesktopAppSettings.ts";
|
||||
import * as DesktopState from "../app/DesktopState.ts";
|
||||
import * as DesktopUpdates from "./DesktopUpdates.ts";
|
||||
|
||||
interface UpdatesHarnessOptions {
|
||||
readonly checkForUpdates?: Effect.Effect<
|
||||
void,
|
||||
ElectronUpdater.ElectronUpdaterCheckForUpdatesError
|
||||
>;
|
||||
readonly setUpdateChannelError?: DesktopAppSettings.DesktopSettingsWriteError;
|
||||
readonly setDisableDifferentialDownload?: Effect.Effect<void>;
|
||||
readonly stopBackend?: Effect.Effect<void>;
|
||||
readonly env?: Record<string, string | undefined>;
|
||||
}
|
||||
|
||||
const flushCallbacks = Effect.yieldNow;
|
||||
|
||||
function makeHarness(options: UpdatesHarnessOptions = {}) {
|
||||
let checkCount = 0;
|
||||
let allowDowngrade = false;
|
||||
let fullChangelog = false;
|
||||
const feedUrls: ElectronUpdater.ElectronUpdaterFeedUrl[] = [];
|
||||
const listeners = new Map<string, Set<(...args: readonly unknown[]) => void>>();
|
||||
const sentStates: DesktopUpdateState[] = [];
|
||||
|
||||
const addListener = (eventName: string, listener: (...args: readonly unknown[]) => void) => {
|
||||
const eventListeners = listeners.get(eventName) ?? new Set();
|
||||
eventListeners.add(listener);
|
||||
listeners.set(eventName, eventListeners);
|
||||
};
|
||||
|
||||
const removeListener = (eventName: string, listener: (...args: readonly unknown[]) => void) => {
|
||||
const eventListeners = listeners.get(eventName);
|
||||
if (!eventListeners) {
|
||||
return;
|
||||
}
|
||||
eventListeners.delete(listener);
|
||||
if (eventListeners.size === 0) {
|
||||
listeners.delete(eventName);
|
||||
}
|
||||
};
|
||||
|
||||
const updaterLayer = Layer.succeed(ElectronUpdater.ElectronUpdater, {
|
||||
setFeedURL: (options) =>
|
||||
Effect.sync(() => {
|
||||
feedUrls.push(options);
|
||||
}),
|
||||
setAutoDownload: () => Effect.void,
|
||||
setAutoInstallOnAppQuit: () => Effect.void,
|
||||
setChannel: () => Effect.void,
|
||||
setAllowPrerelease: () => Effect.void,
|
||||
allowDowngrade: Effect.sync(() => allowDowngrade),
|
||||
setAllowDowngrade: (value) =>
|
||||
Effect.sync(() => {
|
||||
allowDowngrade = value;
|
||||
}),
|
||||
setFullChangelog: (value) =>
|
||||
Effect.sync(() => {
|
||||
fullChangelog = value;
|
||||
}),
|
||||
setDisableDifferentialDownload: () => options.setDisableDifferentialDownload ?? Effect.void,
|
||||
checkForUpdates: Effect.sync(() => {
|
||||
checkCount += 1;
|
||||
}).pipe(Effect.andThen(options.checkForUpdates ?? Effect.void)),
|
||||
downloadUpdate: Effect.void,
|
||||
quitAndInstall: () => Effect.void,
|
||||
on: (eventName, listener) =>
|
||||
Effect.acquireRelease(
|
||||
Effect.sync(() => {
|
||||
addListener(eventName, listener as unknown as (...args: readonly unknown[]) => void);
|
||||
}),
|
||||
() =>
|
||||
Effect.sync(() => {
|
||||
removeListener(eventName, listener as unknown as (...args: readonly unknown[]) => void);
|
||||
}),
|
||||
).pipe(Effect.asVoid),
|
||||
} satisfies ElectronUpdater.ElectronUpdater["Service"]);
|
||||
|
||||
const windowLayer = Layer.succeed(ElectronWindow.ElectronWindow, {
|
||||
create: () => Effect.die("unexpected BrowserWindow creation"),
|
||||
main: Effect.succeed(Option.none()),
|
||||
currentMainOrFirst: Effect.succeed(Option.none()),
|
||||
focusedMainOrFirst: Effect.succeed(Option.none()),
|
||||
setMain: () => Effect.void,
|
||||
clearMain: () => Effect.void,
|
||||
reveal: () => Effect.void,
|
||||
sendAll: (_channel, state) =>
|
||||
Effect.sync(() => {
|
||||
sentStates.push(state as DesktopUpdateState);
|
||||
}),
|
||||
destroyAll: Effect.void,
|
||||
syncAllAppearance: () => Effect.void,
|
||||
} satisfies ElectronWindow.ElectronWindow["Service"]);
|
||||
|
||||
const stubBackendInstance: DesktopBackendPool.DesktopBackendInstance = {
|
||||
id: DesktopBackendPool.PRIMARY_INSTANCE_ID,
|
||||
label: Effect.succeed("Windows"),
|
||||
start: Effect.void,
|
||||
stop: () => options.stopBackend ?? Effect.void,
|
||||
currentConfig: Effect.succeed(Option.none()),
|
||||
snapshot: Effect.succeed({
|
||||
desiredRunning: false,
|
||||
ready: false,
|
||||
activePid: Option.none(),
|
||||
restartAttempt: 0,
|
||||
restartScheduled: false,
|
||||
}),
|
||||
waitForReady: () => Effect.succeed(true),
|
||||
};
|
||||
const backendLayer = DesktopBackendPool.layerTest([stubBackendInstance]);
|
||||
|
||||
const environmentLayer = DesktopEnvironment.layer({
|
||||
dirname: "/repo/apps/desktop/src",
|
||||
homeDirectory: `/tmp/t3-desktop-updates-home-${process.pid}`,
|
||||
platform: "darwin",
|
||||
processArch: "x64",
|
||||
appVersion: "1.2.3",
|
||||
appPath: "/repo",
|
||||
isPackaged: true,
|
||||
resourcesPath: "/missing/resources",
|
||||
runningUnderArm64Translation: false,
|
||||
}).pipe(
|
||||
Layer.provide(
|
||||
Layer.mergeAll(
|
||||
NodeServices.layer,
|
||||
DesktopConfig.layerTest({
|
||||
T3CODE_HOME: `/tmp/t3-desktop-updates-test-${process.pid}`,
|
||||
T3CODE_DESKTOP_MOCK_UPDATES: "true",
|
||||
T3CODE_DESKTOP_MOCK_UPDATE_SERVER_PORT: "4141",
|
||||
...options.env,
|
||||
}),
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
const setUpdateChannelError = options.setUpdateChannelError;
|
||||
const settingsLayer = setUpdateChannelError
|
||||
? Layer.succeed(DesktopAppSettings.DesktopAppSettings, {
|
||||
get: Effect.succeed(DesktopAppSettings.DEFAULT_DESKTOP_SETTINGS),
|
||||
load: Effect.succeed(DesktopAppSettings.DEFAULT_DESKTOP_SETTINGS),
|
||||
setMainWindowBounds: () => Effect.die("unexpected main window bounds update"),
|
||||
setServerExposureMode: () => Effect.die("unexpected server exposure update"),
|
||||
setTailscaleServe: () => Effect.die("unexpected Tailscale Serve update"),
|
||||
setUpdateChannel: () => Effect.fail(setUpdateChannelError),
|
||||
setWslBackendEnabled: () => Effect.die("unexpected WSL backend toggle"),
|
||||
setWslDistro: () => Effect.die("unexpected WSL distro change"),
|
||||
setWslOnly: () => Effect.die("unexpected WSL-only toggle"),
|
||||
applyWslWindowsFallback: Effect.die("unexpected WSL Windows fallback"),
|
||||
applyWslWindowsFallbackInMemory: Effect.die("unexpected WSL Windows fallback"),
|
||||
} satisfies DesktopAppSettings.DesktopAppSettings["Service"])
|
||||
: DesktopAppSettings.layer;
|
||||
|
||||
const layer = DesktopUpdates.layer.pipe(
|
||||
Layer.provideMerge(updaterLayer),
|
||||
Layer.provideMerge(windowLayer),
|
||||
Layer.provideMerge(backendLayer),
|
||||
Layer.provideMerge(DesktopState.layer),
|
||||
Layer.provideMerge(settingsLayer),
|
||||
Layer.provideMerge(
|
||||
DesktopConfig.layerTest({
|
||||
T3CODE_HOME: `/tmp/t3-desktop-updates-test-${process.pid}`,
|
||||
T3CODE_DESKTOP_MOCK_UPDATES: "true",
|
||||
T3CODE_DESKTOP_MOCK_UPDATE_SERVER_PORT: "4141",
|
||||
...options.env,
|
||||
}),
|
||||
),
|
||||
Layer.provideMerge(environmentLayer),
|
||||
Layer.provideMerge(NodeServices.layer),
|
||||
);
|
||||
|
||||
return {
|
||||
layer,
|
||||
checkCount: () => checkCount,
|
||||
feedUrls: () => feedUrls,
|
||||
fullChangelog: () => fullChangelog,
|
||||
listenerCount: () =>
|
||||
Array.from(listeners.values()).reduce(
|
||||
(total, eventListeners) => total + eventListeners.size,
|
||||
0,
|
||||
),
|
||||
sentStates,
|
||||
emit: (eventName: string, payload?: unknown) => {
|
||||
for (const listener of listeners.get(eventName) ?? []) {
|
||||
listener(payload);
|
||||
}
|
||||
},
|
||||
};
|
||||
}
|
||||
import { flushCallbacks, makeHarness } from "./updatesTestHarness.ts";
|
||||
|
||||
describe("DesktopUpdates", () => {
|
||||
it("preserves complete causes for update poller and event failures", () => {
|
||||
@@ -274,6 +85,29 @@ describe("DesktopUpdates", () => {
|
||||
}).pipe(Effect.provide(Layer.merge(TestClock.layer(), harness.layer)));
|
||||
});
|
||||
|
||||
it.effect("subscribe delivers the latest state plus subsequent changes", () => {
|
||||
const harness = makeHarness();
|
||||
|
||||
return Effect.scoped(
|
||||
Effect.gen(function* () {
|
||||
const updates = yield* DesktopUpdates.DesktopUpdates;
|
||||
yield* updates.configure;
|
||||
|
||||
const { latest, changes } = yield* updates.subscribe;
|
||||
assert.equal(latest.status, "idle");
|
||||
|
||||
const nextState = yield* Stream.runHead(changes).pipe(Effect.forkChild);
|
||||
yield* flushCallbacks;
|
||||
harness.emit("update-available", { version: "1.2.4" });
|
||||
yield* flushCallbacks;
|
||||
|
||||
const observed = yield* Fiber.join(nextState);
|
||||
assert.equal(Option.getOrThrow(observed).status, "available");
|
||||
assert.equal(Option.getOrThrow(observed).availableVersion, "1.2.4");
|
||||
}),
|
||||
).pipe(Effect.provide(Layer.merge(TestClock.layer(), harness.layer)));
|
||||
});
|
||||
|
||||
it.effect("updates and broadcasts state from updater events", () => {
|
||||
const harness = makeHarness();
|
||||
|
||||
|
||||
@@ -14,9 +14,12 @@ import * as Effect from "effect/Effect";
|
||||
import * as FileSystem from "effect/FileSystem";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as Option from "effect/Option";
|
||||
import * as PubSub from "effect/PubSub";
|
||||
import * as Ref from "effect/Ref";
|
||||
import * as Schema from "effect/Schema";
|
||||
import * as Scope from "effect/Scope";
|
||||
import * as Semaphore from "effect/Semaphore";
|
||||
import * as Stream from "effect/Stream";
|
||||
|
||||
import * as DesktopBackendPool from "../backend/DesktopBackendPool.ts";
|
||||
import * as DesktopConfig from "../app/DesktopConfig.ts";
|
||||
@@ -150,6 +153,15 @@ export class DesktopUpdates extends Context.Service<
|
||||
DesktopUpdates,
|
||||
{
|
||||
readonly getState: Effect.Effect<DesktopUpdateState>;
|
||||
/** Current state plus a stream of every later state change. */
|
||||
readonly subscribe: Effect.Effect<
|
||||
{
|
||||
readonly latest: DesktopUpdateState;
|
||||
readonly changes: Stream.Stream<DesktopUpdateState>;
|
||||
},
|
||||
never,
|
||||
Scope.Scope
|
||||
>;
|
||||
readonly emitState: Effect.Effect<void>;
|
||||
readonly disabledReason: Effect.Effect<Option.Option<string>>;
|
||||
readonly configure: Effect.Effect<void, DesktopUpdateConfigureError, Scope.Scope>;
|
||||
@@ -268,12 +280,21 @@ export const make = Effect.gen(function* () {
|
||||
),
|
||||
);
|
||||
|
||||
const stateChanges = yield* PubSub.sliding<DesktopUpdateState>(16);
|
||||
// Makes ref writes + publishes atomic against subscribe, so a snapshot
|
||||
// never overlaps with the first change a subscriber receives.
|
||||
const stateMutex = yield* Semaphore.make(1);
|
||||
|
||||
const emitState = Ref.get(updateStateRef).pipe(
|
||||
Effect.flatMap((state) => electronWindow.sendAll(IpcChannels.UPDATE_STATE_CHANNEL, state)),
|
||||
);
|
||||
|
||||
const setState = (state: DesktopUpdateState): Effect.Effect<void> =>
|
||||
Ref.set(updateStateRef, state).pipe(Effect.andThen(emitState));
|
||||
stateMutex
|
||||
.withPermits(1)(
|
||||
Ref.set(updateStateRef, state).pipe(Effect.andThen(PubSub.publish(stateChanges, state))),
|
||||
)
|
||||
.pipe(Effect.andThen(emitState));
|
||||
|
||||
const updateState = (
|
||||
f: (state: DesktopUpdateState) => DesktopUpdateState,
|
||||
@@ -705,6 +726,13 @@ export const make = Effect.gen(function* () {
|
||||
|
||||
return DesktopUpdates.of({
|
||||
getState: Ref.get(updateStateRef),
|
||||
subscribe: stateMutex.withPermits(1)(
|
||||
Effect.gen(function* () {
|
||||
const subscription = yield* PubSub.subscribe(stateChanges);
|
||||
const latest = yield* Ref.get(updateStateRef);
|
||||
return { latest, changes: Stream.fromSubscription(subscription) };
|
||||
}),
|
||||
),
|
||||
emitState,
|
||||
disabledReason: resolveDisabledReason,
|
||||
configure: Effect.gen(function* () {
|
||||
|
||||
@@ -0,0 +1,194 @@
|
||||
import { assert, describe, it } from "@effect/vitest";
|
||||
import type { DesktopUpdateState } from "@t3tools/contracts";
|
||||
|
||||
import {
|
||||
MAX_REMOTE_UPDATE_CHECKS,
|
||||
MAX_REMOTE_UPDATE_DOWNLOADS,
|
||||
nextRemoteDesktopUpdateStep,
|
||||
type RemoteDesktopUpdateAttempts,
|
||||
} from "./remoteUpdateFlow.ts";
|
||||
|
||||
const NO_ATTEMPTS: RemoteDesktopUpdateAttempts = { checks: 0, downloads: 0 };
|
||||
|
||||
function makeState(overrides: Partial<DesktopUpdateState> = {}): DesktopUpdateState {
|
||||
return {
|
||||
enabled: true,
|
||||
status: "idle",
|
||||
channel: "latest",
|
||||
currentVersion: "1.2.3",
|
||||
hostArch: "arm64",
|
||||
appArch: "arm64",
|
||||
runningUnderArm64Translation: false,
|
||||
availableVersion: null,
|
||||
downloadedVersion: null,
|
||||
releaseNotes: [],
|
||||
downloadPercent: null,
|
||||
checkedAt: null,
|
||||
message: null,
|
||||
errorContext: null,
|
||||
canRetry: false,
|
||||
...overrides,
|
||||
};
|
||||
}
|
||||
|
||||
describe("nextRemoteDesktopUpdateStep", () => {
|
||||
it("fails immediately when updates are disabled, preferring the known reason", () => {
|
||||
const state = makeState({ enabled: false, status: "disabled" });
|
||||
assert.deepEqual(nextRemoteDesktopUpdateStep(state, NO_ATTEMPTS, "dev build"), {
|
||||
action: "done",
|
||||
outcome: "failed",
|
||||
reason: "dev build",
|
||||
});
|
||||
assert.deepEqual(nextRemoteDesktopUpdateStep(state, NO_ATTEMPTS, null), {
|
||||
action: "done",
|
||||
outcome: "failed",
|
||||
reason: "Automatic updates are disabled on this machine.",
|
||||
});
|
||||
});
|
||||
|
||||
it("installs only from the downloaded status the updater will accept", () => {
|
||||
assert.deepEqual(
|
||||
nextRemoteDesktopUpdateStep(
|
||||
makeState({ status: "downloaded", downloadedVersion: "1.2.4" }),
|
||||
NO_ATTEMPTS,
|
||||
null,
|
||||
),
|
||||
{ action: "install" },
|
||||
);
|
||||
// A previous install failure keeps status "downloaded", so a remote run
|
||||
// retries the install.
|
||||
assert.deepEqual(
|
||||
nextRemoteDesktopUpdateStep(
|
||||
makeState({
|
||||
status: "downloaded",
|
||||
downloadedVersion: "1.2.4",
|
||||
errorContext: "install",
|
||||
message: "quitAndInstall failed",
|
||||
}),
|
||||
NO_ATTEMPTS,
|
||||
null,
|
||||
),
|
||||
{ action: "install" },
|
||||
);
|
||||
// A leftover downloadedVersion on an error state (background updater
|
||||
// error) must not report an install the updater refuses: fresh runs
|
||||
// re-check, and post-check it fails.
|
||||
const staleError = makeState({
|
||||
status: "error",
|
||||
downloadedVersion: "1.2.4",
|
||||
message: "background updater error",
|
||||
});
|
||||
assert.deepEqual(nextRemoteDesktopUpdateStep(staleError, NO_ATTEMPTS, null), {
|
||||
action: "check",
|
||||
});
|
||||
assert.deepEqual(nextRemoteDesktopUpdateStep(staleError, { checks: 1, downloads: 0 }, null), {
|
||||
action: "done",
|
||||
outcome: "failed",
|
||||
reason: "background updater error",
|
||||
});
|
||||
});
|
||||
|
||||
it("rides along while a check or download is already in flight", () => {
|
||||
assert.deepEqual(
|
||||
nextRemoteDesktopUpdateStep(makeState({ status: "checking" }), NO_ATTEMPTS, null),
|
||||
{
|
||||
action: "wait",
|
||||
},
|
||||
);
|
||||
assert.deepEqual(
|
||||
nextRemoteDesktopUpdateStep(
|
||||
makeState({ status: "downloading", availableVersion: "1.2.4", downloadPercent: 40 }),
|
||||
NO_ATTEMPTS,
|
||||
null,
|
||||
),
|
||||
{ action: "wait" },
|
||||
);
|
||||
});
|
||||
|
||||
it("downloads an available update until the attempt cap, then fails", () => {
|
||||
const available = makeState({ status: "available", availableVersion: "1.2.4" });
|
||||
assert.deepEqual(nextRemoteDesktopUpdateStep(available, NO_ATTEMPTS, null), {
|
||||
action: "download",
|
||||
});
|
||||
assert.deepEqual(
|
||||
nextRemoteDesktopUpdateStep(
|
||||
available,
|
||||
{ checks: 1, downloads: MAX_REMOTE_UPDATE_DOWNLOADS },
|
||||
null,
|
||||
),
|
||||
{
|
||||
action: "done",
|
||||
outcome: "failed",
|
||||
reason: "The desktop app failed to download the update.",
|
||||
},
|
||||
);
|
||||
assert.deepEqual(
|
||||
nextRemoteDesktopUpdateStep(
|
||||
makeState({
|
||||
status: "available",
|
||||
availableVersion: "1.2.4",
|
||||
message: "network blipped",
|
||||
}),
|
||||
{ checks: 1, downloads: MAX_REMOTE_UPDATE_DOWNLOADS },
|
||||
null,
|
||||
),
|
||||
{ action: "done", outcome: "failed", reason: "network blipped" },
|
||||
);
|
||||
});
|
||||
|
||||
it("re-checks stale up-to-date and error states before trusting them", () => {
|
||||
// These states are retained from earlier/background checks; a remote
|
||||
// request must look again instead of replaying them.
|
||||
assert.deepEqual(
|
||||
nextRemoteDesktopUpdateStep(makeState({ status: "up-to-date" }), NO_ATTEMPTS, null),
|
||||
{ action: "check" },
|
||||
);
|
||||
assert.deepEqual(
|
||||
nextRemoteDesktopUpdateStep(
|
||||
makeState({ status: "error", message: "feed unreachable" }),
|
||||
NO_ATTEMPTS,
|
||||
null,
|
||||
),
|
||||
{ action: "check" },
|
||||
);
|
||||
});
|
||||
|
||||
it("reports up-to-date and error states as terminal after this run's check", () => {
|
||||
const checked = { checks: 1, downloads: 0 };
|
||||
assert.deepEqual(
|
||||
nextRemoteDesktopUpdateStep(makeState({ status: "up-to-date" }), checked, null),
|
||||
{ action: "done", outcome: "up-to-date" },
|
||||
);
|
||||
assert.deepEqual(
|
||||
nextRemoteDesktopUpdateStep(
|
||||
makeState({ status: "error", message: "feed unreachable" }),
|
||||
checked,
|
||||
null,
|
||||
),
|
||||
{ action: "done", outcome: "failed", reason: "feed unreachable" },
|
||||
);
|
||||
assert.deepEqual(nextRemoteDesktopUpdateStep(makeState({ status: "error" }), checked, null), {
|
||||
action: "done",
|
||||
outcome: "failed",
|
||||
reason: "The desktop app update failed.",
|
||||
});
|
||||
});
|
||||
|
||||
it("checks from idle until the attempt cap, then fails", () => {
|
||||
assert.deepEqual(nextRemoteDesktopUpdateStep(makeState(), NO_ATTEMPTS, null), {
|
||||
action: "check",
|
||||
});
|
||||
assert.deepEqual(
|
||||
nextRemoteDesktopUpdateStep(
|
||||
makeState(),
|
||||
{ checks: MAX_REMOTE_UPDATE_CHECKS, downloads: 0 },
|
||||
null,
|
||||
),
|
||||
{
|
||||
action: "done",
|
||||
outcome: "failed",
|
||||
reason: "The desktop app did not report an update result.",
|
||||
},
|
||||
);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,93 @@
|
||||
import type { DesktopUpdateRemoteOutcome, DesktopUpdateState } from "@t3tools/contracts";
|
||||
|
||||
/**
|
||||
* What a server-triggered update run should do next, given the updater's
|
||||
* current state. "wait" means an action (possibly started locally) is in
|
||||
* flight and the run should ride along until the next state change.
|
||||
*/
|
||||
export type RemoteDesktopUpdateStep =
|
||||
| { readonly action: "check" }
|
||||
| { readonly action: "download" }
|
||||
| { readonly action: "install" }
|
||||
| { readonly action: "wait" }
|
||||
| {
|
||||
readonly action: "done";
|
||||
readonly outcome: DesktopUpdateRemoteOutcome;
|
||||
readonly reason?: string;
|
||||
};
|
||||
|
||||
/**
|
||||
* How many times this run already issued each action. The caps are what stop
|
||||
* a check -> up-to-date -> check loop and endless download retries; they are
|
||||
* counts rather than booleans because a state event raced by the local
|
||||
* 4-minute poller can re-show an already-handled status once.
|
||||
*/
|
||||
export interface RemoteDesktopUpdateAttempts {
|
||||
readonly checks: number;
|
||||
readonly downloads: number;
|
||||
}
|
||||
|
||||
export const MAX_REMOTE_UPDATE_CHECKS = 2;
|
||||
export const MAX_REMOTE_UPDATE_DOWNLOADS = 3;
|
||||
|
||||
export function nextRemoteDesktopUpdateStep(
|
||||
state: DesktopUpdateState,
|
||||
attempts: RemoteDesktopUpdateAttempts,
|
||||
disabledReason: string | null,
|
||||
): RemoteDesktopUpdateStep {
|
||||
if (!state.enabled || state.status === "disabled") {
|
||||
return {
|
||||
action: "done",
|
||||
outcome: "failed",
|
||||
reason: disabledReason ?? "Automatic updates are disabled on this machine.",
|
||||
};
|
||||
}
|
||||
// Only "downloaded" is installable: installDownloadedUpdate rejects any
|
||||
// other status. A leftover downloadedVersion on an "error" state (e.g. a
|
||||
// background updater error) must fall through to the error branch instead
|
||||
// of reporting an install that the updater will refuse.
|
||||
if (state.status === "downloaded") {
|
||||
return { action: "install" };
|
||||
}
|
||||
if (state.status === "downloading" || state.status === "checking") {
|
||||
return { action: "wait" };
|
||||
}
|
||||
if (state.status === "available") {
|
||||
if (attempts.downloads >= MAX_REMOTE_UPDATE_DOWNLOADS) {
|
||||
return {
|
||||
action: "done",
|
||||
outcome: "failed",
|
||||
reason: state.message ?? "The desktop app failed to download the update.",
|
||||
};
|
||||
}
|
||||
return { action: "download" };
|
||||
}
|
||||
// "up-to-date" and "error" are retained from earlier/background checks,
|
||||
// so before this run has issued its own check they are stale, not
|
||||
// terminal: the whole point of a remote request is to look again.
|
||||
if (state.status === "up-to-date") {
|
||||
if (attempts.checks === 0) {
|
||||
return { action: "check" };
|
||||
}
|
||||
return { action: "done", outcome: "up-to-date" };
|
||||
}
|
||||
if (state.status === "error") {
|
||||
if (attempts.checks === 0) {
|
||||
return { action: "check" };
|
||||
}
|
||||
return {
|
||||
action: "done",
|
||||
outcome: "failed",
|
||||
reason: state.message ?? "The desktop app update failed.",
|
||||
};
|
||||
}
|
||||
// status === "idle"
|
||||
if (attempts.checks >= MAX_REMOTE_UPDATE_CHECKS) {
|
||||
return {
|
||||
action: "done",
|
||||
outcome: "failed",
|
||||
reason: "The desktop app did not report an update result.",
|
||||
};
|
||||
}
|
||||
return { action: "check" };
|
||||
}
|
||||
@@ -0,0 +1,209 @@
|
||||
import * as NodeServices from "@effect/platform-node/NodeServices";
|
||||
import type { DesktopUpdateState } from "@t3tools/contracts";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as Option from "effect/Option";
|
||||
|
||||
import * as DesktopBackendPool from "../backend/DesktopBackendPool.ts";
|
||||
import * as DesktopConfig from "../app/DesktopConfig.ts";
|
||||
import * as DesktopEnvironment from "../app/DesktopEnvironment.ts";
|
||||
import * as ElectronUpdater from "../electron/ElectronUpdater.ts";
|
||||
import * as ElectronWindow from "../electron/ElectronWindow.ts";
|
||||
import * as DesktopAppSettings from "../settings/DesktopAppSettings.ts";
|
||||
import * as DesktopState from "../app/DesktopState.ts";
|
||||
import * as DesktopUpdates from "./DesktopUpdates.ts";
|
||||
|
||||
/** Shared DesktopUpdates test harness: a fully stubbed updater layer whose
|
||||
electron-updater events are driven by hand via `emit`. Used by
|
||||
DesktopUpdates.test.ts and DesktopRemoteUpdates.test.ts. */
|
||||
|
||||
export const flushCallbacks = Effect.yieldNow;
|
||||
|
||||
export interface UpdatesHarnessOptions {
|
||||
readonly checkForUpdates?: Effect.Effect<
|
||||
void,
|
||||
ElectronUpdater.ElectronUpdaterCheckForUpdatesError
|
||||
>;
|
||||
readonly setUpdateChannelError?: DesktopAppSettings.DesktopSettingsWriteError;
|
||||
readonly setDisableDifferentialDownload?: Effect.Effect<void>;
|
||||
readonly quitAndInstall?: Effect.Effect<void, ElectronUpdater.ElectronUpdaterQuitAndInstallError>;
|
||||
readonly stopBackend?: Effect.Effect<void>;
|
||||
readonly env?: Record<string, string | undefined>;
|
||||
}
|
||||
|
||||
export function makeHarness(options: UpdatesHarnessOptions = {}) {
|
||||
let checkCount = 0;
|
||||
let quitAndInstallCount = 0;
|
||||
let allowDowngrade = false;
|
||||
let fullChangelog = false;
|
||||
const feedUrls: ElectronUpdater.ElectronUpdaterFeedUrl[] = [];
|
||||
const listeners = new Map<string, Set<(...args: readonly unknown[]) => void>>();
|
||||
const sentStates: DesktopUpdateState[] = [];
|
||||
|
||||
const addListener = (eventName: string, listener: (...args: readonly unknown[]) => void) => {
|
||||
const eventListeners = listeners.get(eventName) ?? new Set();
|
||||
eventListeners.add(listener);
|
||||
listeners.set(eventName, eventListeners);
|
||||
};
|
||||
|
||||
const removeListener = (eventName: string, listener: (...args: readonly unknown[]) => void) => {
|
||||
const eventListeners = listeners.get(eventName);
|
||||
if (!eventListeners) {
|
||||
return;
|
||||
}
|
||||
eventListeners.delete(listener);
|
||||
if (eventListeners.size === 0) {
|
||||
listeners.delete(eventName);
|
||||
}
|
||||
};
|
||||
|
||||
const updaterLayer = Layer.succeed(ElectronUpdater.ElectronUpdater, {
|
||||
setFeedURL: (options) =>
|
||||
Effect.sync(() => {
|
||||
feedUrls.push(options);
|
||||
}),
|
||||
setAutoDownload: () => Effect.void,
|
||||
setAutoInstallOnAppQuit: () => Effect.void,
|
||||
setChannel: () => Effect.void,
|
||||
setAllowPrerelease: () => Effect.void,
|
||||
allowDowngrade: Effect.sync(() => allowDowngrade),
|
||||
setAllowDowngrade: (value) =>
|
||||
Effect.sync(() => {
|
||||
allowDowngrade = value;
|
||||
}),
|
||||
setFullChangelog: (value) =>
|
||||
Effect.sync(() => {
|
||||
fullChangelog = value;
|
||||
}),
|
||||
setDisableDifferentialDownload: () => options.setDisableDifferentialDownload ?? Effect.void,
|
||||
checkForUpdates: Effect.sync(() => {
|
||||
checkCount += 1;
|
||||
}).pipe(Effect.andThen(options.checkForUpdates ?? Effect.void)),
|
||||
downloadUpdate: Effect.void,
|
||||
quitAndInstall: () =>
|
||||
Effect.sync(() => {
|
||||
quitAndInstallCount += 1;
|
||||
}).pipe(Effect.andThen(options.quitAndInstall ?? Effect.void)),
|
||||
on: (eventName, listener) =>
|
||||
Effect.acquireRelease(
|
||||
Effect.sync(() => {
|
||||
addListener(eventName, listener as unknown as (...args: readonly unknown[]) => void);
|
||||
}),
|
||||
() =>
|
||||
Effect.sync(() => {
|
||||
removeListener(eventName, listener as unknown as (...args: readonly unknown[]) => void);
|
||||
}),
|
||||
).pipe(Effect.asVoid),
|
||||
} satisfies ElectronUpdater.ElectronUpdater["Service"]);
|
||||
|
||||
const windowLayer = Layer.succeed(ElectronWindow.ElectronWindow, {
|
||||
create: () => Effect.die("unexpected BrowserWindow creation"),
|
||||
main: Effect.succeed(Option.none()),
|
||||
currentMainOrFirst: Effect.succeed(Option.none()),
|
||||
focusedMainOrFirst: Effect.succeed(Option.none()),
|
||||
setMain: () => Effect.void,
|
||||
clearMain: () => Effect.void,
|
||||
reveal: () => Effect.void,
|
||||
sendAll: (_channel, state) =>
|
||||
Effect.sync(() => {
|
||||
sentStates.push(state as DesktopUpdateState);
|
||||
}),
|
||||
destroyAll: Effect.void,
|
||||
syncAllAppearance: () => Effect.void,
|
||||
} satisfies ElectronWindow.ElectronWindow["Service"]);
|
||||
|
||||
const stubBackendInstance: DesktopBackendPool.DesktopBackendInstance = {
|
||||
id: DesktopBackendPool.PRIMARY_INSTANCE_ID,
|
||||
label: Effect.succeed("Windows"),
|
||||
start: Effect.void,
|
||||
stop: () => options.stopBackend ?? Effect.void,
|
||||
currentConfig: Effect.succeed(Option.none()),
|
||||
snapshot: Effect.succeed({
|
||||
desiredRunning: false,
|
||||
ready: false,
|
||||
activePid: Option.none(),
|
||||
restartAttempt: 0,
|
||||
restartScheduled: false,
|
||||
}),
|
||||
waitForReady: () => Effect.succeed(true),
|
||||
};
|
||||
const backendLayer = DesktopBackendPool.layerTest([stubBackendInstance]);
|
||||
|
||||
const environmentLayer = DesktopEnvironment.layer({
|
||||
dirname: "/repo/apps/desktop/src",
|
||||
homeDirectory: `/tmp/t3-desktop-updates-home-${process.pid}`,
|
||||
platform: "darwin",
|
||||
processArch: "x64",
|
||||
appVersion: "1.2.3",
|
||||
appPath: "/repo",
|
||||
isPackaged: true,
|
||||
resourcesPath: "/missing/resources",
|
||||
runningUnderArm64Translation: false,
|
||||
}).pipe(
|
||||
Layer.provide(
|
||||
Layer.mergeAll(
|
||||
NodeServices.layer,
|
||||
DesktopConfig.layerTest({
|
||||
T3CODE_HOME: `/tmp/t3-desktop-updates-test-${process.pid}`,
|
||||
T3CODE_DESKTOP_MOCK_UPDATES: "true",
|
||||
T3CODE_DESKTOP_MOCK_UPDATE_SERVER_PORT: "4141",
|
||||
...options.env,
|
||||
}),
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
const setUpdateChannelError = options.setUpdateChannelError;
|
||||
const settingsLayer = setUpdateChannelError
|
||||
? Layer.succeed(DesktopAppSettings.DesktopAppSettings, {
|
||||
get: Effect.succeed(DesktopAppSettings.DEFAULT_DESKTOP_SETTINGS),
|
||||
load: Effect.succeed(DesktopAppSettings.DEFAULT_DESKTOP_SETTINGS),
|
||||
setMainWindowBounds: () => Effect.die("unexpected main window bounds update"),
|
||||
setServerExposureMode: () => Effect.die("unexpected server exposure update"),
|
||||
setTailscaleServe: () => Effect.die("unexpected Tailscale Serve update"),
|
||||
setUpdateChannel: () => Effect.fail(setUpdateChannelError),
|
||||
setWslBackendEnabled: () => Effect.die("unexpected WSL backend toggle"),
|
||||
setWslDistro: () => Effect.die("unexpected WSL distro change"),
|
||||
setWslOnly: () => Effect.die("unexpected WSL-only toggle"),
|
||||
applyWslWindowsFallback: Effect.die("unexpected WSL Windows fallback"),
|
||||
applyWslWindowsFallbackInMemory: Effect.die("unexpected WSL Windows fallback"),
|
||||
} satisfies DesktopAppSettings.DesktopAppSettings["Service"])
|
||||
: DesktopAppSettings.layer;
|
||||
|
||||
const layer = DesktopUpdates.layer.pipe(
|
||||
Layer.provideMerge(updaterLayer),
|
||||
Layer.provideMerge(windowLayer),
|
||||
Layer.provideMerge(backendLayer),
|
||||
Layer.provideMerge(DesktopState.layer),
|
||||
Layer.provideMerge(settingsLayer),
|
||||
Layer.provideMerge(
|
||||
DesktopConfig.layerTest({
|
||||
T3CODE_HOME: `/tmp/t3-desktop-updates-test-${process.pid}`,
|
||||
T3CODE_DESKTOP_MOCK_UPDATES: "true",
|
||||
T3CODE_DESKTOP_MOCK_UPDATE_SERVER_PORT: "4141",
|
||||
...options.env,
|
||||
}),
|
||||
),
|
||||
Layer.provideMerge(environmentLayer),
|
||||
Layer.provideMerge(NodeServices.layer),
|
||||
);
|
||||
|
||||
return {
|
||||
layer,
|
||||
checkCount: () => checkCount,
|
||||
quitAndInstalls: () => quitAndInstallCount,
|
||||
feedUrls: () => feedUrls,
|
||||
fullChangelog: () => fullChangelog,
|
||||
listenerCount: () =>
|
||||
Array.from(listeners.values()).reduce(
|
||||
(total, eventListeners) => total + eventListeners.size,
|
||||
0,
|
||||
),
|
||||
sentStates,
|
||||
emit: (eventName: string, payload?: unknown) => {
|
||||
for (const listener of listeners.get(eventName) ?? []) {
|
||||
listener(payload);
|
||||
}
|
||||
},
|
||||
};
|
||||
}
|
||||
@@ -59,6 +59,7 @@ const electronDialogLayer = Layer.succeed(ElectronDialog.ElectronDialog, {
|
||||
|
||||
const desktopUpdatesLayer = Layer.succeed(DesktopUpdates.DesktopUpdates, {
|
||||
getState: Effect.die("unexpected getState"),
|
||||
subscribe: Effect.die("unexpected subscribe"),
|
||||
emitState: Effect.void,
|
||||
disabledReason: Effect.succeed(Option.none()),
|
||||
configure: Effect.void,
|
||||
|
||||
@@ -9,6 +9,7 @@ import * as Path from "effect/Path";
|
||||
import * as ChildProcessSpawner from "effect/unstable/process/ChildProcessSpawner";
|
||||
|
||||
import * as ServerConfig from "../config.ts";
|
||||
import * as DesktopAppUpdate from "../desktopUpdate/DesktopAppUpdate.ts";
|
||||
import * as ProcessRunner from "../processRunner.ts";
|
||||
import * as ServiceLauncherClient from "./serviceLauncherClient.ts";
|
||||
import { SERVICE_LAUNCHER_PROTOCOL } from "./serviceProtocol.ts";
|
||||
@@ -19,6 +20,7 @@ interface HarnessOptions {
|
||||
readonly managed?: boolean;
|
||||
readonly preflight?: "ready" | "blocked";
|
||||
readonly requestUpdate?: ServiceLauncherClient.ServiceLauncherClient["Service"]["requestUpdate"];
|
||||
readonly desktopAppUpdate?: DesktopAppUpdate.DesktopAppUpdate["Service"];
|
||||
}
|
||||
|
||||
const makeHarness = Effect.fn("test.make_self_update_harness")(function* (
|
||||
@@ -88,6 +90,13 @@ const makeHarness = Effect.fn("test.make_self_update_harness")(function* (
|
||||
const selfUpdate = yield* ServerSelfUpdate.make().pipe(
|
||||
Effect.provideService(ProcessRunner.ProcessRunner, runner),
|
||||
Effect.provideService(ServiceLauncherClient.ServiceLauncherClient, launcher),
|
||||
Effect.provideService(
|
||||
DesktopAppUpdate.DesktopAppUpdate,
|
||||
options.desktopAppUpdate ?? {
|
||||
available: false,
|
||||
run: () => Effect.die("unexpected desktop app update run"),
|
||||
},
|
||||
),
|
||||
Effect.provideService(HostProcessExecutablePath, "/usr/bin/node"),
|
||||
Effect.provide(ServerConfig.layer({ ...config, mode: options.mode ?? "web" })),
|
||||
);
|
||||
@@ -121,6 +130,30 @@ it.layer(NodeServices.layer)("server self update", (it) => {
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("delegates desktop-managed updates to the desktop app when available", () =>
|
||||
Effect.gen(function* () {
|
||||
const stages: string[] = [];
|
||||
const { selfUpdate, order } = yield* makeHarness({
|
||||
mode: "desktop",
|
||||
desktopAppUpdate: {
|
||||
available: true,
|
||||
run: (reportProgress) =>
|
||||
reportProgress("downloading").pipe(
|
||||
Effect.andThen(reportProgress("installing")),
|
||||
Effect.as({ targetVersion: "1.2.0", method: "desktop-app" as const }),
|
||||
),
|
||||
},
|
||||
});
|
||||
const result = yield* selfUpdate.update({ targetVersion: "1.1.0" }, (stage) =>
|
||||
Effect.sync(() => void stages.push(stage)),
|
||||
);
|
||||
expect(result).toEqual({ targetVersion: "1.2.0", method: "desktop-app" });
|
||||
expect(stages).toEqual(["downloading", "installing"]);
|
||||
// The launcher staging path must not run on the desktop path.
|
||||
expect(order).toEqual([]);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("preserves the preflight refusal reason", () =>
|
||||
Effect.gen(function* () {
|
||||
const { selfUpdate } = yield* makeHarness({ preflight: "blocked" });
|
||||
|
||||
@@ -15,6 +15,7 @@ import * as Path from "effect/Path";
|
||||
import * as Ref from "effect/Ref";
|
||||
|
||||
import * as ServerConfig from "../config.ts";
|
||||
import * as DesktopAppUpdate from "../desktopUpdate/DesktopAppUpdate.ts";
|
||||
import * as ProcessRunner from "../processRunner.ts";
|
||||
import {
|
||||
ensurePinnedRuntimeInstalled,
|
||||
@@ -47,6 +48,7 @@ export class ServerSelfUpdate extends Context.Service<
|
||||
|
||||
export const make = Effect.fn("cloud.server_self_update.make")(function* () {
|
||||
const serverConfig = yield* ServerConfig.ServerConfig;
|
||||
const desktopAppUpdate = yield* DesktopAppUpdate.DesktopAppUpdate;
|
||||
const launcher = yield* ServiceLauncherClient.ServiceLauncherClient;
|
||||
const runner = yield* ProcessRunner.ProcessRunner;
|
||||
const fs = yield* FileSystem.FileSystem;
|
||||
@@ -65,6 +67,12 @@ export const make = Effect.fn("cloud.server_self_update.make")(function* () {
|
||||
"cloud.server_self_update.update",
|
||||
)(function* (input, reportProgress = () => Effect.void) {
|
||||
if (capability === "desktop-managed") {
|
||||
// input.targetVersion is meaningless here: the desktop app's own
|
||||
// update feed decides what it downloads, and the result carries what
|
||||
// it actually got.
|
||||
if (desktopAppUpdate.available) {
|
||||
return yield* desktopAppUpdate.run(reportProgress);
|
||||
}
|
||||
return yield* failWith(
|
||||
"This server is managed by the T3 Code desktop app on its machine; update the desktop app to update it.",
|
||||
);
|
||||
|
||||
@@ -0,0 +1,203 @@
|
||||
import * as NodeServices from "@effect/platform-node/NodeServices";
|
||||
import { expect, it } from "@effect/vitest";
|
||||
import type { DesktopUpdateState, DesktopUpdateStatusReport } from "@t3tools/contracts";
|
||||
import * as Deferred from "effect/Deferred";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as FileSystem from "effect/FileSystem";
|
||||
import * as Fiber from "effect/Fiber";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as Option from "effect/Option";
|
||||
import * as Stream from "effect/Stream";
|
||||
|
||||
import * as ServerConfig from "../config.ts";
|
||||
import * as DesktopTelemetryReceiver from "../resourceTelemetry/DesktopTelemetryReceiver.ts";
|
||||
import * as DesktopAppUpdate from "./DesktopAppUpdate.ts";
|
||||
|
||||
function makeState(overrides: Partial<DesktopUpdateState> = {}): DesktopUpdateState {
|
||||
return {
|
||||
enabled: true,
|
||||
status: "idle",
|
||||
channel: "latest",
|
||||
currentVersion: "1.2.3",
|
||||
hostArch: "arm64",
|
||||
appArch: "arm64",
|
||||
runningUnderArm64Translation: false,
|
||||
availableVersion: null,
|
||||
downloadedVersion: null,
|
||||
releaseNotes: [],
|
||||
downloadPercent: null,
|
||||
checkedAt: null,
|
||||
message: null,
|
||||
errorContext: null,
|
||||
canRetry: false,
|
||||
...overrides,
|
||||
};
|
||||
}
|
||||
|
||||
function report(
|
||||
requestId: string,
|
||||
state: DesktopUpdateState,
|
||||
terminal?: {
|
||||
readonly outcome: DesktopUpdateStatusReport["outcome"];
|
||||
readonly reason?: string;
|
||||
},
|
||||
): DesktopUpdateStatusReport {
|
||||
return {
|
||||
version: 1,
|
||||
type: "desktopUpdateStatus",
|
||||
requestId,
|
||||
...(terminal?.outcome === undefined ? {} : { outcome: terminal.outcome }),
|
||||
...(terminal?.reason === undefined ? {} : { reason: terminal.reason }),
|
||||
state,
|
||||
};
|
||||
}
|
||||
|
||||
interface HarnessOptions {
|
||||
readonly mode?: "web" | "desktop";
|
||||
readonly controlFd?: number | undefined;
|
||||
/** Reports emitted for the run, given the requestId the service generated.
|
||||
The stream ends after the last one unless `keepOpen` is set. */
|
||||
readonly reports?: (requestId: string) => readonly DesktopUpdateStatusReport[];
|
||||
readonly keepOpen?: boolean;
|
||||
}
|
||||
|
||||
const makeHarness = Effect.fn("test.make_desktop_app_update_harness")(function* (
|
||||
options: HarnessOptions = {},
|
||||
) {
|
||||
const fs = yield* FileSystem.FileSystem;
|
||||
const baseDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-desktop-app-update-test-" });
|
||||
const requestIdDeferred = yield* Deferred.make<string>();
|
||||
const baseConfig = yield* ServerConfig.ServerConfig.pipe(
|
||||
Effect.provide(ServerConfig.layerTest(process.cwd(), baseDir)),
|
||||
);
|
||||
const config: ServerConfig.ServerConfig["Service"] = {
|
||||
...baseConfig,
|
||||
mode: options.mode ?? "desktop",
|
||||
...("controlFd" in options
|
||||
? { desktopTelemetryControlFd: options.controlFd }
|
||||
: { desktopTelemetryControlFd: 5 }),
|
||||
};
|
||||
const reportsForRun = options.reports ?? (() => []);
|
||||
const changes = Stream.unwrap(
|
||||
Deferred.await(requestIdDeferred).pipe(
|
||||
Effect.map((requestId) => {
|
||||
const emitted = Stream.fromIterable(reportsForRun(requestId));
|
||||
return options.keepOpen ? Stream.concat(emitted, Stream.never) : emitted;
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
const service = yield* DesktopAppUpdate.make().pipe(
|
||||
Effect.provide(
|
||||
Layer.mergeAll(
|
||||
DesktopTelemetryReceiver.layerTest({
|
||||
requestDesktopUpdate: (requestId) =>
|
||||
Deferred.succeed(requestIdDeferred, requestId).pipe(Effect.asVoid),
|
||||
desktopUpdates: Effect.succeed({
|
||||
latest: Option.none<DesktopUpdateStatusReport>(),
|
||||
changes,
|
||||
}),
|
||||
}),
|
||||
ServerConfig.layer(config),
|
||||
),
|
||||
),
|
||||
);
|
||||
return { service };
|
||||
});
|
||||
|
||||
it.layer(NodeServices.layer)("desktop app update", (it) => {
|
||||
it.effect("is unavailable without desktop mode or the control fd", () =>
|
||||
Effect.gen(function* () {
|
||||
const web = yield* makeHarness({ mode: "web" });
|
||||
expect(web.service.available).toBe(false);
|
||||
const noFd = yield* makeHarness({ controlFd: undefined });
|
||||
expect(noFd.service.available).toBe(false);
|
||||
expect((yield* noFd.service.run(() => Effect.void).pipe(Effect.flip)).reason).toContain(
|
||||
"not started by the T3 Code desktop app",
|
||||
);
|
||||
const desktop = yield* makeHarness();
|
||||
expect(desktop.service.available).toBe(true);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("collapses state reports into progress stages and succeeds on installing", () =>
|
||||
Effect.gen(function* () {
|
||||
const { service } = yield* makeHarness({
|
||||
reports: (requestId) => [
|
||||
report(requestId, makeState({ status: "checking" })),
|
||||
report(requestId, makeState({ status: "available", availableVersion: "1.2.4" })),
|
||||
report(requestId, makeState({ status: "downloading", downloadPercent: 40 })),
|
||||
// Reports from another run must be ignored.
|
||||
report("other-run", makeState({ status: "error", message: "unrelated" })),
|
||||
report(requestId, makeState({ status: "downloaded", downloadedVersion: "1.2.4" }), {
|
||||
outcome: "installing",
|
||||
}),
|
||||
],
|
||||
});
|
||||
const stages: string[] = [];
|
||||
const result = yield* service.run((stage) => Effect.sync(() => void stages.push(stage)));
|
||||
expect(result).toEqual({ targetVersion: "1.2.4", method: "desktop-app" });
|
||||
// "downloading" is not repeated for every download report.
|
||||
expect(stages).toEqual(["downloading", "installing"]);
|
||||
|
||||
// Success releases the in-flight guard: if the desktop rejected the
|
||||
// install after reporting, the server must accept a retry instead of
|
||||
// refusing until restart. (The second run fails differently because
|
||||
// the stub report stream is exhausted.)
|
||||
const retry = yield* service.run(() => Effect.void).pipe(Effect.flip);
|
||||
expect(retry.reason).not.toBe("A desktop app update is already in progress.");
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("maps up-to-date and failed outcomes to readable errors", () =>
|
||||
Effect.gen(function* () {
|
||||
const upToDate = yield* makeHarness({
|
||||
reports: (requestId) => [
|
||||
report(requestId, makeState({ status: "up-to-date" }), { outcome: "up-to-date" }),
|
||||
],
|
||||
});
|
||||
expect((yield* upToDate.service.run(() => Effect.void).pipe(Effect.flip)).reason).toBe(
|
||||
"The T3 Code desktop app on this machine is already up to date on 1.2.3.",
|
||||
);
|
||||
|
||||
const failed = yield* makeHarness({
|
||||
reports: (requestId) => [
|
||||
report(requestId, makeState({ status: "error", message: "feed unreachable" }), {
|
||||
outcome: "failed",
|
||||
reason: "feed unreachable",
|
||||
}),
|
||||
],
|
||||
});
|
||||
expect((yield* failed.service.run(() => Effect.void).pipe(Effect.flip)).reason).toBe(
|
||||
"feed unreachable",
|
||||
);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("fails when the desktop stops reporting before a terminal outcome", () =>
|
||||
Effect.gen(function* () {
|
||||
const { service } = yield* makeHarness({
|
||||
reports: (requestId) => [report(requestId, makeState({ status: "checking" }))],
|
||||
});
|
||||
expect((yield* service.run(() => Effect.void).pipe(Effect.flip)).reason).toBe(
|
||||
"The desktop app stopped reporting its update.",
|
||||
);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("allows only one desktop update at a time", () =>
|
||||
Effect.gen(function* () {
|
||||
const { service } = yield* makeHarness({ reports: () => [], keepOpen: true });
|
||||
const first = yield* Effect.forkChild(
|
||||
service.run(() => Effect.void),
|
||||
{
|
||||
startImmediately: true,
|
||||
},
|
||||
);
|
||||
expect((yield* service.run(() => Effect.void).pipe(Effect.flip)).reason).toBe(
|
||||
"A desktop app update is already in progress.",
|
||||
);
|
||||
yield* Fiber.interrupt(first);
|
||||
}),
|
||||
);
|
||||
});
|
||||
@@ -0,0 +1,176 @@
|
||||
// @effect-diagnostics nodeBuiltinImport:off
|
||||
import * as NodeCrypto from "node:crypto";
|
||||
|
||||
import {
|
||||
ServerSelfUpdateError,
|
||||
type DesktopUpdateState,
|
||||
type DesktopUpdateStatusReport,
|
||||
type ServerSelfUpdateProgressStage,
|
||||
type ServerSelfUpdateResult,
|
||||
} from "@t3tools/contracts";
|
||||
import * as Context from "effect/Context";
|
||||
import * as Duration from "effect/Duration";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as Option from "effect/Option";
|
||||
import * as Ref from "effect/Ref";
|
||||
import * as Result from "effect/Result";
|
||||
import * as Stream from "effect/Stream";
|
||||
|
||||
import { ServerConfig } from "../config.ts";
|
||||
import * as DesktopTelemetryReceiver from "../resourceTelemetry/DesktopTelemetryReceiver.ts";
|
||||
|
||||
/** Backstop for a desktop updater that hangs without ever reporting a
|
||||
terminal outcome. Generous: it covers a slow download of a full build. */
|
||||
const DESKTOP_UPDATE_TIMEOUT = Duration.minutes(20);
|
||||
|
||||
/** Progress stage a desktop update state maps to, or null when the state
|
||||
carries no progress worth streaming. */
|
||||
export function desktopUpdateProgressStage(
|
||||
state: DesktopUpdateState,
|
||||
): ServerSelfUpdateProgressStage | null {
|
||||
switch (state.status) {
|
||||
case "checking":
|
||||
case "available":
|
||||
case "downloading":
|
||||
return "downloading";
|
||||
case "downloaded":
|
||||
return "installing";
|
||||
default:
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
export class DesktopAppUpdate extends Context.Service<
|
||||
DesktopAppUpdate,
|
||||
{
|
||||
/** True when this server was spawned by a desktop app that can be
|
||||
driven over the telemetry control channel. */
|
||||
readonly available: boolean;
|
||||
/** Drives the desktop app's check -> download -> quit-and-install flow
|
||||
and translates its status reports into self-update progress. On
|
||||
success the desktop app is about to stop this server and relaunch. */
|
||||
readonly run: (
|
||||
reportProgress: (stage: ServerSelfUpdateProgressStage) => Effect.Effect<void>,
|
||||
) => Effect.Effect<ServerSelfUpdateResult, ServerSelfUpdateError>;
|
||||
}
|
||||
>()("t3/desktopUpdate/DesktopAppUpdate") {}
|
||||
|
||||
export const make = Effect.fn("desktopUpdate.desktopAppUpdate.make")(function* () {
|
||||
const config = yield* ServerConfig;
|
||||
const receiver = yield* DesktopTelemetryReceiver.DesktopTelemetryReceiver;
|
||||
const inFlight = yield* Ref.make(false);
|
||||
|
||||
const available = config.mode === "desktop" && config.desktopTelemetryControlFd !== undefined;
|
||||
const failWith = (reason: string, cause?: unknown) =>
|
||||
cause === undefined
|
||||
? new ServerSelfUpdateError({ reason })
|
||||
: new ServerSelfUpdateError({ reason, cause });
|
||||
|
||||
const consumeReports = (
|
||||
requestId: string,
|
||||
changes: Stream.Stream<DesktopUpdateStatusReport>,
|
||||
reportProgress: (stage: ServerSelfUpdateProgressStage) => Effect.Effect<void>,
|
||||
) =>
|
||||
Effect.gen(function* () {
|
||||
const lastStage = yield* Ref.make<ServerSelfUpdateProgressStage | null>(null);
|
||||
const emitStage = (stage: ServerSelfUpdateProgressStage | null): Effect.Effect<void> =>
|
||||
stage === null
|
||||
? Effect.void
|
||||
: Ref.get(lastStage).pipe(
|
||||
Effect.flatMap((previous) =>
|
||||
previous === stage
|
||||
? Effect.void
|
||||
: Ref.set(lastStage, stage).pipe(Effect.andThen(reportProgress(stage))),
|
||||
),
|
||||
);
|
||||
|
||||
const terminal = yield* changes.pipe(
|
||||
Stream.filter((report) => report.requestId === requestId),
|
||||
Stream.mapEffect(
|
||||
(report): Effect.Effect<Option.Option<DesktopUpdateStatusReport>> =>
|
||||
report.outcome === undefined
|
||||
? emitStage(desktopUpdateProgressStage(report.state)).pipe(
|
||||
Effect.as(Option.none<DesktopUpdateStatusReport>()),
|
||||
)
|
||||
: Effect.succeed(Option.some(report)),
|
||||
),
|
||||
Stream.filterMap(
|
||||
Option.match({
|
||||
onNone: () => Result.failVoid,
|
||||
onSome: Result.succeed,
|
||||
}),
|
||||
),
|
||||
Stream.runHead,
|
||||
);
|
||||
if (Option.isNone(terminal)) {
|
||||
return yield* failWith("The desktop app stopped reporting its update.");
|
||||
}
|
||||
|
||||
const report = terminal.value;
|
||||
if (report.outcome === "installing") {
|
||||
yield* emitStage("installing");
|
||||
const targetVersion =
|
||||
report.state.downloadedVersion ??
|
||||
report.state.availableVersion ??
|
||||
report.state.currentVersion;
|
||||
yield* Effect.logInfo("Desktop app update installing; the app will relaunch this server.", {
|
||||
targetVersion,
|
||||
});
|
||||
// If the app really is relaunching, this process stops moments
|
||||
// later and the flag never matters. If the desktop rejected the
|
||||
// install after reporting (app already quitting), clearing it lets
|
||||
// the user retry instead of wedging this server until restart.
|
||||
yield* Ref.set(inFlight, false);
|
||||
return { targetVersion, method: "desktop-app" as const };
|
||||
}
|
||||
if (report.outcome === "up-to-date") {
|
||||
return yield* failWith(
|
||||
`The T3 Code desktop app on this machine is already up to date on ${report.state.currentVersion}.`,
|
||||
);
|
||||
}
|
||||
return yield* failWith(
|
||||
report.reason ?? report.state.message ?? "The desktop app update failed.",
|
||||
);
|
||||
});
|
||||
|
||||
const run: DesktopAppUpdate["Service"]["run"] = Effect.fn("desktopUpdate.desktopAppUpdate.run")(
|
||||
function* (reportProgress) {
|
||||
if (!available) {
|
||||
return yield* failWith(
|
||||
"This server was not started by the T3 Code desktop app, so it cannot drive a desktop update.",
|
||||
);
|
||||
}
|
||||
if (yield* Ref.getAndSet(inFlight, true)) {
|
||||
return yield* failWith("A desktop app update is already in progress.");
|
||||
}
|
||||
|
||||
return yield* Effect.scoped(
|
||||
Effect.gen(function* () {
|
||||
const requestId = NodeCrypto.randomUUID();
|
||||
// Subscribe before sending the request so a fast first report
|
||||
// cannot be missed.
|
||||
const { changes } = yield* receiver.desktopUpdates;
|
||||
yield* receiver
|
||||
.requestDesktopUpdate(requestId)
|
||||
.pipe(
|
||||
Effect.mapError((error) =>
|
||||
failWith("Could not reach the T3 Code desktop app on this machine.", error),
|
||||
),
|
||||
);
|
||||
return yield* consumeReports(requestId, changes, reportProgress);
|
||||
}),
|
||||
).pipe(
|
||||
Effect.timeout(DESKTOP_UPDATE_TIMEOUT),
|
||||
Effect.catchTags({
|
||||
TimeoutError: () => failWith("The desktop app did not finish the update in time."),
|
||||
}),
|
||||
Effect.onError(() => Ref.set(inFlight, false)),
|
||||
);
|
||||
},
|
||||
);
|
||||
|
||||
return DesktopAppUpdate.of({ available, run });
|
||||
});
|
||||
|
||||
export const layer = Layer.effect(DesktopAppUpdate, make());
|
||||
@@ -74,6 +74,42 @@ it.layer(NodeServices.layer)("ServerEnvironmentLive", (it) => {
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("advertises desktopAppUpdate only with desktop mode and the control fd", () =>
|
||||
Effect.gen(function* () {
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const baseDir = yield* fileSystem.makeTempDirectoryScoped({
|
||||
prefix: "t3-server-environment-desktop-update-test-",
|
||||
});
|
||||
const serverConfig = yield* makeServerConfig(baseDir);
|
||||
yield* fileSystem.makeDirectory(serverConfig.stateDir, { recursive: true });
|
||||
|
||||
const describeWith = (overrides: Partial<ServerConfig.ServerConfig["Service"]>) =>
|
||||
Effect.gen(function* () {
|
||||
const serverEnvironment = yield* ServerEnvironment.ServerEnvironment;
|
||||
return yield* serverEnvironment.getDescriptor;
|
||||
}).pipe(
|
||||
Effect.provide(
|
||||
ServerEnvironment.layer.pipe(
|
||||
Layer.provide(ServerConfig.layer({ ...serverConfig, ...overrides })),
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
const withFd = yield* describeWith({ mode: "desktop", desktopTelemetryControlFd: 5 });
|
||||
expect(withFd.capabilities.serverSelfUpdate).toBe("desktop-managed");
|
||||
expect(withFd.capabilities.desktopAppUpdate).toBe(true);
|
||||
expect(withFd.capabilities.serverSelfUpdateProgress).toBe(true);
|
||||
|
||||
const withoutFd = yield* describeWith({ mode: "desktop" });
|
||||
expect(withoutFd.capabilities.serverSelfUpdate).toBe("desktop-managed");
|
||||
expect(withoutFd.capabilities.desktopAppUpdate).toBeUndefined();
|
||||
expect(withoutFd.capabilities.serverSelfUpdateProgress).toBeUndefined();
|
||||
|
||||
const web = yield* describeWith({ mode: "web", desktopTelemetryControlFd: 5 });
|
||||
expect(web.capabilities.desktopAppUpdate).toBeUndefined();
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("structures persisted environment id filesystem failures", () =>
|
||||
Effect.gen(function* () {
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
|
||||
@@ -131,6 +131,12 @@ export const make = Effect.gen(function* () {
|
||||
desktopManaged: serverConfig.mode === "desktop",
|
||||
launcherManaged: launcher.managed,
|
||||
});
|
||||
// Static is correct: the control fd is known at bootstrap, and the desktop
|
||||
// app and its bundled server ship in one artifact, so a present fd means
|
||||
// the app speaks the requestDesktopUpdate protocol. WSL backends never get
|
||||
// the fd and correctly do not advertise.
|
||||
const desktopAppUpdate =
|
||||
serverSelfUpdate === "desktop-managed" && serverConfig.desktopTelemetryControlFd !== undefined;
|
||||
|
||||
const descriptor: ExecutionEnvironmentDescriptor = {
|
||||
environmentId,
|
||||
@@ -150,7 +156,10 @@ export const make = Effect.gen(function* () {
|
||||
threadPinReorder: true,
|
||||
threadTitleRegeneration: true,
|
||||
...(serverSelfUpdate === null ? {} : { serverSelfUpdate }),
|
||||
...(serverSelfUpdate === "boot-service" ? { serverSelfUpdateProgress: true } : {}),
|
||||
...(serverSelfUpdate === "boot-service" || desktopAppUpdate
|
||||
? { serverSelfUpdateProgress: true }
|
||||
: {}),
|
||||
...(desktopAppUpdate ? { desktopAppUpdate: true } : {}),
|
||||
},
|
||||
};
|
||||
|
||||
|
||||
@@ -7,6 +7,7 @@ import {
|
||||
type DesktopHostTelemetryMessage as DesktopHostTelemetryMessageValue,
|
||||
type DesktopHostTelemetrySnapshot,
|
||||
DesktopTelemetryControlMessage,
|
||||
type DesktopUpdateStatusReport,
|
||||
type ResourceTelemetrySourceStatus,
|
||||
} from "@t3tools/contracts";
|
||||
import { resolveServerBackgroundActivitySettings } from "@t3tools/shared/backgroundActivitySettings";
|
||||
@@ -18,6 +19,7 @@ import * as Layer from "effect/Layer";
|
||||
import * as Option from "effect/Option";
|
||||
import * as PubSub from "effect/PubSub";
|
||||
import * as Ref from "effect/Ref";
|
||||
import * as Result from "effect/Result";
|
||||
import * as Schema from "effect/Schema";
|
||||
import * as Semaphore from "effect/Semaphore";
|
||||
import * as Scope from "effect/Scope";
|
||||
@@ -171,6 +173,23 @@ export class DesktopTelemetryReceiver extends Context.Service<
|
||||
readonly setDiagnosticsDemand: (
|
||||
enabled: boolean,
|
||||
) => Effect.Effect<void, DesktopTelemetryControlError>;
|
||||
/** Asks the desktop app supervising this server to update itself. The
|
||||
desktop answers with desktopUpdateStatus reports carrying the same
|
||||
requestId. */
|
||||
readonly requestDesktopUpdate: (
|
||||
requestId: string,
|
||||
) => Effect.Effect<void, DesktopTelemetryControlError>;
|
||||
/** Latest desktop update state report plus subsequent reports. The
|
||||
desktop replays its latest report when the backend attaches, so this
|
||||
is populated shortly after startup on desktop-managed servers. */
|
||||
readonly desktopUpdates: Effect.Effect<
|
||||
{
|
||||
readonly latest: Option.Option<DesktopUpdateStatusReport>;
|
||||
readonly changes: Stream.Stream<DesktopUpdateStatusReport>;
|
||||
},
|
||||
never,
|
||||
Scope.Scope
|
||||
>;
|
||||
}
|
||||
>()("t3/resourceTelemetry/DesktopTelemetryReceiver") {}
|
||||
|
||||
@@ -322,6 +341,8 @@ export const make = Effect.fn("resourceTelemetry.desktopTelemetryReceiver.make")
|
||||
);
|
||||
const changes = yield* PubSub.sliding<DesktopHostTelemetrySnapshot>(8);
|
||||
const healthChanges = yield* PubSub.sliding<DesktopTelemetryReceiverHealth>(4);
|
||||
const latestUpdateReport = yield* Ref.make(Option.none<DesktopUpdateStatusReport>());
|
||||
const updateReportChanges = yield* PubSub.sliding<DesktopUpdateStatusReport>(16);
|
||||
const controlMutex = yield* Semaphore.make(1);
|
||||
const snapshotMutex = yield* Semaphore.make(1);
|
||||
const health = yield* Ref.make<DesktopTelemetryReceiverHealth>({
|
||||
@@ -462,8 +483,8 @@ export const make = Effect.fn("resourceTelemetry.desktopTelemetryReceiver.make")
|
||||
(
|
||||
value,
|
||||
): Effect.Effect<
|
||||
DesktopHostTelemetryMessageValue,
|
||||
DesktopTelemetryProtocolMismatch | DesktopTelemetryDecodeFailed
|
||||
Option.Option<DesktopHostTelemetryMessageValue>,
|
||||
DesktopTelemetryProtocolMismatch
|
||||
> => {
|
||||
const version = messageVersion(value);
|
||||
if (version !== undefined && version !== 1) {
|
||||
@@ -474,11 +495,25 @@ export const make = Effect.fn("resourceTelemetry.desktopTelemetryReceiver.make")
|
||||
}),
|
||||
);
|
||||
}
|
||||
// An undecodable line is logged and skipped instead of failing
|
||||
// the stream: failing would stop desktop telemetry for the
|
||||
// whole process lifetime over one unknown message shape.
|
||||
return decodeMessage(value).pipe(
|
||||
Effect.mapError((cause) => new DesktopTelemetryDecodeFailed({ cause })),
|
||||
Effect.map(Option.some),
|
||||
Effect.catchCause((cause) =>
|
||||
Effect.logWarning("Skipping undecodable desktop telemetry message", {
|
||||
cause: String(cause),
|
||||
}).pipe(Effect.as(Option.none<DesktopHostTelemetryMessageValue>())),
|
||||
),
|
||||
);
|
||||
},
|
||||
),
|
||||
Stream.filterMap(
|
||||
Option.match({
|
||||
onNone: () => Result.failVoid,
|
||||
onSome: Result.succeed,
|
||||
}),
|
||||
),
|
||||
Stream.mapError(normalizeReceiverError),
|
||||
);
|
||||
|
||||
@@ -503,6 +538,15 @@ export const make = Effect.fn("resourceTelemetry.desktopTelemetryReceiver.make")
|
||||
);
|
||||
}
|
||||
|
||||
// Not a resource sample: do not touch `latest` or sample health.
|
||||
if (message.type === "desktopUpdateStatus") {
|
||||
return recordContact.pipe(
|
||||
Effect.andThen(Ref.set(latestUpdateReport, Option.some(message))),
|
||||
Effect.andThen(PubSub.publish(updateReportChanges, message)),
|
||||
Effect.asVoid,
|
||||
);
|
||||
}
|
||||
|
||||
const sampledAt = DateTime.makeUnsafe(message.sampledAtUnixMs);
|
||||
return snapshotMutex.withPermits(1)(
|
||||
recordContact.pipe(
|
||||
@@ -616,6 +660,20 @@ export const make = Effect.fn("resourceTelemetry.desktopTelemetryReceiver.make")
|
||||
health: Ref.get(health),
|
||||
subscribeHealth: subscribeBeforeSnapshotWithoutMutex(healthChanges, Ref.get(health)),
|
||||
setDiagnosticsDemand,
|
||||
requestDesktopUpdate: (requestId) =>
|
||||
sendControlMessage({
|
||||
version: 1,
|
||||
type: "requestDesktopUpdate",
|
||||
requestId,
|
||||
}),
|
||||
desktopUpdates: Effect.gen(function* () {
|
||||
const subscription = yield* PubSub.subscribe(updateReportChanges);
|
||||
const initial = yield* Ref.get(latestUpdateReport);
|
||||
return {
|
||||
latest: initial,
|
||||
changes: Stream.fromSubscription(subscription),
|
||||
};
|
||||
}),
|
||||
});
|
||||
});
|
||||
|
||||
@@ -656,6 +714,13 @@ export const layerTest = (
|
||||
})),
|
||||
),
|
||||
setDiagnosticsDemand: () => Effect.void,
|
||||
requestDesktopUpdate: () => Effect.void,
|
||||
desktopUpdates:
|
||||
overrides.desktopUpdates ??
|
||||
Effect.succeed({
|
||||
latest: Option.none<DesktopUpdateStatusReport>(),
|
||||
changes: Stream.empty,
|
||||
}),
|
||||
...overrides,
|
||||
}),
|
||||
);
|
||||
|
||||
@@ -95,6 +95,7 @@ import * as CloudManagedEndpointRuntime from "./cloud/ManagedEndpointRuntime.ts"
|
||||
import * as CloudCliTokenManager from "./cloud/CliTokenManager.ts";
|
||||
import * as CloudCliState from "./cloud/CliState.ts";
|
||||
import * as ServerSelfUpdate from "./cloud/selfUpdate.ts";
|
||||
import * as DesktopAppUpdate from "./desktopUpdate/DesktopAppUpdate.ts";
|
||||
import * as ServiceLauncherClient from "./cloud/serviceLauncherClient.ts";
|
||||
import * as ProcessDiagnostics from "./diagnostics/ProcessDiagnostics.ts";
|
||||
import * as ProcessResourceMonitor from "./diagnostics/ProcessResourceMonitor.ts";
|
||||
@@ -157,6 +158,12 @@ const HostPowerMonitorLayerLive = HostPowerMonitor.layer.pipe(
|
||||
Layer.provide(DesktopTelemetryReceiverLayerLive),
|
||||
);
|
||||
|
||||
// Reuses DesktopTelemetryReceiverLayerLive: a fresh receiver layer here
|
||||
// would open a second reader on the desktop telemetry fd.
|
||||
const DesktopAppUpdateLayerLive = DesktopAppUpdate.layer.pipe(
|
||||
Layer.provide(DesktopTelemetryReceiverLayerLive),
|
||||
);
|
||||
|
||||
const BackgroundLayerLive = BackgroundPolicy.layer.pipe(
|
||||
Layer.provide(HostPowerMonitorLayerLive),
|
||||
Layer.provideMerge(ServerSettingsLayerLive),
|
||||
@@ -460,7 +467,7 @@ export const makeRoutesLayer = Layer.mergeAll(
|
||||
// and mutations observed on WebSocket invalidate patches subsequently read over HTTP.
|
||||
Layer.provide(PullRequestServiceLive),
|
||||
Layer.provide(PreviewAutomationBroker.layer),
|
||||
Layer.provide(ServerSelfUpdate.layer),
|
||||
Layer.provide(ServerSelfUpdate.layer.pipe(Layer.provide(DesktopAppUpdateLayerLive))),
|
||||
Layer.provide(commandReadinessLayer),
|
||||
Layer.provide(browserApiCorsLayer),
|
||||
Layer.provide(httpCompressionLayer),
|
||||
|
||||
@@ -343,6 +343,7 @@ import {
|
||||
resolveServerConfigVersionMismatch,
|
||||
resolveServerSelfUpdateCapability,
|
||||
serverUpdateGuidance,
|
||||
supportsDesktopAppUpdate,
|
||||
} from "../versionSkew";
|
||||
import { useAssetUrls } from "../assets/assetUrls";
|
||||
|
||||
@@ -2018,6 +2019,7 @@ function ChatViewContent(props: ChatViewProps) {
|
||||
: "server";
|
||||
const serverUpdateEnvironmentId = activeThread?.environmentId ?? null;
|
||||
const versionMismatchSelfUpdate = resolveServerSelfUpdateCapability(serverConfig);
|
||||
const versionMismatchDesktopAppUpdate = supportsDesktopAppUpdate(serverConfig);
|
||||
const serverUpdateState = useAtomValue(
|
||||
serverEnvironment.updateStateAtom(serverUpdateEnvironmentId),
|
||||
);
|
||||
@@ -2139,19 +2141,23 @@ function ChatViewContent(props: ChatViewProps) {
|
||||
description:
|
||||
updateInProgress || updateFailed ? (
|
||||
<ServerUpdateProgress state={serverUpdateState} />
|
||||
) : versionMismatchSelfUpdate === "desktop-managed" ? (
|
||||
) : versionMismatchSelfUpdate === "desktop-managed" &&
|
||||
!versionMismatchDesktopAppUpdate ? (
|
||||
serverUpdateGuidance(versionMismatchSelfUpdate, versionMismatchServerLabel)
|
||||
) : null,
|
||||
// The desktop-managed guidance is already the description; the action
|
||||
// slot would only repeat it.
|
||||
// slot would only repeat it. When the desktop app accepts remote
|
||||
// update requests, the action button takes over instead.
|
||||
actions:
|
||||
updateInProgress ||
|
||||
!versionMismatch ||
|
||||
versionMismatchSelfUpdate === "desktop-managed" ? undefined : (
|
||||
(versionMismatchSelfUpdate === "desktop-managed" &&
|
||||
!versionMismatchDesktopAppUpdate) ? undefined : (
|
||||
<ServerUpdateAction
|
||||
environmentId={serverUpdateEnvironmentId}
|
||||
serverLabel={versionMismatchServerLabel}
|
||||
selfUpdate={versionMismatchSelfUpdate}
|
||||
desktopAppUpdate={versionMismatchDesktopAppUpdate}
|
||||
targetVersion={versionMismatch.clientVersion}
|
||||
label={updateFailed ? "Retry" : "Update"}
|
||||
/>
|
||||
@@ -2180,6 +2186,7 @@ function ChatViewContent(props: ChatViewProps) {
|
||||
versionMismatchDismissKey,
|
||||
serverUpdateEnvironmentId,
|
||||
versionMismatchSelfUpdate,
|
||||
versionMismatchDesktopAppUpdate,
|
||||
versionMismatchServerLabel,
|
||||
]);
|
||||
const providerStatuses = serverConfig?.providers ?? EMPTY_PROVIDERS;
|
||||
|
||||
@@ -98,6 +98,49 @@ describe("ServerUpdateAction", () => {
|
||||
|
||||
expect(testState.toast).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("keeps the manual instruction for desktop servers without remote update support", () => {
|
||||
const markup = renderToStaticMarkup(
|
||||
<ServerUpdateAction
|
||||
environmentId={"env-test" as EnvironmentId}
|
||||
serverLabel="Test server"
|
||||
selfUpdate="desktop-managed"
|
||||
targetVersion="0.0.31"
|
||||
/>,
|
||||
);
|
||||
|
||||
expect(markup).toContain("Update the desktop app on that machine to update this server.");
|
||||
expect(markup).not.toContain("<button");
|
||||
});
|
||||
|
||||
it("updates remote desktop apps through the shared update flow", async () => {
|
||||
testState.updateServer.mockResolvedValue(
|
||||
AsyncResult.success({ targetVersion: "0.0.34", method: "desktop-app" as const }),
|
||||
);
|
||||
|
||||
const action = ServerUpdateAction({
|
||||
environmentId: "env-test" as EnvironmentId,
|
||||
serverLabel: "Test server",
|
||||
selfUpdate: "desktop-managed",
|
||||
desktopAppUpdate: true,
|
||||
targetVersion: "0.0.31",
|
||||
}) as ActionElement;
|
||||
|
||||
// No confirm-dialog host is mounted in this test, which the component
|
||||
// treats as consent: the click itself was the request.
|
||||
action.props.onClick?.();
|
||||
await flushPromises();
|
||||
|
||||
expect(testState.updateServer).toHaveBeenCalledWith({
|
||||
environmentId: "env-test",
|
||||
input: { targetVersion: "0.0.31" },
|
||||
});
|
||||
expect(testState.toast).toHaveBeenCalledWith({
|
||||
type: "success",
|
||||
title: "Test server updated",
|
||||
description: "Desktop app relaunched on 0.0.34.",
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe("ServerUpdateProgress", () => {
|
||||
|
||||
@@ -5,6 +5,7 @@ import {
|
||||
squashAtomCommandFailure,
|
||||
} from "@t3tools/client-runtime/state/runtime";
|
||||
|
||||
import { requestConfirmDialog } from "~/confirmDialog";
|
||||
import { useCopyToClipboard } from "~/hooks/useCopyToClipboard";
|
||||
import { serverEnvironment } from "~/state/server";
|
||||
import { useAtomCommand } from "~/state/use-atom-command";
|
||||
@@ -71,15 +72,20 @@ export function ServerUpdateAction({
|
||||
environmentId,
|
||||
serverLabel,
|
||||
selfUpdate,
|
||||
desktopAppUpdate = false,
|
||||
targetVersion,
|
||||
label = "Update",
|
||||
}: {
|
||||
readonly environmentId: EnvironmentId;
|
||||
readonly serverLabel: string;
|
||||
readonly selfUpdate: ServerSelfUpdateCapability | null;
|
||||
/** The desktop app supervising this server accepts remote update
|
||||
requests (capabilities.desktopAppUpdate). */
|
||||
readonly desktopAppUpdate?: boolean;
|
||||
readonly targetVersion: string;
|
||||
readonly label?: string;
|
||||
}) {
|
||||
const isDesktopAppUpdate = selfUpdate === "desktop-managed";
|
||||
const updateServer = useAtomCommand(serverEnvironment.updateServer, {
|
||||
reportFailure: false,
|
||||
});
|
||||
@@ -102,6 +108,21 @@ export function ServerUpdateAction({
|
||||
});
|
||||
|
||||
const handleUpdate = async () => {
|
||||
if (pendingUpdateEnvironmentIds.has(environmentId)) {
|
||||
return;
|
||||
}
|
||||
if (isDesktopAppUpdate) {
|
||||
// No themed host mounted (undefined) means proceed: the click itself
|
||||
// was the request. This is the only confirmation in the flow; the
|
||||
// remote machine installs without asking anyone there.
|
||||
const confirmed =
|
||||
(await requestConfirmDialog(
|
||||
`Update the T3 Code desktop app on ${serverLabel}? It will close and relaunch on that machine.`,
|
||||
)) ?? true;
|
||||
if (!confirmed) {
|
||||
return;
|
||||
}
|
||||
}
|
||||
if (pendingUpdateEnvironmentIds.has(environmentId)) {
|
||||
return;
|
||||
}
|
||||
@@ -125,14 +146,16 @@ export function ServerUpdateAction({
|
||||
toastManager.add({
|
||||
type: "success",
|
||||
title: `${serverLabel} updated`,
|
||||
description: `Reconnected on t3@${result.value.targetVersion}.`,
|
||||
description: isDesktopAppUpdate
|
||||
? `Desktop app relaunched on ${result.value.targetVersion}.`
|
||||
: `Reconnected on t3@${result.value.targetVersion}.`,
|
||||
});
|
||||
} finally {
|
||||
pendingUpdateEnvironmentIds.delete(environmentId);
|
||||
}
|
||||
};
|
||||
|
||||
if (selfUpdate === "desktop-managed") {
|
||||
if (selfUpdate === "desktop-managed" && !desktopAppUpdate) {
|
||||
return (
|
||||
<span className="text-muted-foreground text-xs">
|
||||
Update the desktop app on that machine to update this server.
|
||||
|
||||
@@ -103,6 +103,7 @@ import { useUiStateStore } from "~/uiStateStore";
|
||||
import {
|
||||
resolveServerConfigVersionMismatch,
|
||||
resolveServerSelfUpdateCapability,
|
||||
supportsDesktopAppUpdate,
|
||||
} from "~/versionSkew";
|
||||
import { hasCloudPublicConfig } from "~/cloud/publicConfig";
|
||||
import { useCloudLinkController } from "~/cloud/useCloudLinkController";
|
||||
@@ -1467,6 +1468,7 @@ function SavedBackendListRow({
|
||||
environmentId={environmentId}
|
||||
serverLabel={`${environment.label} server`}
|
||||
selfUpdate={resolveServerSelfUpdateCapability(environment.serverConfig)}
|
||||
desktopAppUpdate={supportsDesktopAppUpdate(environment.serverConfig)}
|
||||
targetVersion={versionMismatch.clientVersion}
|
||||
label={serverUpdateState.status === "failed" ? "Retry" : "Update"}
|
||||
/>
|
||||
@@ -3034,6 +3036,7 @@ export function ConnectionsSettings() {
|
||||
environmentId={primaryEnvironmentId}
|
||||
serverLabel={primaryEnvironment?.label ?? "this server"}
|
||||
selfUpdate={resolveServerSelfUpdateCapability(primaryServerConfig)}
|
||||
desktopAppUpdate={supportsDesktopAppUpdate(primaryServerConfig)}
|
||||
targetVersion={primaryVersionMismatch.clientVersion}
|
||||
label={primaryServerUpdateState.status === "failed" ? "Retry" : "Update"}
|
||||
/>
|
||||
|
||||
@@ -11,6 +11,7 @@ import {
|
||||
resolveServerSelfUpdateCapability,
|
||||
resolveVersionMismatch,
|
||||
serverUpdateGuidance,
|
||||
supportsDesktopAppUpdate,
|
||||
} from "./versionSkew";
|
||||
|
||||
describe("versionSkew", () => {
|
||||
@@ -96,6 +97,27 @@ describe("versionSkew", () => {
|
||||
expect(resolveServerSelfUpdateCapability(null)).toBeNull();
|
||||
});
|
||||
|
||||
it("detects remote desktop-app update support from config descriptors", () => {
|
||||
const descriptor = (desktopAppUpdate?: boolean) => ({
|
||||
environment: {
|
||||
environmentId: EnvironmentId.make("environment-desktop"),
|
||||
label: "Desktop",
|
||||
platform: { os: "darwin", arch: "arm64" } as const,
|
||||
serverVersion: "9.9.9",
|
||||
capabilities: {
|
||||
repositoryIdentity: true,
|
||||
serverSelfUpdate: "desktop-managed" as const,
|
||||
...(desktopAppUpdate === undefined ? {} : { desktopAppUpdate }),
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
expect(supportsDesktopAppUpdate(descriptor(true))).toBe(true);
|
||||
expect(supportsDesktopAppUpdate(descriptor(false))).toBe(false);
|
||||
expect(supportsDesktopAppUpdate(descriptor())).toBe(false);
|
||||
expect(supportsDesktopAppUpdate(null)).toBe(false);
|
||||
});
|
||||
|
||||
it("matches version-drift guidance to the advertised update path", () => {
|
||||
expect(serverUpdateGuidance("respawn", "Remote server")).toBe(
|
||||
"Update the Remote server so they stay in sync.",
|
||||
|
||||
@@ -57,6 +57,14 @@ export function resolveServerSelfUpdateCapability(
|
||||
return serverConfig?.environment.capabilities.serverSelfUpdate ?? null;
|
||||
}
|
||||
|
||||
/** True when the desktop app supervising this server can be told to update
|
||||
itself over RPC. Older desktop servers only get the manual instruction. */
|
||||
export function supportsDesktopAppUpdate(
|
||||
serverConfig: Pick<ServerConfig, "environment"> | null | undefined,
|
||||
): boolean {
|
||||
return serverConfig?.environment.capabilities.desktopAppUpdate === true;
|
||||
}
|
||||
|
||||
/** The command to hand users whose server cannot update itself. */
|
||||
export function manualServerUpdateCommand(targetVersion: string): string {
|
||||
return `npx t3@${targetVersion}`;
|
||||
|
||||
@@ -84,8 +84,14 @@ recorded reason. Older servers without an ID retain version-only reconnect behav
|
||||
|
||||
The existing additive RPC and lifecycle schemas remain compatible with older clients. New servers
|
||||
advertise remote self-update only when they have valid launcher context and a live IPC channel.
|
||||
Desktop-managed servers direct the user to update the desktop app. Other process shapes provide a
|
||||
manual command; the old detached foreground respawn path no longer exists.
|
||||
Desktop-managed servers advertise `desktopAppUpdate` when the desktop telemetry control fd is
|
||||
attached; `server.updateServer` then drives the desktop app's own check, download, and
|
||||
quit-and-install over that channel (`apps/server/src/desktopUpdate/DesktopAppUpdate.ts`), and the
|
||||
app relaunch brings the server back. The result carries no update ID, so client resume correlation
|
||||
relies on the desktop app version equaling the bundled server version (both are bumped together by
|
||||
`scripts/update-release-package-versions.ts`). Desktop servers without the capability direct the
|
||||
user to update the desktop app locally. Other process shapes provide a manual command; the old
|
||||
detached foreground respawn path no longer exists.
|
||||
|
||||
## Source Map
|
||||
|
||||
|
||||
@@ -22,11 +22,11 @@ The update does not remove saved threads, settings, or project files.
|
||||
|
||||
## Choose the Action You See
|
||||
|
||||
| Action | What to do |
|
||||
| -------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
||||
| **Update server** | Available for the T3 Code Linux background service. Select the button and leave T3 Code open while it prepares, tests, restarts, and reconnects. |
|
||||
| **Update the desktop app** | Open the T3 Code desktop app on the machine that runs the server and install the app update there. Reopen it if needed. |
|
||||
| **Copy update command** | Copy the command, open a terminal on the server machine, stop the current T3 Code server, and relaunch it with the copied command and any startup options you normally use. |
|
||||
| Action | What to do |
|
||||
| -------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
||||
| **Update server** | Available for the T3 Code Linux background service and for servers run by a current T3 Code desktop app. Select the button and leave T3 Code open while it updates, restarts, and reconnects. For desktop-app servers this closes and relaunches the desktop app on that machine. |
|
||||
| **Update the desktop app** | Shown for desktop apps that predate remote updates. Open the T3 Code desktop app on the machine that runs the server and install the app update there. Reopen it if needed. |
|
||||
| **Copy update command** | Copy the command, open a terminal on the server machine, stop the current T3 Code server, and relaunch it with the copied command and any startup options you normally use. |
|
||||
|
||||
The available action depends on how that server was started. T3 Code does not update connected
|
||||
servers silently in the background.
|
||||
|
||||
@@ -30,8 +30,10 @@ export type ExecutionEnvironmentPlatform = typeof ExecutionEnvironmentPlatform.T
|
||||
|
||||
/** How a server can replace itself with another version when asked over RPC.
|
||||
New servers only advertise the stable launcher-backed "boot-service" path;
|
||||
"respawn" remains decodable for compatibility with older servers. */
|
||||
export const ServerSelfUpdateMethod = Schema.Literals(["boot-service", "respawn"]);
|
||||
"respawn" remains decodable for compatibility with older servers.
|
||||
"desktop-app" means the supervising desktop app updated and relaunched
|
||||
itself, bringing the server back with it. */
|
||||
export const ServerSelfUpdateMethod = Schema.Literals(["boot-service", "respawn", "desktop-app"]);
|
||||
export type ServerSelfUpdateMethod = typeof ServerSelfUpdateMethod.Type;
|
||||
|
||||
/** What update path a client should offer for a server: one of the RPC
|
||||
@@ -74,6 +76,11 @@ export const ExecutionEnvironmentCapabilities = Schema.Struct({
|
||||
/** Server can stream self-update progress before acknowledging the
|
||||
restart. Clients fall back to server.updateServer when absent. */
|
||||
serverSelfUpdateProgress: Schema.optionalKey(Schema.Boolean),
|
||||
/** The desktop app supervising this server can be driven over RPC:
|
||||
server.updateServer runs its check -> download -> relaunch. Absent on
|
||||
desktop servers whose app predates the remote trigger, where clients
|
||||
must keep telling the user to update the app on that machine. */
|
||||
desktopAppUpdate: Schema.optionalKey(Schema.Boolean),
|
||||
});
|
||||
export type ExecutionEnvironmentCapabilities = typeof ExecutionEnvironmentCapabilities.Type;
|
||||
|
||||
|
||||
@@ -2,6 +2,7 @@ import * as Schema from "effect/Schema";
|
||||
|
||||
import { NonNegativeInt, PositiveInt, TrimmedNonEmptyString } from "./baseSchemas.ts";
|
||||
import { HostPowerSnapshot } from "./background.ts";
|
||||
import { DesktopUpdateStateSchema } from "./ipc.ts";
|
||||
|
||||
export const RESOURCE_MONITOR_PROTOCOL_VERSION = 2 as const;
|
||||
|
||||
@@ -244,9 +245,33 @@ export const DesktopHostTelemetryHello = Schema.Struct({
|
||||
});
|
||||
export type DesktopHostTelemetryHello = typeof DesktopHostTelemetryHello.Type;
|
||||
|
||||
/** Terminal marker for a server-triggered desktop update run. */
|
||||
export const DesktopUpdateRemoteOutcome = Schema.Literals(["installing", "up-to-date", "failed"]);
|
||||
export type DesktopUpdateRemoteOutcome = typeof DesktopUpdateRemoteOutcome.Type;
|
||||
|
||||
/**
|
||||
* Desktop main -> server: the desktop app's update state. Sent once when the
|
||||
* backend attaches and again on every state change, so the server always
|
||||
* knows whether the app on its machine can be updated and how a
|
||||
* server-triggered run is progressing.
|
||||
*/
|
||||
export const DesktopUpdateStatusReport = Schema.Struct({
|
||||
version: Schema.Literal(1),
|
||||
type: Schema.Literal("desktopUpdateStatus"),
|
||||
// Set while a server-triggered run owns the flow; absent for the attach
|
||||
// snapshot and for locally driven update activity.
|
||||
requestId: Schema.optionalKey(TrimmedNonEmptyString),
|
||||
// Terminal marker for a server-triggered run; absent while it is working.
|
||||
outcome: Schema.optionalKey(DesktopUpdateRemoteOutcome),
|
||||
reason: Schema.optionalKey(TrimmedNonEmptyString),
|
||||
state: DesktopUpdateStateSchema,
|
||||
});
|
||||
export type DesktopUpdateStatusReport = typeof DesktopUpdateStatusReport.Type;
|
||||
|
||||
export const DesktopHostTelemetryMessage = Schema.Union([
|
||||
DesktopHostTelemetryHello,
|
||||
DesktopHostTelemetrySnapshot,
|
||||
DesktopUpdateStatusReport,
|
||||
]);
|
||||
export type DesktopHostTelemetryMessage = typeof DesktopHostTelemetryMessage.Type;
|
||||
|
||||
@@ -266,9 +291,22 @@ export const DesktopTelemetrySetHostPowerIntervals = Schema.Struct({
|
||||
export type DesktopTelemetrySetHostPowerIntervals =
|
||||
typeof DesktopTelemetrySetHostPowerIntervals.Type;
|
||||
|
||||
/**
|
||||
* Server -> desktop main: run the app's own update flow now (check ->
|
||||
* download -> quit-and-install) with no local confirmation. The remote click
|
||||
* on the machine that sent the RPC is the consent.
|
||||
*/
|
||||
export const DesktopTelemetryRequestDesktopUpdate = Schema.Struct({
|
||||
version: Schema.Literal(1),
|
||||
type: Schema.Literal("requestDesktopUpdate"),
|
||||
requestId: TrimmedNonEmptyString,
|
||||
});
|
||||
export type DesktopTelemetryRequestDesktopUpdate = typeof DesktopTelemetryRequestDesktopUpdate.Type;
|
||||
|
||||
export const DesktopTelemetryControlMessage = Schema.Union([
|
||||
DesktopTelemetrySetDiagnosticsDemand,
|
||||
DesktopTelemetrySetHostPowerIntervals,
|
||||
DesktopTelemetryRequestDesktopUpdate,
|
||||
]);
|
||||
export type DesktopTelemetryControlMessage = typeof DesktopTelemetryControlMessage.Type;
|
||||
|
||||
|
||||
Reference in new issue
Block a user