Skip to content

Commit 300d888

Browse files
authored
Merge branch 'main' into pr/grok-native
2 parents 29e5c6b + 990bb0b commit 300d888

5 files changed

Lines changed: 103 additions & 88 deletions

File tree

‎apps/server/src/server.ts‎

Lines changed: 7 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -583,8 +583,13 @@ export const makeServerLayer = Layer.unwrap(
583583
const server = yield* HttpServer.HttpServer;
584584
const address = server.address;
585585
if (typeof address === "string" || !("port" in address)) return;
586-
yield* Effect.sleep("250 millis").pipe(
587-
Effect.andThen(reconcileDesiredCloudLink(`http://127.0.0.1:${address.port}`)),
586+
// No settling delay before the first attempt: routes are already
587+
// serving by the time activation opens this gate (the startup
588+
// sequence awaits routesReady), and the retry schedule below
589+
// covers anything this sleep used to hedge against. Every
590+
// millisecond here is dead time on the path to remote
591+
// reachability after a restart.
592+
yield* reconcileDesiredCloudLink(`http://127.0.0.1:${address.port}`).pipe(
588593
Effect.retry({
589594
while: (error) =>
590595
error._tag !== "EnvironmentHttpBadRequestError" &&

‎apps/web/src/terminal/ghostty/surface.test.ts‎

Lines changed: 0 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -23,7 +23,6 @@ import {
2323
terminalLinkAtPositionWithRange,
2424
terminalContentOriginY,
2525
terminalFontFamily,
26-
fittedTerminalFontSize,
2726
terminalFontSize,
2827
terminalWheelArrowData,
2928
terminalWheelDeltaRows,
@@ -343,24 +342,6 @@ describe("terminal font resolution", () => {
343342
expect(terminalFontFamily(" , ")).toBe(DEFAULT_TERMINAL_FONT_FAMILY);
344343
});
345344

346-
it("slides the rendered size down until a full-width grid fits the canvas", () => {
347-
// SF Mono-like advance: 0.6em per cell.
348-
const cellWidthAt = (size: number) => size * 0.6;
349-
// A wide drawer keeps the preference untouched.
350-
expect(fittedTerminalFontSize(cellWidthAt, 20, 1140)).toBe(20);
351-
// A split pane at the same preference shrinks until 80 columns fit.
352-
const fitted = fittedTerminalFontSize(cellWidthAt, 20, 570);
353-
expect(fitted).toBeLessThan(20);
354-
expect(Math.floor((570 - 8) / cellWidthAt(fitted))).toBeGreaterThanOrEqual(80);
355-
// A tiny pane stops at the legibility floor instead of vanishing.
356-
expect(fittedTerminalFontSize(cellWidthAt, 20, 220)).toBe(8);
357-
// A preference below the floor is honored as-is.
358-
expect(fittedTerminalFontSize(cellWidthAt, 6, 220)).toBe(6);
359-
// Unmeasured layouts leave the preference alone.
360-
expect(fittedTerminalFontSize(cellWidthAt, 14, 0)).toBe(14);
361-
expect(fittedTerminalFontSize(() => 0, 14, 600)).toBe(14);
362-
});
363-
364345
it("clamps requested font sizes to the supported range", () => {
365346
expect(terminalFontSize()).toBe(DEFAULT_TERMINAL_FONT_SIZE);
366347
expect(terminalFontSize(Number.NaN)).toBe(DEFAULT_TERMINAL_FONT_SIZE);

‎apps/web/src/terminal/ghostty/surface.ts‎

Lines changed: 5 additions & 55 deletions
Original file line numberDiff line numberDiff line change
@@ -129,42 +129,6 @@ export async function loadTerminalFontFamily(
129129
return (environment?.resolve ?? terminalFontFamily)(family);
130130
}
131131

132-
/**
133-
* Grids narrower than a classic 80-column terminal wrap command output hard,
134-
* so the rendered font size follows the canvas width: the preference is the
135-
* ceiling, and the size slides down (to a legibility floor) until a full-width
136-
* grid fits. A widening pane slides it back up toward the preference.
137-
*/
138-
const MIN_TERMINAL_FIT_COLUMNS = 80;
139-
const MIN_TERMINAL_FIT_FONT_SIZE = 8;
140-
141-
export function fittedTerminalFontSize(
142-
cellWidthAt: (size: number) => number,
143-
requested: number,
144-
mountWidth: number,
145-
): number {
146-
const available = mountWidth - CONTENT_PADDING * 2;
147-
if (available <= 0) return requested;
148-
const floor = Math.min(requested, MIN_TERMINAL_FIT_FONT_SIZE);
149-
const fits = (cellWidth: number) =>
150-
cellWidth > 0 && Math.floor(available / cellWidth) >= MIN_TERMINAL_FIT_COLUMNS;
151-
let cellWidth = cellWidthAt(requested);
152-
if (cellWidth <= 0 || fits(cellWidth)) return requested;
153-
// The advance scales linearly with size for monospace faces: jump close to
154-
// the fitting size, then settle the remaining rounding one step at a time.
155-
const targetCellWidth = available / MIN_TERMINAL_FIT_COLUMNS;
156-
let size = Math.max(
157-
floor,
158-
Math.min(requested, Math.floor((requested * targetCellWidth) / cellWidth)),
159-
);
160-
while (size > floor) {
161-
cellWidth = cellWidthAt(size);
162-
if (cellWidth <= 0 || fits(cellWidth)) break;
163-
size -= 1;
164-
}
165-
return size;
166-
}
167-
168132
export function terminalFontSize(size?: number): number {
169133
if (size === undefined || !Number.isFinite(size)) return DEFAULT_TERMINAL_FONT_SIZE;
170134
return Math.max(MIN_TERMINAL_FONT_SIZE, Math.min(MAX_TERMINAL_FONT_SIZE, Math.round(size)));
@@ -519,7 +483,6 @@ export class GhosttyTerminalSurface {
519483
private fontFamily: string;
520484
private requestedFontFamily: string | undefined;
521485
private fontSize: number;
522-
private requestedFontSize: number;
523486
private fontEpoch = 0;
524487
private pendingFontEpoch: number | null = null;
525488
private readonly resizeObserver: ResizeObserver;
@@ -601,7 +564,6 @@ export class GhosttyTerminalSurface {
601564
this.fontFamily = fontFamily;
602565
this.requestedFontFamily = options.font?.family;
603566
this.fontSize = terminalFontSize(options.font?.size);
604-
this.requestedFontSize = this.fontSize;
605567
this.resizeObserver = new ResizeObserver(() => this.fit());
606568
this.installEvents();
607569
this.watchDevicePixelRatio();
@@ -642,6 +604,11 @@ export class GhosttyTerminalSurface {
642604

643605
const context = canvas.getContext("2d", { alpha: false });
644606
if (!context) throw new Error("Canvas 2D is unavailable");
607+
// An opaque canvas backing store initializes to solid black, and the font
608+
// and WASM loads below leave it on screen for the whole setup window; paint
609+
// the theme background first so the mount never flashes a black box.
610+
context.fillStyle = `rgb(${options.theme.background.r}, ${options.theme.background.g}, ${options.theme.background.b})`;
611+
context.fillRect(0, 0, canvas.width, canvas.height);
645612
const fontSize = terminalFontSize(options.font?.size);
646613
try {
647614
// Cell metrics must come from the faces that will render; measuring before
@@ -719,7 +686,6 @@ export class GhosttyTerminalSurface {
719686
this.pendingFontEpoch = null;
720687
this.fontFamily = fontFamily;
721688
this.requestedFontFamily = font.family;
722-
this.requestedFontSize = fontSize;
723689
this.fontSize = fontSize;
724690
this.applyFontMetrics();
725691
}
@@ -775,22 +741,6 @@ export class GhosttyTerminalSurface {
775741
const width = this.mount.clientWidth;
776742
const height = this.mount.clientHeight;
777743
if (width <= 0 || height <= 0) return false;
778-
const fitted = fittedTerminalFontSize(
779-
(size) => measureGhosttyCell(this.context, size, this.fontFamily).width,
780-
this.requestedFontSize,
781-
width,
782-
);
783-
if (fitted !== this.fontSize) {
784-
this.fontSize = fitted;
785-
this.metrics = measureGhosttyCell(this.context, this.fontSize, this.fontFamily);
786-
// The grid-change branch below resizes the core, but only when the
787-
// column count moved; the cell geometry always did, so sync it here.
788-
this.core.resize(this.cols, this.rows, this.metrics.width, this.metrics.height);
789-
this.inputLeft = -1;
790-
this.inputTop = -1;
791-
this.forceFullRender = true;
792-
this.scrollbarDirty = true;
793-
}
794744
const ratio = window.devicePixelRatio || 1;
795745
const pixelWidth = Math.max(1, Math.round(width * ratio));
796746
const pixelHeight = Math.max(1, Math.round(height * ratio));

‎packages/client-runtime/src/state/server.test.ts‎

Lines changed: 55 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -7,12 +7,16 @@ import {
77
} from "@t3tools/contracts";
88
import { describe, expect, it } from "@effect/vitest";
99
import * as Cause from "effect/Cause";
10+
import * as Duration from "effect/Duration";
1011
import * as Effect from "effect/Effect";
1112
import * as Exit from "effect/Exit";
13+
import * as Fiber from "effect/Fiber";
1214
import * as Option from "effect/Option";
1315
import * as Queue from "effect/Queue";
16+
import * as Ref from "effect/Ref";
1417
import * as Stream from "effect/Stream";
1518
import * as SubscriptionRef from "effect/SubscriptionRef";
19+
import * as TestClock from "effect/testing/TestClock";
1620
import { RpcClientError } from "effect/unstable/rpc";
1721
import * as Socket from "effect/unstable/socket/Socket";
1822

@@ -30,6 +34,7 @@ import {
3034
makeEnvironmentServerConfigState,
3135
isLegacyUpdateHandoffLoss,
3236
matchesServerUpdateReadyEvent,
37+
nudgeReconnectDuringUpdateRestart,
3338
projectServerWelcome,
3439
resolveServerConfigValue,
3540
resolveServerUpdateProgressResult,
@@ -71,6 +76,56 @@ function session(client: WsRpcProtocolClient): RpcSession {
7176
};
7277
}
7378

79+
describe("update restart reconnect nudges", () => {
80+
it.effect("retries once per backoff entry instead of only the first", () =>
81+
Effect.gen(function* () {
82+
const retries = yield* Ref.make(0);
83+
const states = [
84+
{ phase: "backoff" },
85+
{ phase: "connecting" },
86+
{ phase: "backoff" },
87+
{ phase: "backoff" },
88+
];
89+
90+
yield* nudgeReconnectDuringUpdateRestart({
91+
stateChanges: Stream.fromIterable(states),
92+
retryNow: Ref.update(retries, (count) => count + 1),
93+
interval: Duration.zero,
94+
});
95+
96+
// Three backoff entries, three nudges. The old one-shot behavior fired
97+
// once and then let the supervisor's ladder stretch to 16-second gaps.
98+
expect(yield* Ref.get(retries)).toBe(3);
99+
}),
100+
);
101+
102+
it.effect("paces nudges so a fast-failing connection cannot spin", () =>
103+
Effect.gen(function* () {
104+
const retries = yield* Ref.make(0);
105+
106+
const fiber = yield* Effect.forkChild(
107+
nudgeReconnectDuringUpdateRestart({
108+
stateChanges: Stream.fromIterable([{ phase: "backoff" }, { phase: "backoff" }]),
109+
retryNow: Ref.update(retries, (count) => count + 1),
110+
}),
111+
{ startImmediately: true },
112+
);
113+
114+
// Each nudge waits out the interval first, so nothing fires immediately.
115+
yield* TestClock.adjust(Duration.millis(999));
116+
expect(yield* Ref.get(retries)).toBe(0);
117+
118+
yield* TestClock.adjust(Duration.millis(1));
119+
expect(yield* Ref.get(retries)).toBe(1);
120+
121+
yield* TestClock.adjust(Duration.seconds(1));
122+
expect(yield* Ref.get(retries)).toBe(2);
123+
124+
yield* Fiber.join(fiber);
125+
}).pipe(Effect.provide(TestClock.layer())),
126+
);
127+
});
128+
74129
describe("server state projection", () => {
75130
it("only treats a legacy transport interruption as an unacknowledged handoff", () => {
76131
expect(isLegacyUpdateHandoffLoss(Cause.interrupt(1))).toBe(true);

‎packages/client-runtime/src/state/server.ts‎

Lines changed: 36 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -149,6 +149,35 @@ export function validateServerUpdateReadyEvent(
149149
);
150150
}
151151

152+
/**
153+
* Keeps reconnect attempts ~1s apart for the whole update restart.
154+
*
155+
* A restart takes the server down for ~15 seconds, but the supervisor's normal
156+
* backoff ladder (1/2/4/8/16s) assumes an unexpected failure and lands attempts
157+
* at ~3, 5, 9, 17 and 33 seconds — so a 15-second restart is observed as a
158+
* 33-second "Resuming". Nudging on every backoff entry (not just the first)
159+
* holds the retry cadence flat until the server answers again. The sleep before
160+
* each nudge is the pacer: a connection that fails instantly re-enters backoff
161+
* immediately and would otherwise spin a tight retry loop.
162+
*
163+
* Callers fork this as a child of the update command so it is interrupted as
164+
* soon as the update settles, whether it succeeds, fails, or times out.
165+
*/
166+
export function nudgeReconnectDuringUpdateRestart(input: {
167+
readonly stateChanges: Stream.Stream<{ readonly phase: string }, unknown>;
168+
readonly retryNow: Effect.Effect<void>;
169+
readonly interval?: Duration.Duration;
170+
}): Effect.Effect<void> {
171+
return input.stateChanges.pipe(
172+
Stream.filter((state) => state.phase === "backoff"),
173+
Stream.runForEach(() =>
174+
Effect.sleep(input.interval ?? Duration.seconds(1)).pipe(Effect.andThen(input.retryNow)),
175+
),
176+
Effect.timeoutOption(SERVER_UPDATE_RESUME_TIMEOUT),
177+
Effect.ignore,
178+
);
179+
}
180+
152181
export function serverUpdateStateForProgressEvent(
153182
fromVersion: string,
154183
targetVersion: string,
@@ -589,18 +618,13 @@ export function createServerEnvironmentAtoms<R, E>(
589618
}),
590619
);
591620

592-
// The update restart is intentional. As soon as the supervisor sees
593-
// that first failed connection, discard any prior backoff debt and
594-
// retry immediately instead of carrying an old 16-second delay.
595-
yield* environmentRegistry.stateChanges(target.environmentId).pipe(
596-
Stream.filter((state) => state.phase === "backoff"),
597-
Stream.take(1),
598-
Stream.runDrain,
599-
Effect.andThen(environmentRegistry.retryNow(target.environmentId)),
600-
Effect.timeoutOption(Duration.seconds(30)),
601-
Effect.ignore,
602-
Effect.forkChild,
603-
);
621+
// The update restart is intentional and the server stays unreachable
622+
// for the whole restart, so hold the retry cadence flat instead of
623+
// letting the supervisor climb its backoff ladder.
624+
yield* nudgeReconnectDuringUpdateRestart({
625+
stateChanges: environmentRegistry.stateChanges(target.environmentId),
626+
retryNow: environmentRegistry.retryNow(target.environmentId),
627+
}).pipe(Effect.forkChild);
604628

605629
const resumed = yield* environmentRegistry
606630
.followStream(target.environmentId, subscribe(WS_METHODS.subscribeServerLifecycle, {}))

0 commit comments

Comments
 (0)