Skip to content

Commit ac34343

Browse files
donjor-agent[bot]rsi-pr-agent
authored andcommitted
fix(fork): keep the client usable while the attached server restarts (#1712)
* fix(fork): keep the client usable while the attached server restarts Desktop: a restarted server reporting the same environment id re-verifies in place with its fresh pid/start time instead of dropping the attachment; identity stays the env-id find plus descriptor check, and late verifies or mints never drop or roll back a newer bearer or instance. Renderer: a primary absent from the topology stays registered (offline) for a five-minute grace before removal, so an update restart no longer wipes caches, drafts and open routes; on return it re-runs descriptor discovery, keeping the old registration through transient failures within the grace, so a different environment at the same URL replaces it. Covers #1706. Fork-Domain: backend-attach Fork-Tier: bugfix Fork-Upstreamable: no * fix(fork): time the primary absence grace on a monotonic clock An NTP step during the restart ended the wall-clock grace early and the poll wiped the client anyway. Covers #1706. Squashes: - 39611a4 fix(fork): keep the client usable while the attached server restarts (#1712) (#1712) - 7097dc3 fixup! fix(fork): keep the client usable while the attached server restarts (#1712) (#1712) - 5985a44 fix(fork): keep the client usable while the attached server restarts (#1712) (#1712) - dd6fb01 fixup! fix(fork): keep the client usable while the attached server restarts (#1712) (#1712) Fork-Domain: backend-attach Fork-Tier: bugfix Fork-Upstreamable: no
1 parent a1cfdb3 commit ac34343

6 files changed

Lines changed: 413 additions & 47 deletions

File tree

‎apps/desktop/src/app/DesktopAttachedPrimary.fork.test.ts‎

Lines changed: 179 additions & 27 deletions
Original file line numberDiff line numberDiff line change
@@ -150,14 +150,18 @@ const makeScenario = (input: {
150150
readonly pairGate?: (
151151
call: number,
152152
) => Effect.Effect<void, DesktopRunningLocalServers.LocalServerPairingError>;
153+
/** Holds a given descriptor fetch, i.e. one verify, open. */
154+
readonly descriptorGate?: (call: number) => Effect.Effect<void>;
155+
/** Answers a given descriptor fetch with a 503, failing that verify. */
156+
readonly descriptorFails?: (call: number) => boolean;
153157
}) =>
154158
Effect.gen(function* () {
155159
const live: Array<RunningLocalServer> = [server];
156-
const counts = { pair: 0, mint: 0 };
160+
const counts = { pair: 0, mint: 0, descriptor: 0 };
157161
const httpClientLayer = Layer.succeed(
158162
HttpClient.HttpClient,
159163
HttpClient.make((request) =>
160-
Effect.sync(() => {
164+
Effect.gen(function* () {
161165
if (request.url.endsWith("/oauth/token")) {
162166
counts.mint += 1;
163167
return tokenResponse(`attached-bearer-token-${counts.mint}`);
@@ -169,6 +173,11 @@ const makeScenario = (input: {
169173
input.sessionAuthenticated(authorization.value.replace(/^Bearer /, "")),
170174
);
171175
}
176+
const call = ++counts.descriptor;
177+
yield* input.descriptorGate?.(call) ?? Effect.void;
178+
if (input.descriptorFails?.(call) === true) {
179+
return HttpClientResponse.fromWeb(request, new Response("down", { status: 503 }));
180+
}
172181
return descriptorResponse(server.environmentId as string);
173182
}),
174183
),
@@ -384,7 +393,7 @@ describe("DesktopAttachedPrimary RSI-Software/t3code-hyprws#1350", () => {
384393
}),
385394
);
386395

387-
it.effect("catches a same-port restart via pid and start-time identity", () =>
396+
it.effect("keeps the attachment across a same-environment restart", () =>
388397
Effect.gen(function* () {
389398
let live: ReadonlyArray<RunningLocalServer> = [server];
390399
const httpClientLayer = Layer.succeed(
@@ -412,13 +421,62 @@ describe("DesktopAttachedPrimary RSI-Software/t3code-hyprws#1350", () => {
412421
);
413422

414423
assert.ok(Option.isSome(yield* service.attach(ATTACHED_PRIMARY_SELECTION_AUTO)));
415-
// Same URL, same env id — but a new pid and start time: the old server
416-
// is gone and its bearer must not be served against the replacement.
424+
// Same URL, same env id, new pid and start time: an update restart of
425+
// the same environment re-verifies in place and updates the held
426+
// identity instead of dropping the client's environments
427+
// (RSI-Software/t3code-hyprws#1706).
417428
live = [{ ...server, pid: 99, startedAt: "2026-02-02T00:00:00.000Z" }];
429+
const kept = yield* service.current;
430+
assert.ok(Option.isSome(kept));
431+
assert.strictEqual(kept.value.pid, 99);
432+
assert.ok(Option.isSome(service.cached()));
433+
// The persisted session store outlives the restart, so the held bearer
434+
// is still served without a re-pair.
435+
assert.strictEqual(yield* service.getBearerToken, "attached-bearer-token");
436+
}),
437+
);
438+
439+
it.effect("drops the attachment when a different environment takes the port", () =>
440+
Effect.gen(function* () {
441+
let live: ReadonlyArray<RunningLocalServer> = [server];
442+
const httpClientLayer = Layer.succeed(
443+
HttpClient.HttpClient,
444+
HttpClient.make((request) =>
445+
Effect.succeed(
446+
request.url.endsWith("/oauth/token")
447+
? tokenResponse("attached-bearer-token")
448+
: request.url.endsWith("/api/auth/session")
449+
? sessionResponse(true)
450+
: descriptorResponse(server.environmentId as string),
451+
),
452+
),
453+
);
454+
const discoveryLayer = Layer.succeed(DesktopRunningLocalServers.DesktopRunningLocalServers, {
455+
discover: Effect.suspend(() => Effect.succeed(live)),
456+
pairLocalServer: () =>
457+
Effect.succeed({
458+
pairingUrl: "http://127.0.0.1:3773/pair#token=PAIRCODE",
459+
pairingExpiresAt: "2099-01-01T00:00:00.000Z",
460+
}),
461+
} as unknown as DesktopRunningLocalServers.DesktopRunningLocalServers["Service"]);
462+
const service = yield* make.pipe(
463+
Effect.provide(Layer.mergeAll(discoveryLayer, httpClientLayer)),
464+
);
465+
466+
assert.ok(Option.isSome(yield* service.attach(ATTACHED_PRIMARY_SELECTION_AUTO)));
467+
// Same port, but the env id differs: a different server owns the
468+
// endpoint now and the attachment drops immediately.
469+
live = [
470+
{
471+
...server,
472+
pid: 99,
473+
startedAt: "2026-02-02T00:00:00.000Z",
474+
environmentId: otherEnvironmentId,
475+
},
476+
];
418477
assert.ok(Option.isNone(yield* service.current));
419478
assert.ok(Option.isNone(service.cached()));
420-
const token = yield* Effect.option(service.getBearerToken);
421-
assert.ok(Option.isNone(token));
479+
assert.ok(Option.isNone(yield* Effect.option(service.getBearerToken)));
422480
}),
423481
);
424482

@@ -538,39 +596,112 @@ describe("DesktopAttachedPrimary RSI-Software/t3code-hyprws#1350", () => {
538596
}),
539597
);
540598

541-
it.effect("a restart during a re-mint spares the successor from a late reject", () =>
599+
it.effect(
600+
"a restart during a re-mint publishes the restarted instance and spares it from a late reject",
601+
() =>
602+
Effect.gen(function* () {
603+
const gate = yield* held();
604+
const { service, live, counts } = yield* makeScenario({
605+
// The first bearer is revoked; every later one is live.
606+
sessionAuthenticated: (bearer) => bearer !== "attached-bearer-token-1",
607+
pairGate: (call) =>
608+
call === 2
609+
? Deferred.succeed(gate.started, undefined).pipe(
610+
Effect.andThen(Deferred.await(gate.release)),
611+
)
612+
: Effect.void,
613+
});
614+
assert.ok(Option.isSome(yield* service.attach(ATTACHED_PRIMARY_SELECTION_AUTO)));
615+
const remint = yield* service.getBearerToken.pipe(Effect.forkChild);
616+
yield* Deferred.await(gate.started);
617+
// The server restarts under the held re-mint; the poll re-verifies in
618+
// place instead of dropping.
619+
live.splice(0, live.length, restartedServer);
620+
const kept = yield* service.refresh;
621+
assert.ok(Option.isSome(kept));
622+
assert.strictEqual(kept.value.pid, restartedServer.pid);
623+
yield* Deferred.succeed(gate.release, undefined);
624+
// The re-mint completes and publishes the restarted instance.
625+
assert.strictEqual(yield* Fiber.join(remint), "attached-bearer-token-2");
626+
// The renderer's late report names the old bearer: the successor stays.
627+
yield* service.reject("attached-bearer-token-1", "transport");
628+
assert.ok(Option.isSome(service.cached()));
629+
// The new bearer is rejected before anything re-verifies: the skip
630+
// lands on the restarted instance the mint published, not the one it
631+
// started under, so the same server never auto-attaches again.
632+
yield* service.reject("attached-bearer-token-2", "unauthorized");
633+
assert.ok(Option.isNone(yield* service.refreshOrAttach));
634+
assert.strictEqual(counts.pair, 2);
635+
// Only another restart clears the skip.
636+
live.splice(0, live.length, { ...restartedServer, pid: 100 });
637+
const again = yield* service.refreshOrAttach;
638+
assert.ok(Option.isSome(again));
639+
assert.strictEqual(again.value.pid, 100);
640+
}),
641+
);
642+
643+
it.effect("a stale failed verify does not drop a newer verified restart", () =>
542644
Effect.gen(function* () {
543645
const gate = yield* held();
544-
const { service, live, counts } = yield* makeScenario({
545-
// The first bearer is revoked; every later one is live.
546-
sessionAuthenticated: (bearer) => bearer !== "attached-bearer-token-1",
547-
pairGate: (call) =>
646+
const { service, live } = yield* makeScenario({
647+
sessionAuthenticated: () => true,
648+
// Call 1 is the attach verify; call 2, the older refresh, fails late.
649+
descriptorGate: (call) =>
548650
call === 2
549651
? Deferred.succeed(gate.started, undefined).pipe(
550652
Effect.andThen(Deferred.await(gate.release)),
551653
)
552654
: Effect.void,
655+
descriptorFails: (call) => call === 2,
553656
});
554657
assert.ok(Option.isSome(yield* service.attach(ATTACHED_PRIMARY_SELECTION_AUTO)));
555-
const remint = yield* service.getBearerToken.pipe(Effect.forkChild);
658+
live.splice(0, live.length, restartedServer);
659+
const older = yield* service.refresh.pipe(Effect.forkChild);
556660
yield* Deferred.await(gate.started);
557-
// The server restarts under the held re-mint; the poll drops and re-attaches.
661+
// A newer verify sees the restarted server first and publishes it.
662+
const newer = yield* service.refresh;
663+
assert.ok(Option.isSome(newer));
664+
assert.strictEqual(newer.value.pid, restartedServer.pid);
665+
yield* Deferred.succeed(gate.release, undefined);
666+
const stale = yield* Fiber.join(older);
667+
// The older request's failure is stale: the healthy attachment stays.
668+
assert.ok(Option.isSome(stale));
669+
assert.strictEqual(stale.value.pid, restartedServer.pid);
670+
assert.ok(Option.isSome(service.cached()));
671+
assert.strictEqual(yield* service.getBearerToken, "attached-bearer-token-1");
672+
}),
673+
);
674+
675+
it.effect("a refresh that finishes after a re-mint keeps the new bearer", () =>
676+
Effect.gen(function* () {
677+
const gate = yield* held();
678+
const { service, live } = yield* makeScenario({
679+
sessionAuthenticated: (bearer) => bearer !== "attached-bearer-token-1",
680+
// Call 1 is the attach verify; call 2 is the background refresh.
681+
descriptorGate: (call) =>
682+
call === 2
683+
? Deferred.succeed(gate.started, undefined).pipe(
684+
Effect.andThen(Deferred.await(gate.release)),
685+
)
686+
: Effect.void,
687+
});
688+
assert.ok(Option.isSome(yield* service.attach(ATTACHED_PRIMARY_SELECTION_AUTO)));
689+
// The server restarts and a poll starts verifying it, captured under
690+
// the first bearer, then stalls.
558691
live.splice(0, live.length, restartedServer);
559-
assert.ok(Option.isNone(yield* service.refresh));
560-
const reattach = yield* service.refreshOrAttach.pipe(Effect.forkChild);
692+
const refresh = yield* service.refresh.pipe(Effect.forkChild);
693+
yield* Deferred.await(gate.started);
694+
// Meanwhile a bearer read finds the first bearer revoked and re-mints.
695+
assert.strictEqual(yield* service.getBearerToken, "attached-bearer-token-2");
561696
yield* Deferred.succeed(gate.release, undefined);
562-
// The stale re-mint never publishes over the dropped attachment.
563-
assert.ok(Option.isNone(yield* Fiber.join(remint).pipe(Effect.option)));
564-
const successor = yield* Fiber.join(reattach);
565-
assert.ok(Option.isSome(successor));
566-
assert.strictEqual(successor.value.pid, restartedServer.pid);
567-
const successorToken = yield* service.getBearerToken;
568-
assert.strictEqual(successorToken, `attached-bearer-token-${counts.mint}`);
569-
// The renderer's late report names the old bearer: the successor stays.
570-
yield* service.reject("attached-bearer-token-1", "transport");
697+
const refreshed = yield* Fiber.join(refresh);
698+
assert.ok(Option.isSome(refreshed));
699+
assert.strictEqual(refreshed.value.pid, restartedServer.pid);
700+
// The late refresh did not restore the first bearer, so its late
701+
// reject is a no-op and the successor stays attached.
702+
yield* service.reject("attached-bearer-token-1", "unauthorized");
571703
assert.ok(Option.isSome(service.cached()));
572-
assert.strictEqual(yield* service.getBearerToken, successorToken);
573-
assert.ok(Option.isSome(yield* service.refreshOrAttach));
704+
assert.strictEqual(yield* service.getBearerToken, "attached-bearer-token-2");
574705
}),
575706
);
576707

@@ -589,6 +720,27 @@ describe("DesktopAttachedPrimary RSI-Software/t3code-hyprws#1350", () => {
589720
}),
590721
);
591722

723+
it.effect("a reject backoff does not delay re-attach after a restart", () =>
724+
Effect.gen(function* () {
725+
const { service, live, counts } = yield* makeScenario({
726+
sessionAuthenticated: () => true,
727+
});
728+
assert.ok(Option.isSome(yield* service.attach(ATTACHED_PRIMARY_SELECTION_AUTO)));
729+
yield* service.reject(yield* service.getBearerToken, "transport");
730+
assert.ok(Option.isNone(service.cached()));
731+
// One reset is not a verdict: the same instance waits out the backoff.
732+
assert.ok(Option.isNone(yield* service.refreshOrAttach));
733+
assert.strictEqual(counts.pair, 1);
734+
// A restart is a new instance with empty backoff: the next poll
735+
// re-attaches at once instead of waiting out the old window.
736+
live.splice(0, live.length, restartedServer);
737+
const reattached = yield* service.refreshOrAttach;
738+
assert.ok(Option.isSome(reattached));
739+
assert.strictEqual(reattached.value.pid, restartedServer.pid);
740+
assert.strictEqual(counts.pair, 2);
741+
}),
742+
);
743+
592744
it.effect("a slow pair failure starts its backoff when it fails", () =>
593745
Effect.gen(function* () {
594746
const { service, counts } = yield* makeScenario({

‎apps/desktop/src/app/DesktopAttachedPrimary.ts‎

Lines changed: 25 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -144,6 +144,9 @@ export const make = Effect.gen(function* () {
144144
const state: { current: AttachmentState | null } = { current: null };
145145
const cache: { current: CachedAttachedBootstrap | null } = { current: null };
146146
const generation = { current: 0 };
147+
// Re-verifies run outside the lock and can finish out of order: only the
148+
// newest result publishes a server instance.
149+
const verifications = { started: 0, published: 0 };
147150
// Server instances auto-attach skips: a 401 survived a re-mint, so its auth
148151
// is broken. A restart is a new identity, so it attaches again.
149152
const skipped = new Set<string>();
@@ -169,14 +172,12 @@ export const make = Effect.gen(function* () {
169172
}
170173
// discover() verifies env id (persisted vs probed descriptor) and
171174
// endpoint reachability, but a restart on the SAME port keeps both.
172-
// Identity beyond the URL: pid + start time must match, and the live
173-
// descriptor must still report the attached env id. Anything else
174-
// means the server restarted away: never serve a stale primary.
175-
if (live.pid !== server.pid || live.startedAt !== server.startedAt) {
176-
return yield* new DesktopAttachedPrimaryUnavailableError({
177-
detail: `Attached server ${server.environmentId} restarted (pid or start time changed).`,
178-
});
179-
}
175+
// Identity is the environment id: the live descriptor must still report
176+
// the attached env id. A same-environment restart (an update restart)
177+
// then re-verifies in place with its fresh pid/start time
178+
// (RSI-Software/t3code-hyprws#1706) instead of dropping the client's
179+
// environments; a different server reports a different env id and is
180+
// rejected here or by the discovery find above.
180181
const descriptor = yield* fetchDescriptorEnvironmentId(live);
181182
if (descriptor.environmentId !== server.environmentId) {
182183
return yield* new DesktopAttachedPrimaryUnavailableError({
@@ -320,19 +321,30 @@ export const make = Effect.gen(function* () {
320321
// matches, so a stale primary is never served.
321322
const reverify = Effect.gen(function* () {
322323
const started = generation.current;
324+
const sequence = ++verifications.started;
323325
const held = state.current;
324326
if (held === null) {
325327
return Option.none<RunningLocalServer>();
326328
}
327329
const verified = yield* verifyServer(held.server).pipe(Effect.option);
328-
if (generation.current !== started) {
329-
// Something newer dropped or replaced the attachment meanwhile.
330+
// Something newer dropped or replaced the attachment meanwhile, or a
331+
// later verify already published: a stale result, success or failure,
332+
// must neither drop nor roll back the attachment.
333+
if (generation.current !== started || sequence < verifications.published) {
330334
return heldServer();
331335
}
332336
if (Option.isNone(verified) || verified.value.httpBaseUrl !== held.server.httpBaseUrl) {
333337
dropNow();
334338
return Option.none<RunningLocalServer>();
335339
}
340+
verifications.published = sequence;
341+
// A same-environment restart re-attaches in place: track the new instance
342+
// so identity-keyed skip/backoff state and snapshots follow it. Update the
343+
// current attachment, not `held`: a mint may have replaced its bearer.
344+
const latest = state.current ?? held;
345+
if (serverIdentity(verified.value) !== serverIdentity(latest.server)) {
346+
state.current = { ...latest, server: verified.value };
347+
}
336348
cache.current = { server: verified.value };
337349
return Option.some(verified.value);
338350
});
@@ -408,11 +420,9 @@ export const make = Effect.gen(function* () {
408420
dropNow();
409421
return yield* new DesktopAttachedPrimaryNotAttachedError();
410422
}
411-
state.current = {
412-
selection: held.selection,
413-
server: live.value,
414-
bearerToken: bearerToken.value,
415-
};
423+
// Keep the latest verified instance: a restart re-verified during the
424+
// mint must stay the identity an unauthorized reject skips.
425+
state.current = { ...(state.current ?? held), bearerToken: bearerToken.value };
416426
return bearerToken.value;
417427
});
418428

‎apps/web/src/connection/platform.ts‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -68,6 +68,7 @@ import {
6868
} from "./desktopLocal";
6969
import * as ConnectionStorage from "./storage";
7070
import { clientPresentationMetadata } from "./clientMetadata";
71+
import { keepPrimaryThroughAbsenceFork } from "./primaryAbsenceGrace.fork"; // fork-hook: backend-attach/platform-absence-import
7172

7273
let nextObservedRpcRequestId = 0;
7374

@@ -689,6 +690,7 @@ const layerPlatformConnectionSource = Layer.effect(
689690
}
690691
}
691692
}
693+
keepPrimaryThroughAbsenceFork(previous, next, registrations, primaryTopologyRead); // fork-hook: backend-attach/platform-absence-grace
692694

693695
const topologyRead = readDesktopSecondaryBootstrapsResult();
694696
for (const [id, cached] of secondaryRegistrationsToRetainAfterTopologyRead(

0 commit comments

Comments
 (0)