Compare commits

...
17 changed files with 475 additions and 141 deletions

No files matched your search

@@ -1,6 +1,10 @@
name: Mobile Showcase Screenshots
on:
push:
branches:
- t3bot/mobile-pending-card-glass
- t3bot/mobile-pending-card-glass-before
workflow_dispatch:
inputs:
platform:
@@ -31,7 +35,7 @@ env:
jobs:
ios:
name: iPhone 6.9, iPhone 6.5, and iPad 13
if: inputs.platform == 'all' || inputs.platform == 'ios'
if: github.event_name == 'push' || inputs.platform == 'all' || inputs.platform == 'ios'
runs-on: blacksmith-12vcpu-macos-26
timeout-minutes: 60
steps:
@@ -62,10 +66,10 @@ jobs:
"$vp_pnpm_bin/pnpm" --version
- name: Capture iOS showcase
run: pnpm screenshots:mobile --platform ios --appearance "${{ inputs.appearance }}"
run: pnpm screenshots:mobile --platform ios --appearance "${{ inputs.appearance || 'dark' }}"
- name: Validate App Store Connect assets
run: pnpm screenshots:mobile --platform ios --appearance "${{ inputs.appearance }}" --validate-only
run: pnpm screenshots:mobile --platform ios --appearance "${{ inputs.appearance || 'dark' }}" --validate-only
- name: Upload iOS screenshots
if: always()
@@ -1,4 +1,11 @@
import { Platform, ScrollView, View, useColorScheme } from "react-native";
import {
Platform,
ScrollView,
type StyleProp,
type TextStyle,
View,
useColorScheme,
} from "react-native";
import { AppText as Text } from "../../../../components/AppText";
import {
@@ -54,14 +61,48 @@ export function TerminalAppearancePreview(props: { readonly fontSize: number })
fontSize: props.fontSize,
lineHeight,
} as const;
// AppText stamps the sans font on every node, so nested spans must
// re-apply the terminal font instead of relying on inheritance, exactly
// like the code preview's tokens below.
const span = (color: string, extra?: TextStyle): StyleProp<TextStyle> => [
lineStyle,
{ color, ...extra },
];
return (
<View className="p-4">
<Text style={[lineStyle, { color: theme.foreground }]}>$ npm run dev</Text>
<Text style={[lineStyle, { color: theme.palette[2] }]}>✓ Ready in 430ms</Text>
<Text style={[lineStyle, { color: theme.foreground }]}>
Local: http://localhost:3000{" "}
<Text style={[lineStyle, { color: theme.cursorForeground }]}>▏</Text>
<Text style={span(theme.foreground)}>
<Text style={span(theme.palette[2])}>→ </Text>
<Text style={span(theme.palette[6])}>t3code </Text>
<Text style={span(theme.palette[4])}>git:(</Text>
<Text style={span(theme.palette[1])}>main</Text>
<Text style={span(theme.palette[4])}>)</Text>
<Text style={span(theme.palette[3])}> ✗</Text>
<Text style={span(theme.foreground)}> vpr dev</Text>
</Text>
<Text style={span(theme.foreground)}>
<Text style={span(theme.palette[2])}>VITE v7.1.1</Text>
<Text style={span(theme.mutedForeground)}> ready in</Text>
<Text style={span(theme.foreground)}> 1.24s</Text>
</Text>
<Text style={span(theme.foreground)}>
<Text style={span(theme.palette[2])}>→ </Text>
<Text style={span(theme.mutedForeground)}>Local: </Text>
<Text style={span(theme.palette[6], { textDecorationLine: "underline" })}>
http://127.0.0.1:5173/
</Text>
</Text>
<Text style={span(theme.foreground)}>
<Text style={span(theme.palette[2])}>✓ 85 passed</Text>
<Text style={span(theme.palette[3])}> △ 2 warnings</Text>
<Text style={span(theme.palette[1])}> ✗ 0 failed</Text>
</Text>
<Text style={span(theme.foreground)}>
<Text style={span(theme.background, { backgroundColor: theme.palette[2] })}>
{" READY "}
</Text>
<Text style={span(theme.mutedForeground)}> watching for changes</Text>{" "}
<Text style={span(theme.cursorForeground)}>▏</Text>
</Text>
</View>
);
@@ -3,6 +3,7 @@ import { Pressable, View } from "react-native";
import { AppText as Text } from "../../components/AppText";
import type { PendingApproval } from "../../lib/threadActivity";
import { PendingCardSurface } from "./PendingCardSurface";
export interface PendingApprovalCardProps {
readonly approval: PendingApproval;
@@ -15,7 +16,7 @@ export interface PendingApprovalCardProps {
export function PendingApprovalCard(props: PendingApprovalCardProps) {
return (
<View className="gap-2.5 rounded-[20px] border border-neutral-200 bg-neutral-100/80 p-4 dark:border-white/6 dark:bg-neutral-900/80">
<PendingCardSurface>
<Text className="font-t3-bold text-2xs uppercase tracking-[1.1px] text-sky-700 dark:text-sky-300">
Approval needed
</Text>
@@ -52,6 +53,6 @@ export function PendingApprovalCard(props: PendingApprovalCardProps) {
<Text className="font-t3-bold text-sm text-rose-700 dark:text-rose-300">Decline</Text>
</Pressable>
</View>
</View>
</PendingCardSurface>
);
}
@@ -0,0 +1,35 @@
import { isLiquidGlassSupported, LiquidGlassView } from "@callstack/liquid-glass";
import type { ReactNode } from "react";
import { useColorScheme, View, type ViewStyle } from "react-native";
const SURFACE_STYLE: ViewStyle = {
borderRadius: 20,
overflow: "hidden",
};
export function PendingCardSurface(props: { readonly children: ReactNode }) {
const isDarkMode = useColorScheme() === "dark";
const content = <View className="gap-2.5 p-4">{props.children}</View>;
if (isLiquidGlassSupported) {
return (
<LiquidGlassView
effect="regular"
interactive
colorScheme={isDarkMode ? "dark" : "light"}
style={SURFACE_STYLE}
>
{content}
</LiquidGlassView>
);
}
return (
<View
className="rounded-[20px] border border-neutral-200 bg-neutral-100 dark:border-white/6 dark:bg-neutral-900"
style={SURFACE_STYLE}
>
{content}
</View>
);
}
@@ -4,6 +4,7 @@ import { Pressable, View } from "react-native";
import { AppText as Text, AppTextInput as TextInput } from "../../components/AppText";
import { cn } from "../../lib/cn";
import type { PendingUserInput, PendingUserInputDraftAnswer } from "../../lib/threadActivity";
import { PendingCardSurface } from "./PendingCardSurface";
export interface PendingUserInputCardProps {
readonly pendingUserInput: PendingUserInput;
@@ -25,7 +26,7 @@ export interface PendingUserInputCardProps {
export function PendingUserInputCard(props: PendingUserInputCardProps) {
return (
<View className="gap-2.5 rounded-[20px] border border-neutral-200 bg-neutral-100/80 p-4 dark:border-white/6 dark:bg-neutral-900/80">
<PendingCardSurface>
<Text className="font-t3-bold text-2xs uppercase tracking-[1.1px] text-sky-700 dark:text-sky-300">
User input needed
</Text>
@@ -100,6 +101,6 @@ export function PendingUserInputCard(props: PendingUserInputCardProps) {
>
<Text className="font-t3-extrabold text-sm text-white">Submit answers</Text>
</Pressable>
</View>
</PendingCardSurface>
);
}
+7 -2
View File
@@ -583,8 +583,13 @@ export const makeServerLayer = Layer.unwrap(
const server = yield* HttpServer.HttpServer;
const address = server.address;
if (typeof address === "string" || !("port" in address)) return;
yield* Effect.sleep("250 millis").pipe(
Effect.andThen(reconcileDesiredCloudLink(`http://127.0.0.1:${address.port}`)),
// No settling delay before the first attempt: routes are already
// serving by the time activation opens this gate (the startup
// sequence awaits routesReady), and the retry schedule below
// covers anything this sleep used to hedge against. Every
// millisecond here is dead time on the path to remote
// reachability after a restart.
yield* reconcileDesiredCloudLink(`http://127.0.0.1:${address.port}`).pipe(
Effect.retry({
while: (error) =>
error._tag !== "EnvironmentHttpBadRequestError" &&
+43
View File
@@ -1,6 +1,7 @@
import { describe, expect, it } from "vite-plus/test";
import {
areFontAdvancesMonospace,
clampCodeFontSize,
clampInterfaceFontSize,
clampPromptFontSize,
@@ -9,8 +10,22 @@ import {
appearanceFontStack,
cssFontFamilies,
resolveDefaultFamilyLabel,
resolveTerminalFontPreference,
} from "./appearanceFonts";
describe("areFontAdvancesMonospace", () => {
it("accepts a fixed advance and rejects any proportional glyph", () => {
expect(areFontAdvancesMonospace([10, 10, 10, 10])).toBe(true);
expect(areFontAdvancesMonospace([10, 10, 7, 10])).toBe(false);
expect(areFontAdvancesMonospace([10, 10.02])).toBe(false);
});
it("fails open when canvas metrics are unavailable", () => {
expect(areFontAdvancesMonospace([])).toBe(true);
expect(areFontAdvancesMonospace([Number.NaN, Number.NaN])).toBe(true);
});
});
describe("cssFontFamilies", () => {
it("returns null for effectively empty input", () => {
expect(cssFontFamilies("")).toBeNull();
@@ -54,6 +69,34 @@ describe("appearanceFontStack", () => {
});
});
describe("resolveTerminalFontPreference", () => {
it("inherits the code font in simple mode", () => {
expect(
resolveTerminalFontPreference({ advanced: false, code: "Fira Code", terminal: "" }),
).toBe("Fira Code");
expect(
resolveTerminalFontPreference({
advanced: false,
code: "Fira Code",
terminal: "Berkeley Mono",
}),
).toBe("Fira Code");
});
it("keeps code and terminal fonts independent in advanced mode", () => {
expect(resolveTerminalFontPreference({ advanced: true, code: "Fira Code", terminal: "" })).toBe(
"",
);
expect(
resolveTerminalFontPreference({
advanced: true,
code: "Fira Code",
terminal: "Berkeley Mono",
}),
).toBe("Berkeley Mono");
});
});
describe("font size clamping", () => {
it("keeps sizes inside the ranges the UI can absorb", () => {
expect(clampInterfaceFontSize(16)).toBe(16);
+39 -5
View File
@@ -25,6 +25,22 @@ export const DEFAULT_SANS_FONT_STACK =
export const DEFAULT_CODE_FONT_STACK =
'"SF Mono", "SFMono-Regular", Menlo, Consolas, "Liberation Mono", monospace';
export const TYPOGRAPHY_ADVANCED_STORAGE_KEY = "t3code:typography-advanced";
/**
* Simple typography treats the terminal as another monospace surface. In
* Advanced mode an empty terminal preference means the terminal default,
* keeping later code-font changes isolated to code surfaces.
*/
export function resolveTerminalFontPreference(input: {
readonly advanced: boolean;
readonly code: string;
readonly terminal: string;
}): string {
if (input.advanced) return input.terminal;
return input.code;
}
function quoteFontFamilyName(name: string): string {
const bare = name.trim();
if (bare.length === 0) return "";
@@ -165,6 +181,22 @@ export function isFontFamilyAvailable(family: string): boolean {
}
}
const MONOSPACE_PROBE_VARIANTS = ["normal 400", "normal 700", "italic 400", "italic 700"] as const;
const MONOSPACE_PROBE_GLYPHS = ["i", "M", "W", "0", "@", "#", ".", " "] as const;
const MONOSPACE_ADVANCE_TOLERANCE = 0.01;
export function areFontAdvancesMonospace(advances: readonly number[]): boolean {
const reference = advances[0];
if (
reference === undefined ||
reference <= 0 ||
advances.some((advance) => !Number.isFinite(advance) || advance <= 0)
) {
return true;
}
return advances.every((advance) => Math.abs(advance - reference) < MONOSPACE_ADVANCE_TOLERANCE);
}
/**
* Whether a family renders every character on the same advance. Cell-grid
* surfaces (the terminal) require this: a proportional face draws its text
@@ -182,13 +214,15 @@ export function isMonospaceFamily(family: string): boolean {
fontProbeContext = document.createElement("canvas").getContext("2d");
}
if (fontProbeContext === null) return true;
const context = fontProbeContext;
// Fall back to a generic mono so an absent face measures as monospace and
// is left for the normal fallback chain to resolve.
fontProbeContext.font = `32px ${families}, monospace`;
const narrow = fontProbeContext.measureText("i").width;
const wide = fontProbeContext.measureText("M").width;
if (!Number.isFinite(narrow) || !Number.isFinite(wide) || wide === 0) return true;
return Math.abs(wide - narrow) < 0.5;
for (const variant of MONOSPACE_PROBE_VARIANTS) {
context.font = `${variant} 32px ${families}, monospace`;
const advances = MONOSPACE_PROBE_GLYPHS.map((glyph) => context.measureText(glyph).width);
if (!areFontAdvancesMonospace(advances)) return false;
}
return true;
} catch {
return true;
}
@@ -18,6 +18,7 @@ import {
type ThreadId,
} from "@t3tools/contracts";
import { getTerminalLabel } from "@t3tools/shared/terminalLabels";
import * as Schema from "effect/Schema";
import {
type PointerEvent as ReactPointerEvent,
type ReactNode,
@@ -57,6 +58,7 @@ import {
} from "../types";
import { readLocalApi } from "~/localApi";
import { useClientSettings } from "../hooks/useSettings";
import { useLocalStorage } from "../hooks/useLocalStorage";
import { useAttachedTerminalSession } from "../state/terminalSessions";
import { serverEnvironment } from "../state/server";
import { previewEnvironment } from "../state/preview";
@@ -64,6 +66,7 @@ import { terminalEnvironment } from "../state/terminal";
import { openTerminalLinkInPreview } from "./preview/openTerminalLinkInPreview";
import { useAtomCommand } from "../state/use-atom-command";
import { preventTerminalCloseShortcut } from "../lib/terminalCloseShortcut";
import { resolveTerminalFontPreference, TYPOGRAPHY_ADVANCED_STORAGE_KEY } from "../appearanceFonts";
const MIN_DRAWER_HEIGHT = 180;
const MAX_DRAWER_HEIGHT_RATIO = 0.75;
@@ -241,6 +244,7 @@ export function shouldHandleTerminalExit(
}
interface TerminalViewportProps {
advancedTypography: boolean;
threadRef: ScopedThreadRef;
threadId: ThreadId;
terminalId: string;
@@ -264,6 +268,7 @@ interface TerminalLaunchLocation {
}
export function TerminalViewport({
advancedTypography,
threadRef,
threadId,
terminalId,
@@ -312,10 +317,12 @@ export function TerminalViewport({
onAddTerminalContext(selection);
});
const readTerminalLabel = useEffectEvent(() => terminalLabel);
// The terminal inherits the monospace (code) preference unless it has an
// override of its own, so one font choice drives every mono surface.
const terminalFontFamily = useClientSettings(
(settings) => settings.fontFamilyTerminal.trim() || settings.fontFamilyCode,
const terminalFontFamily = useClientSettings((settings) =>
resolveTerminalFontPreference({
advanced: advancedTypography,
code: settings.fontFamilyCode,
terminal: settings.fontFamilyTerminal,
}),
);
const terminalFontSize = useClientSettings((settings) => settings.fontSizeTerminal);
const terminalFontRef = useRef({ family: terminalFontFamily, size: terminalFontSize });
@@ -921,6 +928,11 @@ export default function ThreadTerminalDrawer({
terminalLaunchLocationsById,
}: ThreadTerminalDrawerProps) {
const isPanel = mode === "panel";
const [advancedTypography] = useLocalStorage(
TYPOGRAPHY_ADVANCED_STORAGE_KEY,
false,
Schema.Boolean,
);
const controlledDrawerHeight = clampDrawerHeight(height);
const [drawerHeightState, setDrawerHeightState] = useState(() => ({
threadId,
@@ -1357,6 +1369,7 @@ export default function ThreadTerminalDrawer({
>
<div className="h-full p-1">
<TerminalViewport
advancedTypography={advancedTypography}
threadRef={threadRef}
threadId={threadId}
terminalId={terminalId}
@@ -1384,6 +1397,7 @@ export default function ThreadTerminalDrawer({
) : (
<div className="h-full p-1">
<TerminalViewport
advancedTypography={advancedTypography}
key={resolvedActiveTerminalId}
threadRef={threadRef}
threadId={threadId}
@@ -541,6 +541,10 @@ export const ModelPickerContent = memo(function ModelPickerContent(props: {
}
return mapping.size > 0 ? mapping : EMPTY_MODEL_JUMP_LABELS;
}, [keybindings, modelJumpCommandByKey, modelJumpShortcutContext]);
const modelListExtraData = useMemo(
() => ({ favoritesSet, modelJumpLabelByKey }),
[favoritesSet, modelJumpLabelByKey],
);
useEffect(() => {
const onWindowKeyDown = (event: globalThis.KeyboardEvent) => {
@@ -710,7 +714,7 @@ export const ModelPickerContent = memo(function ModelPickerContent(props: {
<LegendList<string>
ref={modelListRef}
data={filteredItemKeys}
extraData={favoritesSet}
extraData={modelListExtraData}
keyExtractor={(modelKey) => modelKey}
renderItem={({ item: modelKey, index }) => {
if (legacySection?.key === modelKey) {
@@ -120,11 +120,26 @@ export function CodeFontPreview() {
);
}
const TERMINAL_PROMPT = "\x1b[2m$\x1b[0m ";
// A zsh-style prompt: green arrow, cyan project, blue/red git segment,
// yellow dirty marker. It doubles as the echo loop's fresh-line prompt.
const TERMINAL_PROMPT =
"\x1b[1;32m→\x1b[0m \x1b[1;36mt3code\x1b[0m \x1b[1;34mgit:(\x1b[1;31mmain\x1b[1;34m)\x1b[0m \x1b[1;33m✗\x1b[0m ";
// A dev-server startup: brand line, addresses, a test summary, and a READY
// badge. Together the lines cover bold, dim, underline, the six accent
// colors, and a background cell, so a font choice shows every SGR the
// terminal actually renders.
const TERMINAL_PREVIEW_TRANSCRIPT =
`${TERMINAL_PROMPT}npm run dev\r\n` +
"\x1b[32m✓\x1b[0m Ready in 430ms\r\n" +
"\x1b[2mLocal:\x1b[0m \x1b[36mhttp://localhost:3000\x1b[0m\r\n" +
`${TERMINAL_PROMPT}vpr dev\r\n` +
"\r\n" +
" \x1b[1;32mVITE\x1b[0m \x1b[32mv7.1.1\x1b[0m \x1b[2mready in\x1b[0m \x1b[1m1.24s\x1b[0m\r\n" +
"\r\n" +
" \x1b[32m→\x1b[0m \x1b[2mLocal:\x1b[0m \x1b[4;36mhttp://127.0.0.1:5173/\x1b[0m\r\n" +
" \x1b[32m→\x1b[0m \x1b[2mNetwork:\x1b[0m \x1b[4;36mhttp://192.168.1.24:5173/\x1b[0m\r\n" +
"\r\n" +
" \x1b[32m✓ 85 passed\x1b[0m \x1b[33m△ 2 warnings\x1b[0m \x1b[31m✗ 0 failed\x1b[0m\r\n" +
"\r\n" +
" \x1b[42;30m READY \x1b[0m \x1b[2mwatching for changes — press\x1b[0m \x1b[1mq\x1b[0m \x1b[2mto quit\x1b[0m\r\n" +
"\r\n" +
TERMINAL_PROMPT;
/** The surface treats an omitted family or size as "use the built-in default". */
@@ -225,7 +240,7 @@ export function TerminalFontPreview({ family, size }: { family: string; size: nu
return (
<div
ref={mountRef}
className="relative mt-1 mb-2 h-36 overflow-hidden rounded-lg border border-border"
className="relative mt-1 mb-2 h-52 overflow-hidden rounded-lg border border-border"
aria-label="Terminal font preview"
/>
);
@@ -115,6 +115,8 @@ import {
isFontFamilyAvailable,
isMonospaceFamily,
resolveDefaultFamilyLabel,
resolveTerminalFontPreference,
TYPOGRAPHY_ADVANCED_STORAGE_KEY,
} from "../../appearanceFonts";
import { CodeFontPreview, PromptFontPreview, TerminalFontPreview } from "./SettingsFontPreviews";
import { discoverInstalledFonts, FontFamilyPicker, useFontEnumeration } from "./FontFamilyPicker";
@@ -1151,10 +1153,8 @@ function useFontDefaultFamilies() {
return {
sans: defaults.sans,
code: defaults.code,
// The composer inherits whatever the interface preference resolves to;
// the terminal inherits the monospace preference the same way.
// The composer inherits whatever the interface preference resolves to.
interfaceFamily: settings.fontFamilySans.trim() || defaults.sans,
monoFamily: settings.fontFamilyCode.trim() || defaults.code,
};
}
@@ -1244,8 +1244,8 @@ function TerminalFontRow() {
return (
<FontFamilySettingsRow
{...searchableSetting("terminal-font")}
description="Terminal output. Follows the monospace font unless set."
defaultFamily={defaults.monoFamily}
description="Terminal output, independent from code blocks and diffs."
defaultFamily={defaults.code}
value={settings.fontFamilyTerminal}
onValueChange={(fontFamilyTerminal) => updateSettings({ fontFamilyTerminal })}
requireMonospace
@@ -1258,7 +1258,11 @@ function TerminalFontRow() {
}}
preview={
<TerminalFontPreview
family={settings.fontFamilyTerminal.trim() || settings.fontFamilyCode}
family={resolveTerminalFontPreference({
advanced: true,
code: settings.fontFamilyCode,
terminal: settings.fontFamilyTerminal,
})}
size={settings.fontSizeTerminal}
/>
}
@@ -1350,7 +1354,11 @@ function SimpleFontRows() {
<>
<CodeFontPreview />
<TerminalFontPreview
family={settings.fontFamilyTerminal.trim() || settings.fontFamilyCode}
family={resolveTerminalFontPreference({
advanced: false,
code: settings.fontFamilyCode,
terminal: settings.fontFamilyTerminal,
})}
size={settings.fontSizeTerminal}
/>
</>
@@ -1370,8 +1378,6 @@ const ADVANCED_TYPOGRAPHY_TARGET_IDS: ReadonlySet<string> = new Set([
: []),
]);
const TYPOGRAPHY_ADVANCED_KEY = "t3code:typography-advanced";
/**
* The two-font view by default - one sans, one monospace, each cascading to
* every surface it reaches - with an Advanced switch in the section header
@@ -1380,7 +1386,11 @@ const TYPOGRAPHY_ADVANCED_KEY = "t3code:typography-advanced";
* target exists to scroll to.
*/
function TypographySection() {
const [advanced, setAdvanced] = useLocalStorage(TYPOGRAPHY_ADVANCED_KEY, false, Schema.Boolean);
const [advanced, setAdvanced] = useLocalStorage(
TYPOGRAPHY_ADVANCED_STORAGE_KEY,
false,
Schema.Boolean,
);
const searchTargetId = useSettingsSearchTargetId();
// Flip Advanced on once per search jump so the hidden target can mount and
// scroll; tracking the handled id lets the user turn it back off without
+23 -20
View File
@@ -1,4 +1,4 @@
import { describe, expect, it } from "vite-plus/test";
import { describe, expect, it, vi } from "vite-plus/test";
import type { GhosttyCell, GhosttyRow } from "./core";
import {
@@ -11,6 +11,7 @@ import {
isTerminalCopyShortcut,
isTerminalLinkPointerGesture,
isTerminalPasteShortcut,
loadTerminalFontFamily,
shouldBlinkTerminalCursor,
shouldReportTerminalMouse,
shouldShowTerminalLinkHover,
@@ -22,7 +23,6 @@ import {
terminalLinkAtPositionWithRange,
terminalContentOriginY,
terminalFontFamily,
fittedTerminalFontSize,
terminalFontSize,
terminalWheelArrowData,
terminalWheelDeltaRows,
@@ -295,6 +295,27 @@ describe("application mouse reporting", () => {
});
describe("terminal font resolution", () => {
it("validates the requested face after its styles load", async () => {
let loaded = false;
const load = vi.fn(async () => {
loaded = true;
return [];
});
const resolve = vi.fn(() => {
expect(loaded).toBe(true);
return DEFAULT_TERMINAL_FONT_FAMILY;
});
await expect(
loadTerminalFontFamily("Proportional Test", 12, {
load,
resolve,
}),
).resolves.toBe(DEFAULT_TERMINAL_FONT_FAMILY);
expect(load).toHaveBeenCalledTimes(4);
expect(resolve).toHaveBeenCalledWith("Proportional Test");
});
it("keeps the glyph fallbacks behind a custom text face", () => {
expect(terminalFontFamily()).toBe(DEFAULT_TERMINAL_FONT_FAMILY);
expect(terminalFontFamily(" ")).toBe(DEFAULT_TERMINAL_FONT_FAMILY);
@@ -321,24 +342,6 @@ describe("terminal font resolution", () => {
expect(terminalFontFamily(" , ")).toBe(DEFAULT_TERMINAL_FONT_FAMILY);
});
it("slides the rendered size down until a full-width grid fits the canvas", () => {
// SF Mono-like advance: 0.6em per cell.
const cellWidthAt = (size: number) => size * 0.6;
// A wide drawer keeps the preference untouched.
expect(fittedTerminalFontSize(cellWidthAt, 20, 1140)).toBe(20);
// A split pane at the same preference shrinks until 80 columns fit.
const fitted = fittedTerminalFontSize(cellWidthAt, 20, 570);
expect(fitted).toBeLessThan(20);
expect(Math.floor((570 - 8) / cellWidthAt(fitted))).toBeGreaterThanOrEqual(80);
// A tiny pane stops at the legibility floor instead of vanishing.
expect(fittedTerminalFontSize(cellWidthAt, 20, 220)).toBe(8);
// A preference below the floor is honored as-is.
expect(fittedTerminalFontSize(cellWidthAt, 6, 220)).toBe(6);
// Unmeasured layouts leave the preference alone.
expect(fittedTerminalFontSize(cellWidthAt, 14, 0)).toBe(14);
expect(fittedTerminalFontSize(() => 0, 14, 600)).toBe(14);
});
it("clamps requested font sizes to the supported range", () => {
expect(terminalFontSize()).toBe(DEFAULT_TERMINAL_FONT_SIZE);
expect(terminalFontSize(Number.NaN)).toBe(DEFAULT_TERMINAL_FONT_SIZE);
+63 -62
View File
@@ -36,6 +36,13 @@ const CONTENT_PADDING = 4;
const MIN_SCROLLBAR_THUMB_HEIGHT = 18;
/** Half a blink cycle: the visible and hidden phases are equally long. */
const CURSOR_BLINK_INTERVAL_MS = 500;
const TERMINAL_FONT_LOAD_TEXT = "iMW0@# .";
const TERMINAL_FONT_LOAD_VARIANTS = [
"normal 400",
"normal 700",
"italic 400",
"italic 700",
] as const;
/** Requested terminal font; omitted fields fall back to the defaults. */
export interface GhosttyTerminalFont {
@@ -78,6 +85,13 @@ function quoteTerminalFontFamilies(list: string): string {
.join(", ");
}
function uncheckedTerminalFontFamily(family?: string): string {
const custom = family === undefined ? "" : quoteTerminalFontFamilies(family);
return custom.length === 0
? DEFAULT_TERMINAL_FONT_FAMILY
: `${custom}, ${TERMINAL_GLYPH_FALLBACKS}`;
}
export function terminalFontFamily(family?: string): string {
// Quote non-ident names ("3270 Nerd Font", "M+ 1m"): an unquoted one makes
// the whole canvas font string invalid and the assignment silently no-ops.
@@ -88,43 +102,31 @@ export function terminalFontFamily(family?: string): string {
// it here rather than render a ragged grid with a stranded cursor.
if (!isMonospaceFamily(custom)) return DEFAULT_TERMINAL_FONT_FAMILY;
// A custom face keeps the glyph fallbacks so prompt symbols stay covered.
return `${custom}, ${TERMINAL_GLYPH_FALLBACKS}`;
return uncheckedTerminalFontFamily(custom);
}
/**
* Grids narrower than a classic 80-column terminal wrap command output hard,
* so the rendered font size follows the canvas width: the preference is the
* ceiling, and the size slides down (to a legibility floor) until a full-width
* grid fits. A widening pane slides it back up toward the preference.
*/
const MIN_TERMINAL_FIT_COLUMNS = 80;
const MIN_TERMINAL_FIT_FONT_SIZE = 8;
export function fittedTerminalFontSize(
cellWidthAt: (size: number) => number,
requested: number,
mountWidth: number,
): number {
const available = mountWidth - CONTENT_PADDING * 2;
if (available <= 0) return requested;
const floor = Math.min(requested, MIN_TERMINAL_FIT_FONT_SIZE);
const fits = (cellWidth: number) =>
cellWidth > 0 && Math.floor(available / cellWidth) >= MIN_TERMINAL_FIT_COLUMNS;
let cellWidth = cellWidthAt(requested);
if (cellWidth <= 0 || fits(cellWidth)) return requested;
// The advance scales linearly with size for monospace faces: jump close to
// the fitting size, then settle the remaining rounding one step at a time.
const targetCellWidth = available / MIN_TERMINAL_FIT_COLUMNS;
let size = Math.max(
floor,
Math.min(requested, Math.floor((requested * targetCellWidth) / cellWidth)),
);
while (size > floor) {
cellWidth = cellWidthAt(size);
if (cellWidth <= 0 || fits(cellWidth)) break;
size -= 1;
/** Load every style the renderer can request, then validate the actual face. */
export async function loadTerminalFontFamily(
family: string | undefined,
size: number,
environment?: {
readonly load: (font: string, text: string) => Promise<unknown>;
readonly resolve: (family: string | undefined) => string;
},
): Promise<string> {
const candidate = uncheckedTerminalFontFamily(family);
const load =
environment?.load ?? ((font: string, text: string) => document.fonts.load(font, text));
try {
await Promise.all(
TERMINAL_FONT_LOAD_VARIANTS.map((variant) =>
load(`${variant} ${size}px ${candidate}`, TERMINAL_FONT_LOAD_TEXT),
),
);
} catch {
// The fixed-width fallback stack remains available if a face cannot load.
}
return size;
return (environment?.resolve ?? terminalFontFamily)(family);
}
export function terminalFontSize(size?: number): number {
@@ -479,9 +481,10 @@ export class GhosttyTerminalSurface {
private readonly options: GhosttyTerminalSurfaceOptions;
private metrics: GhosttyCellMetrics;
private fontFamily: string;
private requestedFontFamily: string | undefined;
private fontSize: number;
private requestedFontSize: number;
private fontEpoch = 0;
private pendingFontEpoch: number | null = null;
private readonly resizeObserver: ResizeObserver;
private readonly scrollbarThumb: HTMLDivElement;
private snapshot: GhosttySnapshot | null = null;
@@ -545,6 +548,7 @@ export class GhosttyTerminalSurface {
context: CanvasRenderingContext2D,
core: GhosttyTerminalCore,
metrics: GhosttyCellMetrics,
fontFamily: string,
options: GhosttyTerminalSurfaceOptions,
) {
this.mount = mount;
@@ -557,9 +561,9 @@ export class GhosttyTerminalSurface {
this.metrics = metrics;
this.options = options;
this.theme = options.theme;
this.fontFamily = terminalFontFamily(options.font?.family);
this.fontFamily = fontFamily;
this.requestedFontFamily = options.font?.family;
this.fontSize = terminalFontSize(options.font?.size);
this.requestedFontSize = this.fontSize;
this.resizeObserver = new ResizeObserver(() => this.fit());
this.installEvents();
this.watchDevicePixelRatio();
@@ -600,16 +604,20 @@ export class GhosttyTerminalSurface {
const context = canvas.getContext("2d", { alpha: false });
if (!context) throw new Error("Canvas 2D is unavailable");
const fontFamily = terminalFontFamily(options.font?.family);
// An opaque canvas backing store initializes to solid black, and the font
// and WASM loads below leave it on screen for the whole setup window; paint
// the theme background first so the mount never flashes a black box.
context.fillStyle = `rgb(${options.theme.background.r}, ${options.theme.background.g}, ${options.theme.background.b})`;
context.fillRect(0, 0, canvas.width, canvas.height);
const fontSize = terminalFontSize(options.font?.size);
try {
// Cell metrics must come from the faces that will render; measuring before
// the bundled webfonts load would size the grid from a fallback font.
await ensureTerminalSymbolsFont();
await document.fonts.load(`${fontSize}px ${fontFamily}`);
} catch {
// Metrics fall back to whichever faces are already available.
}
const fontFamily = await loadTerminalFontFamily(options.font?.family, fontSize);
const metrics = measureGhosttyCell(context, fontSize, fontFamily);
const grid = terminalGridSize(mount.clientWidth, mount.clientHeight, metrics, CONTENT_PADDING);
const core = await GhosttyTerminalCore.create(
@@ -629,6 +637,7 @@ export class GhosttyTerminalSurface {
context,
core,
metrics,
fontFamily,
options,
);
surface.fit();
@@ -667,19 +676,16 @@ export class GhosttyTerminalSurface {
async setFont(font: GhosttyTerminalFont): Promise<void> {
if (this.disposed) return;
const fontFamily = terminalFontFamily(font.family);
const fontSize = terminalFontSize(font.size);
// The fields only change together with their metrics after the load, and
// the epoch lets the newest overlapping call win regardless of load order.
const epoch = ++this.fontEpoch;
try {
await document.fonts.load(`${fontSize}px ${fontFamily}`);
} catch {
// Metrics fall back to whichever faces are already available.
}
this.pendingFontEpoch = epoch;
const fontFamily = await loadTerminalFontFamily(font.family, fontSize);
if (this.disposed || epoch !== this.fontEpoch) return;
this.pendingFontEpoch = null;
this.fontFamily = fontFamily;
this.requestedFontSize = fontSize;
this.requestedFontFamily = font.family;
this.fontSize = fontSize;
this.applyFontMetrics();
}
@@ -706,6 +712,17 @@ export class GhosttyTerminalSurface {
private readonly onFontsLoaded = () => {
if (this.disposed) return;
// The explicit load validates every style and applies the newest request.
// Its own loading events must not revalidate the previously applied face.
if (this.pendingFontEpoch !== null) return;
// A face may become available after an earlier fallback measurement. Run
// the fixed-width guard again before using its newly loaded metrics.
const fontFamily = terminalFontFamily(this.requestedFontFamily);
if (fontFamily !== this.fontFamily) {
this.fontFamily = fontFamily;
this.applyFontMetrics();
return;
}
// A face that finished loading after the initial measurement changes glyph
// advances; re-measure and refit so the grid matches what actually renders.
const metrics = measureGhosttyCell(this.context, this.fontSize, this.fontFamily);
@@ -724,22 +741,6 @@ export class GhosttyTerminalSurface {
const width = this.mount.clientWidth;
const height = this.mount.clientHeight;
if (width <= 0 || height <= 0) return false;
const fitted = fittedTerminalFontSize(
(size) => measureGhosttyCell(this.context, size, this.fontFamily).width,
this.requestedFontSize,
width,
);
if (fitted !== this.fontSize) {
this.fontSize = fitted;
this.metrics = measureGhosttyCell(this.context, this.fontSize, this.fontFamily);
// The grid-change branch below resizes the core, but only when the
// column count moved; the cell geometry always did, so sync it here.
this.core.resize(this.cols, this.rows, this.metrics.width, this.metrics.height);
this.inputLeft = -1;
this.inputTop = -1;
this.forceFullRender = true;
this.scrollbarDirty = true;
}
const ratio = window.devicePixelRatio || 1;
const pixelWidth = Math.max(1, Math.round(width * ratio));
const pixelHeight = Math.max(1, Math.round(height * ratio));
@@ -7,12 +7,16 @@ import {
} from "@t3tools/contracts";
import { describe, expect, it } from "@effect/vitest";
import * as Cause from "effect/Cause";
import * as Duration from "effect/Duration";
import * as Effect from "effect/Effect";
import * as Exit from "effect/Exit";
import * as Fiber from "effect/Fiber";
import * as Option from "effect/Option";
import * as Queue from "effect/Queue";
import * as Ref from "effect/Ref";
import * as Stream from "effect/Stream";
import * as SubscriptionRef from "effect/SubscriptionRef";
import * as TestClock from "effect/testing/TestClock";
import { RpcClientError } from "effect/unstable/rpc";
import * as Socket from "effect/unstable/socket/Socket";
@@ -30,6 +34,7 @@ import {
makeEnvironmentServerConfigState,
isLegacyUpdateHandoffLoss,
matchesServerUpdateReadyEvent,
nudgeReconnectDuringUpdateRestart,
projectServerWelcome,
resolveServerConfigValue,
resolveServerUpdateProgressResult,
@@ -71,6 +76,56 @@ function session(client: WsRpcProtocolClient): RpcSession {
};
}
describe("update restart reconnect nudges", () => {
it.effect("retries once per backoff entry instead of only the first", () =>
Effect.gen(function* () {
const retries = yield* Ref.make(0);
const states = [
{ phase: "backoff" },
{ phase: "connecting" },
{ phase: "backoff" },
{ phase: "backoff" },
];
yield* nudgeReconnectDuringUpdateRestart({
stateChanges: Stream.fromIterable(states),
retryNow: Ref.update(retries, (count) => count + 1),
interval: Duration.zero,
});
// Three backoff entries, three nudges. The old one-shot behavior fired
// once and then let the supervisor's ladder stretch to 16-second gaps.
expect(yield* Ref.get(retries)).toBe(3);
}),
);
it.effect("paces nudges so a fast-failing connection cannot spin", () =>
Effect.gen(function* () {
const retries = yield* Ref.make(0);
const fiber = yield* Effect.forkChild(
nudgeReconnectDuringUpdateRestart({
stateChanges: Stream.fromIterable([{ phase: "backoff" }, { phase: "backoff" }]),
retryNow: Ref.update(retries, (count) => count + 1),
}),
{ startImmediately: true },
);
// Each nudge waits out the interval first, so nothing fires immediately.
yield* TestClock.adjust(Duration.millis(999));
expect(yield* Ref.get(retries)).toBe(0);
yield* TestClock.adjust(Duration.millis(1));
expect(yield* Ref.get(retries)).toBe(1);
yield* TestClock.adjust(Duration.seconds(1));
expect(yield* Ref.get(retries)).toBe(2);
yield* Fiber.join(fiber);
}).pipe(Effect.provide(TestClock.layer())),
);
});
describe("server state projection", () => {
it("only treats a legacy transport interruption as an unacknowledged handoff", () => {
expect(isLegacyUpdateHandoffLoss(Cause.interrupt(1))).toBe(true);
+36 -12
View File
@@ -149,6 +149,35 @@ export function validateServerUpdateReadyEvent(
);
}
/**
* Keeps reconnect attempts ~1s apart for the whole update restart.
*
* A restart takes the server down for ~15 seconds, but the supervisor's normal
* backoff ladder (1/2/4/8/16s) assumes an unexpected failure and lands attempts
* at ~3, 5, 9, 17 and 33 seconds — so a 15-second restart is observed as a
* 33-second "Resuming". Nudging on every backoff entry (not just the first)
* holds the retry cadence flat until the server answers again. The sleep before
* each nudge is the pacer: a connection that fails instantly re-enters backoff
* immediately and would otherwise spin a tight retry loop.
*
* Callers fork this as a child of the update command so it is interrupted as
* soon as the update settles, whether it succeeds, fails, or times out.
*/
export function nudgeReconnectDuringUpdateRestart(input: {
readonly stateChanges: Stream.Stream<{ readonly phase: string }, unknown>;
readonly retryNow: Effect.Effect<void>;
readonly interval?: Duration.Duration;
}): Effect.Effect<void> {
return input.stateChanges.pipe(
Stream.filter((state) => state.phase === "backoff"),
Stream.runForEach(() =>
Effect.sleep(input.interval ?? Duration.seconds(1)).pipe(Effect.andThen(input.retryNow)),
),
Effect.timeoutOption(SERVER_UPDATE_RESUME_TIMEOUT),
Effect.ignore,
);
}
export function serverUpdateStateForProgressEvent(
fromVersion: string,
targetVersion: string,
@@ -589,18 +618,13 @@ export function createServerEnvironmentAtoms<R, E>(
}),
);
// The update restart is intentional. As soon as the supervisor sees
// that first failed connection, discard any prior backoff debt and
// retry immediately instead of carrying an old 16-second delay.
yield* environmentRegistry.stateChanges(target.environmentId).pipe(
Stream.filter((state) => state.phase === "backoff"),
Stream.take(1),
Stream.runDrain,
Effect.andThen(environmentRegistry.retryNow(target.environmentId)),
Effect.timeoutOption(Duration.seconds(30)),
Effect.ignore,
Effect.forkChild,
);
// The update restart is intentional and the server stays unreachable
// for the whole restart, so hold the retry cadence flat instead of
// letting the supervisor climb its backoff ladder.
yield* nudgeReconnectDuringUpdateRestart({
stateChanges: environmentRegistry.stateChanges(target.environmentId),
retryNow: environmentRegistry.retryNow(target.environmentId),
}).pipe(Effect.forkChild);
const resumed = yield* environmentRegistry
.followStream(target.environmentId, subscribe(WS_METHODS.subscribeServerLifecycle, {}))
+51 -7
View File
@@ -44,17 +44,27 @@ const PROJECT_SCRIPTS = JSON.stringify([
},
]);
const SHOWCASE_TERMINAL_PROMPT =
"\u001b[1;32m→\u001b[0m \u001b[1;36mt3code\u001b[0m \u001b[1;34mgit:(\u001b[1;31mfeat/remote-command-center\u001b[1;34m)\u001b[0m \u001b[1;33m✗\u001b[0m ";
// A dev-server startup mirroring the web settings' terminal font preview:
// zsh-style prompt, brand line, addresses, the thread's 612-test summary,
// and a READY badge, so the scene exercises bold, dim, underline, the six
// accent colors, and a background cell.
export const SHOWCASE_TERMINAL_BUFFER = [
"\u001b[38;5;75m~/Code/t3code\u001b[0m \u001b[38;5;212mfeat/remote-command-center\u001b[0m",
"$ vp test run --changed",
`${SHOWCASE_TERMINAL_PROMPT}vpr dev`,
"",
" \u001b[38;5;117mt3code-mobile\u001b[0m 184 passed",
" \u001b[38;5;213mclient-runtime\u001b[0m 263 passed",
" \u001b[38;5;221mserver\u001b[0m 165 passed",
" \u001b[1;32mVITE\u001b[0m \u001b[32mv7.1.1\u001b[0m \u001b[2mready in\u001b[0m \u001b[1m1.24s\u001b[0m",
"",
"\u001b[32m✨ 612 tests passed\u001b[0m · 3 environments online",
" \u001b[32m→\u001b[0m \u001b[2mLocal:\u001b[0m \u001b[4;36mhttp://127.0.0.1:5173/\u001b[0m",
" \u001b[32m→\u001b[0m \u001b[2mNetwork:\u001b[0m \u001b[4;36mhttp://192.168.1.24:5173/\u001b[0m",
" \u001b[32m→\u001b[0m \u001b[2mProject:\u001b[0m \u001b[1mt3code\u001b[0m \u001b[2m— ~/Code/t3code\u001b[0m",
"",
"\u001b[38;5;75m~/Code/t3code\u001b[0m \u001b[38;5;212mfeat/remote-command-center\u001b[0m $ ",
" \u001b[32m✓ 612 passed\u001b[0m \u001b[33m△ 2 warnings\u001b[0m \u001b[31m✗ 0 failed\u001b[0m",
"",
" \u001b[42;30m READY \u001b[0m \u001b[2mwatching for changes — press\u001b[0m \u001b[1mq\u001b[0m \u001b[2mto quit\u001b[0m",
"",
SHOWCASE_TERMINAL_PROMPT,
].join("\r\n");
const BASE_ENVIRONMENT_PRESENCE = `export function environmentLabel(count: number): string {
@@ -561,6 +571,40 @@ function seedDatabase(
3,
minutesBefore(now, 4),
);
database
.prepare(
`INSERT INTO projection_thread_activities (
activity_id, thread_id, turn_id, tone, kind, summary, payload_json, sequence, created_at
) VALUES (?, ?, ?, 'info', 'user-input.requested', ?, ?, ?, ?)`,
)
.run(
"choose-remote-environment",
SHOWCASE_THREAD_ID,
turnId,
"User input requested",
JSON.stringify({
requestId: "showcase-user-input",
questions: [
{
id: "environment",
header: "Environment",
question: "Which environment should receive the first remote handoff?",
options: [
{
label: "Moonbase",
description: "Use the primary T3 Code workspace.",
},
{
label: "Suspense Station",
description: "Use the React workspace.",
},
],
},
],
}),
4,
minutesBefore(now, 2),
);
for (const [index, projector] of PROJECTOR_NAMES.entries()) {
database