Compare commits

..
93 changed files with 3931 additions and 1849 deletions

No files matched your search

+12 -6
View File
@@ -747,9 +747,15 @@ jobs:
if: ${{ !failure() && !cancelled() && needs.preflight.result == 'success' && needs.build.result == 'success' && needs.publish_cli.result == 'success' }}
runs-on: blacksmith-8vcpu-ubuntu-2404
timeout-minutes: 10
permissions:
contents: write
steps:
- id: app_token
name: Mint release app token
uses: actions/create-github-app-token@v2
with:
app-id: ${{ secrets.RELEASE_APP_ID }}
private-key: ${{ secrets.RELEASE_APP_PRIVATE_KEY }}
owner: ${{ github.repository_owner }}
- name: Checkout
uses: actions/checkout@v6
with:
@@ -817,7 +823,7 @@ jobs:
- name: Publish release
if: needs.preflight.outputs.previous_tag != ''
uses: softprops/action-gh-release@v3
uses: softprops/action-gh-release@v2
with:
tag_name: ${{ needs.preflight.outputs.tag }}
target_commitish: ${{ needs.preflight.outputs.ref }}
@@ -834,11 +840,11 @@ jobs:
release-assets/*.blockmap
release-assets/*.yml
fail_on_unmatched_files: true
token: ${{ github.token }}
token: ${{ steps.app_token.outputs.token }}
- name: Publish first release
if: needs.preflight.outputs.previous_tag == ''
uses: softprops/action-gh-release@v3
uses: softprops/action-gh-release@v2
with:
tag_name: ${{ needs.preflight.outputs.tag }}
target_commitish: ${{ needs.preflight.outputs.ref }}
@@ -854,7 +860,7 @@ jobs:
release-assets/*.blockmap
release-assets/*.yml
fail_on_unmatched_files: true
token: ${{ github.token }}
token: ${{ steps.app_token.outputs.token }}
deploy_web:
name: Deploy hosted web app
-8
View File
@@ -47,7 +47,6 @@ import { SettingsClientStorageRouteScreen } from "./features/settings/SettingsCl
import { SettingsAuthRouteScreen } from "./features/settings/SettingsAuthRouteScreen";
import { SettingsEnvironmentsRouteScreen } from "./features/settings/SettingsEnvironmentsRouteScreen";
import { SettingsLegalRouteScreen } from "./features/settings/SettingsLegalRouteScreen";
import { SettingsProjectGroupingRouteScreen } from "./features/settings/SettingsProjectGroupingRouteScreen";
import { SettingsRouteScreen } from "./features/settings/SettingsRouteScreen";
import { ShowcaseCaptureCoordinator } from "./features/showcase/ShowcaseCaptureCoordinator";
import {
@@ -176,13 +175,6 @@ const SettingsSheetStack = createNativeStackNavigator({
title: "Appearance",
},
}),
SettingsProjectGrouping: createNativeStackScreen({
screen: SettingsProjectGroupingRouteScreen,
linking: "project-grouping",
options: {
title: "Project Grouping",
},
}),
SettingsClientStorage: createNativeStackScreen({
screen: SettingsClientStorageRouteScreen,
linking: "client-storage",
@@ -70,7 +70,7 @@ export function AndroidScreenHeader(props: {
accessibilityRole="button"
hitSlop={8}
onPress={props.onBack}
className="-mr-2 size-11 items-center justify-center"
className="size-11 items-center justify-center"
>
<SymbolView
name="chevron.left"
+1 -8
View File
@@ -694,11 +694,7 @@ export function HomeScreen(props: HomeScreenProps) {
);
const renderV2Item = useCallback(
({ item, index }: { readonly item: ThreadListV2ListItem; readonly index: number }) => {
const nextItem = threadListV2Items[index + 1];
const showTrailingDivider =
nextItem?.type === "v2-thread" ||
(nextItem?.type === "v2-pending" && !nextItem.showPendingDivider);
({ item }: { readonly item: ThreadListV2ListItem }) => {
if (item.type === "v2-pending") {
const pendingScopeKey = scopedProjectKey(
item.pendingTask.message.environmentId,
@@ -716,7 +712,6 @@ export function HomeScreen(props: HomeScreenProps) {
: null
}
showPendingDivider={item.showPendingDivider}
showTrailingDivider={showTrailingDivider}
onSelectPendingTask={props.onSelectPendingTask}
onDeletePendingTask={props.onDeletePendingTask}
/>
@@ -749,7 +744,6 @@ export function HomeScreen(props: HomeScreenProps) {
pinned={item.item.pinned}
snoozePresetMinute={nowMinute}
snoozeWakeLabelText={item.snoozeWakeLabelText}
showTrailingDivider={showTrailingDivider}
project={
projectByKey.get(scopedProjectKey(thread.environmentId, thread.projectId)) ?? null
}
@@ -820,7 +814,6 @@ export function HomeScreen(props: HomeScreenProps) {
serverConfigs,
settlementEnvironmentIds,
snoozeEnvironmentIds,
threadListV2Items,
threadSearchMatchByKey,
toggleSettledShelf,
toggleSnoozedShelf,
@@ -31,6 +31,12 @@ export interface ResolvedHomeListOptions extends HomeListOptions {
readonly projectGroupingMode: SidebarProjectGroupingMode;
}
export function resolveProjectGroupingMode(
projectGroupingEnabled: boolean | undefined,
): SidebarProjectGroupingMode {
return projectGroupingEnabled === false ? "separate" : "repository";
}
export const PROJECT_SORT_OPTIONS: ReadonlyArray<{
readonly value: HomeProjectSortOrder;
readonly label: string;
@@ -70,9 +76,7 @@ const HomeListOptionsContext = createContext<HomeListOptionsContextValue | null>
export function HomeListOptionsProvider({
children,
projectGroupingMode,
}: PropsWithChildren<{
readonly projectGroupingMode: SidebarProjectGroupingMode;
}>) {
}: PropsWithChildren<{ readonly projectGroupingMode: SidebarProjectGroupingMode }>) {
const [options, setOptions] = useState<HomeListOptions>(defaultHomeListOptions);
const value = useMemo(
() => ({ options, setOptions, projectGroupingMode }),
@@ -375,7 +375,7 @@ describe("buildHomeThreadGroups", () => {
).toHaveLength(2);
});
it("uses the physical project title for a singleton scope", () => {
it("uses the repository label for a singleton repository scope", () => {
const project = makeProject({
environmentId: EnvironmentId.make("environment-1"),
id: ProjectId.make("project-1"),
@@ -408,8 +408,8 @@ describe("buildHomeThreadGroups", () => {
],
);
expect(scopes[0]?.title).toBe("local-worktree-name");
expect(groups[0]?.title).toBe("local-worktree-name");
expect(scopes[0]?.title).toBe("codething-mvp");
expect(groups[0]?.title).toBe("codething-mvp");
});
it("sorts the newest thread first regardless of snapshot order", () => {
@@ -565,16 +565,10 @@ describe("buildHomeThreadGroups", () => {
);
expect(buildGroups(projects, threads, { projectGroupingMode: "repository" })).toHaveLength(1);
expect(
buildGroups(projects, threads, { projectGroupingMode: "repository_path" }).map(
(group) => group.title,
),
).toEqual(["Mobile", "Web"]);
expect(
buildGroups(projects, threads, { projectGroupingMode: "separate" }).map(
(group) => group.title,
),
).toEqual(["Mobile", "Web"]);
expect(buildGroups(projects, threads, { projectGroupingMode: "repository_path" })).toHaveLength(
2,
);
expect(buildGroups(projects, threads, { projectGroupingMode: "separate" })).toHaveLength(2);
});
it("default view shows only threads from the last 5 days", () => {
+63 -18
View File
@@ -1,5 +1,5 @@
import {
buildProjectGroups,
deriveLogicalProjectKey,
derivePhysicalProjectKey,
deriveProjectGroupLabel,
} from "@t3tools/client-runtime/state/project-grouping";
@@ -37,6 +37,10 @@ export interface HomeProjectScope {
readonly projectRefs: ReadonlyArray<ScopedProjectRef>;
}
function getProjectFreshnessTimestamp(project: EnvironmentProject): number {
return toSortableTimestamp(project.updatedAt) ?? toSortableTimestamp(project.createdAt) ?? 0;
}
function getProjectSortTimestamp(
project: EnvironmentProject,
sortOrder: HomeProjectSortOrder,
@@ -56,19 +60,64 @@ export function buildHomeProjectScopes(input: {
const projects = input.projects.filter(
(project) => input.environmentId === null || project.environmentId === input.environmentId,
);
return buildProjectGroups({
projects,
settings: {
sidebarProjectGroupingMode: input.projectGroupingMode,
sidebarProjectGroupingOverrides: {},
},
}).map((group) => {
const projectsByPhysicalKey = new Map<string, EnvironmentProject[]>();
for (const project of projects) {
const physicalKey = derivePhysicalProjectKey(project);
const existing = projectsByPhysicalKey.get(physicalKey);
if (existing) existing.push(project);
else projectsByPhysicalKey.set(physicalKey, [project]);
}
const winnersByPhysicalKey = new Map<
string,
{ readonly key: string; readonly project: EnvironmentProject }
>();
for (const [physicalKey, members] of projectsByPhysicalKey) {
const project = members.reduce((winner, candidate) => {
const freshnessDelta =
getProjectFreshnessTimestamp(candidate) - getProjectFreshnessTimestamp(winner);
return freshnessDelta > 0 || (freshnessDelta === 0 && candidate.id > winner.id)
? candidate
: winner;
});
const identitySource = members.find((member) => member.repositoryIdentity !== null) ?? project;
winnersByPhysicalKey.set(physicalKey, {
key: deriveLogicalProjectKey(identitySource, { groupingMode: input.projectGroupingMode }),
project,
});
}
const groups = new Map<string, EnvironmentProject[]>();
for (const { key, project } of winnersByPhysicalKey.values()) {
const existing = groups.get(key);
if (existing) existing.push(project);
else groups.set(key, [project]);
}
const projectRefsByGroup = new Map<string, ScopedProjectRef[]>();
const seenProjectRefs = new Set<string>();
for (const project of projects) {
const refKey = scopedProjectKey(project.environmentId, project.id);
if (seenProjectRefs.has(refKey)) continue;
seenProjectRefs.add(refKey);
const key =
winnersByPhysicalKey.get(derivePhysicalProjectKey(project))?.key ??
deriveLogicalProjectKey(project, { groupingMode: input.projectGroupingMode });
const refs = projectRefsByGroup.get(key);
const projectRef = { environmentId: project.environmentId, projectId: project.id };
if (refs) refs.push(projectRef);
else projectRefsByGroup.set(key, [projectRef]);
}
return Array.from(groups, ([key, projects]) => {
const representative = projects[0]!;
return {
key: group.key,
title: group.label,
representative: group.representative,
projects: group.members.map((member) => member.project),
projectRefs: group.memberProjectRefs,
key,
title: deriveProjectGroupLabel({ representative, members: projects }),
representative,
projects,
projectRefs: projectRefsByGroup.get(key) ?? [],
};
});
}
@@ -215,11 +264,9 @@ export function buildHomeThreadGroups(input: {
}): ReadonlyArray<HomeThreadGroup> {
const now = input.now ?? Date.now();
const groups = new Map<string, MutableHomeThreadGroup>();
const groupTitleByKey = new Map<string, string>();
const groupKeyByProjectKey = new Map<string, string>();
for (const scope of buildHomeProjectScopes(input)) {
groupTitleByKey.set(scope.key, scope.title);
groups.set(scope.key, {
key: scope.key,
projects: [...scope.projects],
@@ -298,9 +345,7 @@ export function buildHomeThreadGroups(input: {
continue;
}
const title =
groupTitleByKey.get(group.key) ??
deriveProjectGroupLabel({ representative, members: group.projects });
const title = deriveProjectGroupLabel({ representative, members: group.projects });
const groupMatches =
query.length === 0 ||
title.toLocaleLowerCase().includes(query) ||
@@ -37,15 +37,11 @@ import {
import { resolveThreadSelectionNavigationAction } from "../../lib/adaptive-navigation";
import { scopedThreadKey } from "../../lib/scopedEntities";
import { mobilePreferencesAtom } from "../../state/preferences";
import {
DEFAULT_MOBILE_PROJECT_GROUPING_SETTINGS,
resolveMobileProjectGroupingSettings,
} from "../../state/project-grouping";
import {
parseActiveThreadPath,
useHardwareKeyboardCommand,
} from "../keyboard/hardwareKeyboardCommands";
import { HomeListOptionsProvider } from "../home/home-list-options";
import { HomeListOptionsProvider, resolveProjectGroupingMode } from "../home/home-list-options";
import { ThreadNavigationSidebar } from "../threads/ThreadNavigationSidebar";
import { WORKSPACE_PANE_TIMING } from "./workspace-pane-animation";
import { WorkspaceInspectorPane } from "./workspace-inspector-pane";
@@ -194,17 +190,15 @@ export function AdaptiveWorkspaceLayout(props: {
const preferencesResult = useAtomValue(mobilePreferencesAtom);
if (!AsyncResult.isSuccess(preferencesResult)) {
return AsyncResult.isFailure(preferencesResult) ? (
<AdaptiveWorkspaceLayoutContent
{...props}
projectGroupingMode={DEFAULT_MOBILE_PROJECT_GROUPING_SETTINGS.sidebarProjectGroupingMode}
/>
<AdaptiveWorkspaceLayoutContent {...props} projectGroupingMode="repository" />
) : null;
}
const groupingSettings = resolveMobileProjectGroupingSettings(preferencesResult.value);
return (
<AdaptiveWorkspaceLayoutContent
{...props}
projectGroupingMode={groupingSettings.sidebarProjectGroupingMode}
projectGroupingMode={resolveProjectGroupingMode(
preferencesResult.value.projectGroupingEnabled,
)}
/>
);
}
@@ -1,25 +1,15 @@
import { useNavigation } from "@react-navigation/native";
import { Platform, ScrollView, View } from "react-native";
import { ScrollView, View } from "react-native";
import { useSafeAreaInsets } from "react-native-safe-area-context";
import { AndroidScreenHeader } from "../../components/AndroidScreenHeader";
import { NativeStackScreenOptions } from "../../native/StackHeader";
import { CodeAppearanceSection } from "./appearance/sections/CodeAppearanceSection";
import { TerminalAppearanceSection } from "./appearance/sections/TerminalAppearanceSection";
import { TextAppearanceSection } from "./appearance/sections/TextAppearanceSection";
export function SettingsAppearanceRouteScreen() {
const navigation = useNavigation();
const insets = useSafeAreaInsets();
return (
<View collapsable={false} className="flex-1 bg-sheet">
{Platform.OS === "android" ? (
<>
<NativeStackScreenOptions options={{ headerShown: false }} />
<AndroidScreenHeader title="Appearance" onBack={() => navigation.goBack()} />
</>
) : null}
<ScrollView
contentInsetAdjustmentBehavior="automatic"
showsVerticalScrollIndicator={false}
@@ -1,106 +0,0 @@
import { useAtomSet, useAtomValue } from "@effect/atom-react";
import { useNavigation } from "@react-navigation/native";
import type { SidebarProjectGroupingMode } from "@t3tools/contracts";
import { AsyncResult } from "effect/unstable/reactivity";
import { Platform, Pressable, ScrollView, View } from "react-native";
import { useSafeAreaInsets } from "react-native-safe-area-context";
import { AndroidScreenHeader } from "../../components/AndroidScreenHeader";
import { AppText as Text } from "../../components/AppText";
import { SymbolView } from "../../components/AppSymbol";
import { useThemeColor } from "../../lib/useThemeColor";
import { NativeStackScreenOptions } from "../../native/StackHeader";
import {
mobileProjectGroupingModePatch,
resolveMobileProjectGroupingSettings,
} from "../../state/project-grouping";
import { mobilePreferencesAtom, updateMobilePreferencesAtom } from "../../state/preferences";
import { SettingsSection } from "./components/SettingsSection";
const GROUPING_OPTIONS: ReadonlyArray<{
readonly mode: SidebarProjectGroupingMode;
readonly label: string;
readonly description: string;
}> = [
{
mode: "repository",
label: "Group by repository",
description: "Matching repositories appear as one project.",
},
{
mode: "repository_path",
label: "Group by repository path",
description: "Keep monorepo paths separate.",
},
{
mode: "separate",
label: "Keep separate",
description: "Show every workspace as its own project.",
},
];
export function SettingsProjectGroupingRouteScreen() {
const navigation = useNavigation();
const insets = useSafeAreaInsets();
const checkmarkColor = useThemeColor("--color-icon");
const preferencesResult = useAtomValue(mobilePreferencesAtom);
const savePreferences = useAtomSet(updateMobilePreferencesAtom);
const preferencesReady = AsyncResult.isSuccess(preferencesResult) && !preferencesResult.waiting;
const selectedMode = AsyncResult.isSuccess(preferencesResult)
? resolveMobileProjectGroupingSettings(preferencesResult.value).sidebarProjectGroupingMode
: null;
return (
<View collapsable={false} className="flex-1 bg-sheet">
{Platform.OS === "android" ? (
<>
<NativeStackScreenOptions options={{ headerShown: false }} />
<AndroidScreenHeader title="Project Grouping" onBack={() => navigation.goBack()} />
</>
) : null}
<ScrollView
contentInsetAdjustmentBehavior="automatic"
showsVerticalScrollIndicator={false}
className="flex-1"
contentContainerClassName="gap-3 px-5 pt-4"
contentContainerStyle={{ paddingBottom: Math.max(insets.bottom, 18) + 18 }}
>
<SettingsSection title="Default grouping">
{GROUPING_OPTIONS.map((option, index) => (
<Pressable
key={option.mode}
accessibilityRole="radio"
accessibilityState={{
checked: selectedMode === option.mode,
disabled: !preferencesReady,
}}
disabled={!preferencesReady}
onPress={() => savePreferences(mobileProjectGroupingModePatch(option.mode))}
className={
index === 0
? "flex-row items-center gap-4 p-4"
: "flex-row items-center gap-4 border-t border-border-subtle p-4"
}
>
<View className="min-w-0 flex-1 gap-1">
<Text className="text-lg text-foreground">{option.label}</Text>
<Text className="text-sm leading-normal text-foreground-muted">
{option.description}
</Text>
</View>
{selectedMode === option.mode ? (
<SymbolView
name="checkmark"
size={18}
tintColor={checkmarkColor}
type="monochrome"
weight="semibold"
/>
) : null}
</Pressable>
))}
</SettingsSection>
</ScrollView>
</View>
);
}
@@ -530,9 +530,20 @@ function ConfiguredSettingsRouteScreen() {
}
function GeneralSettingsSection() {
const preferencesResult = useAtomValue(mobilePreferencesAtom);
const savePreferences = useAtomSet(updateMobilePreferencesAtom);
const projectGroupingEnabled = AsyncResult.isSuccess(preferencesResult)
? preferencesResult.value.projectGroupingEnabled !== false
: true;
return (
<SettingsSection title="General">
<SettingsRow icon="folder" label="Project Grouping" target="SettingsProjectGrouping" />
<SettingsSwitchRow
icon="folder"
label="Project Grouping"
value={projectGroupingEnabled}
onValueChange={(value) => savePreferences({ projectGroupingEnabled: value })}
/>
</SettingsSection>
);
}
@@ -1,11 +1,4 @@
import {
Platform,
ScrollView,
type StyleProp,
type TextStyle,
View,
useColorScheme,
} from "react-native";
import { Platform, ScrollView, View, useColorScheme } from "react-native";
import { AppText as Text } from "../../../../components/AppText";
import {
@@ -61,48 +54,14 @@ 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={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 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>
</View>
);
@@ -2,7 +2,6 @@ export type SettingsSheetTarget =
| "SettingsEnvironments"
| "SettingsArchive"
| "SettingsAppearance"
| "SettingsProjectGrouping"
| "SettingsClientStorage";
export type SettingsLegalDocumentTarget = "SettingsLegal";
@@ -50,7 +50,6 @@ import { enqueueThreadOutboxMessage, removeThreadOutboxMessage } from "../../sta
import { useRemoteConnectionStatus } from "../../state/use-remote-environment-registry";
import { branchBadgeLabel, useNewTaskFlow } from "./new-task-flow-provider";
import { useCreateProjectThread } from "./use-project-actions";
import { resolveDraftProjectSelection } from "./new-task-project-selection";
import { useIncomingShare } from "../sharing/IncomingShareProvider";
function formatWorkspaceLabel(input: {
@@ -90,7 +89,7 @@ export function NewTaskDraftScreen(props: {
const colorScheme = useColorScheme();
const isKeyboardVisible = useKeyboardState((state) => state.isVisible);
const controlsBottomPadding = isKeyboardVisible ? 8 : Math.max(insets.bottom, 10);
const { projectScopes, selectedProject, selectedProjectKey, setProject } = flow;
const { logicalProjects, selectedProject, setProject } = flow;
const { connectedEnvironments } = useRemoteConnectionStatus();
const selectedEnvironmentServerConfig = useEnvironmentServerConfig(
selectedProject?.environmentId ?? null,
@@ -278,25 +277,24 @@ export function NewTaskDraftScreen(props: {
return;
}
const selection = resolveDraftProjectSelection(selectedProjectKey, projects, projectScopes);
if (selection.kind === "preserve") {
if (selectedProject) {
return;
}
if (selection.kind === "select") {
setProject(selection.project);
if (logicalProjects.length === 1) {
setProject(logicalProjects[0]!.project);
return;
}
navigation.dispatch(StackActions.replace("NewTask"));
}, [
projectScopes,
logicalProjects,
projects,
props.initialProjectRef,
props.incomingShareId,
props.pendingTaskId,
navigation,
selectedProject,
selectedProjectKey,
setProject,
]);
@@ -1,8 +1,8 @@
import { NativeHeaderToolbar, NativeStackScreenOptions } from "../../native/StackHeader";
import { useIsFocused, useNavigation, type StaticScreenProps } from "@react-navigation/native";
import { SymbolView } from "../../components/AppSymbol";
import type { EnvironmentProject } from "@t3tools/client-runtime/state/shell";
import { useEffect, useRef, useState } from "react";
import type { EnvironmentId, ProjectId } from "@t3tools/contracts";
import { useEffect, useMemo, useRef } from "react";
import { ActivityIndicator, Alert, Platform, Pressable, ScrollView, View } from "react-native";
import { useSafeAreaInsets } from "react-native-safe-area-context";
import { useThemeColor } from "../../lib/useThemeColor";
@@ -11,13 +11,12 @@ import { cn } from "../../lib/cn";
import { AndroidScreenHeader } from "../../components/AndroidScreenHeader";
import { AppText as Text } from "../../components/AppText";
import { ProjectFavicon } from "../../components/ProjectFavicon";
import { useProjects } from "../../state/entities";
import { useProjects, useThreadShells } from "../../state/entities";
import type { WorkspaceState } from "../../state/workspaceModel";
import { useWorkspaceState } from "../../state/workspace";
import { scopedProjectKey } from "../../lib/scopedEntities";
import { groupProjectsByRepository } from "../../lib/repositoryGroups";
import { useAdaptiveWorkspaceLayout } from "../layout/AdaptiveWorkspaceLayout";
import { useIncomingShare } from "../sharing/IncomingShareProvider";
import { useNewTaskFlow } from "./new-task-flow-provider";
type NewTaskRouteParams = {
readonly incomingShareId?: string | string[];
@@ -80,7 +79,7 @@ function deriveProjectEmptyState(catalogState: WorkspaceState): {
export function NewTaskRouteScreen({ route }: StaticScreenProps<NewTaskRouteParams | undefined>) {
const projects = useProjects();
const { projectScopes } = useNewTaskFlow();
const threads = useThreadShells();
const { state: catalogState } = useWorkspaceState();
const navigation = useNavigation();
const isFocused = useIsFocused();
@@ -88,7 +87,6 @@ export function NewTaskRouteScreen({ route }: StaticScreenProps<NewTaskRoutePara
const insets = useSafeAreaInsets();
const chevronColor = useThemeColor("--color-chevron");
const accentColor = useThemeColor("--color-icon-muted");
const [expandedGroupKeys, setExpandedGroupKeys] = useState<ReadonlySet<string>>(() => new Set());
const { getShare, releaseShareReservation } = useIncomingShare();
const routeShareId = Array.isArray(route.params?.incomingShareId)
? route.params.incomingShareId[0]
@@ -102,6 +100,33 @@ export function NewTaskRouteScreen({ route }: StaticScreenProps<NewTaskRoutePara
: `Choose a project for the ${incomingShare.attachments.length} images you shared`
: null;
const screenTitle = incomingShare ? "Start a task" : "Choose project";
const repositoryGroups = useMemo(
() => groupProjectsByRepository({ projects, threads }),
[projects, threads],
);
const items = useMemo(() => {
const nextItems: Array<{
readonly environmentId: EnvironmentId;
readonly id: ProjectId;
readonly key: string;
readonly title: string;
readonly workspaceRoot: string;
}> = [];
for (const group of repositoryGroups) {
const project = group.projects[0]?.project;
if (!project) {
continue;
}
nextItems.push({
environmentId: project.environmentId,
id: project.id,
key: group.key,
title: project.title,
workspaceRoot: project.workspaceRoot,
});
}
return nextItems;
}, [repositoryGroups]);
const projectEmptyState = deriveProjectEmptyState(catalogState);
const resumedDestinationKeyRef = useRef<string | null>(null);
const reservedDestinationProject = incomingShare?.destination
@@ -112,7 +137,7 @@ export function NewTaskRouteScreen({ route }: StaticScreenProps<NewTaskRoutePara
) ?? null)
: null;
async function selectProject(project: EnvironmentProject): Promise<void> {
async function selectProject(item: (typeof items)[number]): Promise<void> {
if (incomingShare?.destination && !reservedDestinationProject) {
try {
await releaseShareReservation(incomingShare.id, incomingShare.destination);
@@ -129,26 +154,14 @@ export function NewTaskRouteScreen({ route }: StaticScreenProps<NewTaskRoutePara
navigation.navigate("NewTaskSheet", {
screen: "NewTaskDraft",
params: {
environmentId: project.environmentId,
projectId: project.id,
title: project.title,
environmentId: item.environmentId,
projectId: item.id,
title: item.title,
incomingShareId: incomingShare?.id,
},
});
}
function toggleGroup(groupKey: string): void {
setExpandedGroupKeys((current) => {
const next = new Set(current);
if (next.has(groupKey)) {
next.delete(groupKey);
} else {
next.add(groupKey);
}
return next;
});
}
useEffect(() => {
const destination = incomingShare?.destination;
if (!destination) {
@@ -238,12 +251,11 @@ export function NewTaskRouteScreen({ route }: StaticScreenProps<NewTaskRoutePara
contentInset={{ bottom: Math.max(insets.bottom, 18) + 18 }}
contentContainerStyle={{
gap: 12,
paddingBottom: 8,
paddingHorizontal: 20,
paddingTop: 8,
}}
>
{projectScopes.length === 0 ? (
{items.length === 0 ? (
<View collapsable={false} className="items-center gap-3 rounded-[24px] bg-card px-6 py-8">
{projectEmptyState.loading ? <ActivityIndicator color={accentColor} /> : null}
<Text className="text-center text-lg font-t3-bold text-foreground">
@@ -274,89 +286,42 @@ export function NewTaskRouteScreen({ route }: StaticScreenProps<NewTaskRoutePara
</View>
) : (
<View collapsable={false} className="overflow-hidden rounded-[24px] bg-card">
{projectScopes.map((scope, scopeIndex) => {
const hasMultipleProjects = scope.projects.length > 1;
const expanded = expandedGroupKeys.has(scope.key);
const singleProject = hasMultipleProjects ? null : scope.projects[0];
{items.map((item, index) => {
const isFirst = index === 0;
const isLast = index === items.length - 1;
return (
<View
key={scope.key}
className={cn(scopeIndex > 0 && "border-t border-border-subtle")}
<Pressable
key={item.key}
disabled={reservedDestinationProject !== null}
onPress={() => void selectProject(item)}
className={cn(
"bg-card px-4 py-3.5",
!isFirst && "border-t border-border-subtle",
isFirst && "rounded-t-[24px]",
isLast && "rounded-b-[24px]",
)}
>
<Pressable
disabled={singleProject !== null && reservedDestinationProject !== null}
onPress={() => {
if (singleProject) {
void selectProject(singleProject);
} else {
toggleGroup(scope.key);
}
}}
className="flex-row items-center gap-3 bg-card px-4 py-3.5"
>
<View className="flex-row items-center justify-between gap-3">
<View className="h-7 w-7 items-center justify-center">
<ProjectFavicon
environmentId={scope.representative.environmentId}
environmentId={item.environmentId}
size={20}
projectTitle={scope.title}
workspaceRoot={scope.representative.workspaceRoot}
projectTitle={item.title}
workspaceRoot={item.workspaceRoot}
/>
</View>
<View className="min-w-0 flex-1">
<Text className="text-base leading-snug font-t3-bold">{scope.title}</Text>
<Text
className="text-xs leading-snug text-foreground-muted"
ellipsizeMode="middle"
numberOfLines={1}
>
{hasMultipleProjects
? `${scope.projects.length} workspaces`
: singleProject?.workspaceRoot}
</Text>
<View className="flex-1">
<Text className="text-base leading-snug font-t3-bold">{item.title}</Text>
</View>
<SymbolView
name={hasMultipleProjects && expanded ? "chevron.down" : "chevron.right"}
name="chevron.right"
size={14}
tintColor={chevronColor}
type="monochrome"
/>
</Pressable>
{hasMultipleProjects && expanded
? scope.projects.map((project) => (
<Pressable
key={scopedProjectKey(project.environmentId, project.id)}
disabled={reservedDestinationProject !== null}
onPress={() => void selectProject(project)}
className="flex-row items-center gap-3 border-t border-border-subtle bg-card py-3 pr-4 pl-10"
>
<ProjectFavicon
environmentId={project.environmentId}
size={18}
projectTitle={project.title}
workspaceRoot={project.workspaceRoot}
/>
<View className="min-w-0 flex-1">
<Text className="text-sm font-t3-bold text-foreground">
{project.title}
</Text>
<Text
className="text-xs text-foreground-muted"
ellipsizeMode="middle"
numberOfLines={1}
>
{project.workspaceRoot}
</Text>
</View>
<SymbolView
name="chevron.right"
size={14}
tintColor={chevronColor}
type="monochrome"
/>
</Pressable>
))
: null}
</View>
</View>
</Pressable>
);
})}
</View>
@@ -3,7 +3,6 @@ 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;
@@ -16,7 +15,7 @@ export interface PendingApprovalCardProps {
export function PendingApprovalCard(props: PendingApprovalCardProps) {
return (
<PendingCardSurface>
<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">
<Text className="font-t3-bold text-2xs uppercase tracking-[1.1px] text-sky-700 dark:text-sky-300">
Approval needed
</Text>
@@ -53,6 +52,6 @@ export function PendingApprovalCard(props: PendingApprovalCardProps) {
<Text className="font-t3-bold text-sm text-rose-700 dark:text-rose-300">Decline</Text>
</Pressable>
</View>
</PendingCardSurface>
</View>
);
}
@@ -1,35 +0,0 @@
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,7 +4,6 @@ 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;
@@ -26,7 +25,7 @@ export interface PendingUserInputCardProps {
export function PendingUserInputCard(props: PendingUserInputCardProps) {
return (
<PendingCardSurface>
<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">
<Text className="font-t3-bold text-2xs uppercase tracking-[1.1px] text-sky-700 dark:text-sky-300">
User input needed
</Text>
@@ -101,6 +100,6 @@ export function PendingUserInputCard(props: PendingUserInputCardProps) {
>
<Text className="font-t3-extrabold text-sm text-white">Submit answers</Text>
</Pressable>
</PendingCardSurface>
</View>
);
}
@@ -1,4 +1,3 @@
import { isLiquidGlassSupported } from "@callstack/liquid-glass";
import { type EnvironmentConnectionPhase } from "@t3tools/client-runtime/connection";
import type { EnvironmentThreadStatus } from "@t3tools/client-runtime/state/threads";
import { useKeyboardChatComposerInset, useKeyboardScrollToEnd } from "@legendapp/list/keyboard";
@@ -392,7 +391,7 @@ export const ThreadDetailScreen = memo(function ThreadDetailScreen(props: Thread
{props.activePendingApproval || props.activePendingUserInput ? (
<Animated.View
className="shrink-0 gap-3 px-4 pb-3"
entering={isLiquidGlassSupported ? undefined : FadeInDown.duration(220)}
entering={FadeInDown.duration(220)}
exiting={FadeOut.duration(140)}
>
{props.activePendingApproval ? (
@@ -27,6 +27,7 @@ import {
groupByProvider,
resolveSelectableModelSelection,
} from "../../lib/modelOptions";
import { groupProjectsByRepository } from "../../lib/repositoryGroups";
import { scopedProjectKey } from "../../lib/scopedEntities";
import { appAtomRegistry } from "../../state/atom-registry";
import {
@@ -58,12 +59,6 @@ import {
} from "../../state/use-remote-environment-registry";
import { EnvironmentProject } from "@t3tools/client-runtime/state/shell";
import { type VcsRef } from "@t3tools/client-runtime/state/vcs";
import {
buildHomeProjectScopes,
sortHomeProjectScopes,
type HomeProjectScope,
} from "../home/homeThreadList";
import { useMobileProjectGroupingSettings } from "../../state/project-grouping";
type WorkspaceMode = "local" | "worktree";
@@ -114,7 +109,10 @@ export function branchBadgeLabel(input: {
}
type NewTaskFlowContextValue = {
readonly projectScopes: ReadonlyArray<HomeProjectScope>;
readonly logicalProjects: ReadonlyArray<{
readonly key: string;
readonly project: EnvironmentProject;
}>;
readonly selectedEnvironmentId: EnvironmentId | null;
readonly selectedProjectKey: string | null;
readonly selectedModelKey: string | null;
@@ -177,20 +175,32 @@ export function NewTaskFlowProvider(props: React.PropsWithChildren) {
const projects = useProjects();
const threads = useThreadShells();
const { savedConnectionsById } = useSavedRemoteConnections();
const groupingSettings = useMobileProjectGroupingSettings();
const projectScopes = useMemo(
const repositoryGroups = useMemo(
() => groupProjectsByRepository({ projects, threads }),
[projects, threads],
);
const logicalProjects = useMemo(
() =>
sortHomeProjectScopes({
scopes: buildHomeProjectScopes({
projects,
environmentId: null,
projectGroupingMode: groupingSettings.sidebarProjectGroupingMode,
pipe(
repositoryGroups,
Arr.map((group) => {
const primaryProject = group.projects[0]?.project;
if (!primaryProject) {
return null;
}
return { key: group.key, project: primaryProject };
}),
threads,
pendingTasks: [],
projectSortOrder: "updated_at",
}),
[groupingSettings.sidebarProjectGroupingMode, projects, threads],
Arr.filter(
(
entry,
): entry is {
readonly key: string;
readonly project: EnvironmentProject;
} => entry !== null,
),
),
[repositoryGroups],
);
const [selectedEnvironmentIdOverride, setSelectedEnvironmentId] = useState<EnvironmentId | null>(
@@ -836,7 +846,7 @@ export function NewTaskFlowProvider(props: React.PropsWithChildren) {
const value = useMemo<NewTaskFlowContextValue>(
() => ({
projectScopes,
logicalProjects,
selectedEnvironmentId,
selectedProjectKey,
selectedModelKey,
@@ -902,7 +912,7 @@ export function NewTaskFlowProvider(props: React.PropsWithChildren) {
finishEditingPendingTask,
interactionMode,
loadBranches,
projectScopes,
logicalProjects,
modelOptions,
prompt,
providerGroups,
@@ -1,82 +0,0 @@
import { EnvironmentId, ProjectId } from "@t3tools/contracts";
import { describe, expect, it } from "vite-plus/test";
import type { EnvironmentProject } from "@t3tools/client-runtime/state/shell";
import type { HomeProjectScope } from "../home/homeThreadList";
import {
getOnlySelectableProject,
resolveDraftProjectSelection,
} from "./new-task-project-selection";
function makeProject(id: string): EnvironmentProject {
return {
environmentId: EnvironmentId.make("environment"),
id: ProjectId.make(id),
title: id,
workspaceRoot: `/work/${id}`,
repositoryIdentity: null,
defaultModelSelection: null,
scripts: [],
createdAt: "2026-07-01T00:00:00.000Z",
updatedAt: "2026-07-01T00:00:00.000Z",
};
}
function makeScope(projects: ReadonlyArray<EnvironmentProject>): HomeProjectScope {
return {
key: "github.com/t3tools/t3code",
title: "T3 Code",
representative: projects[0]!,
projects,
projectRefs: projects.map((project) => ({
environmentId: project.environmentId,
projectId: project.id,
})),
};
}
describe("getOnlySelectableProject", () => {
it("auto-selects when there is exactly one physical project", () => {
const project = makeProject("t3code");
expect(getOnlySelectableProject([makeScope([project])])).toBe(project);
});
it("does not auto-select a representative when one group has multiple clones", () => {
const projects = [makeProject("t3code"), makeProject("t3code-2"), makeProject("t3code-3")];
expect(getOnlySelectableProject([makeScope(projects)])).toBeNull();
});
});
describe("resolveDraftProjectSelection", () => {
it("preserves an explicit project selection", () => {
const project = makeProject("t3code");
expect(
resolveDraftProjectSelection("environment:t3code", [project], [makeScope([project])]),
).toEqual({ kind: "preserve" });
});
it("selects the only physical project when no project was explicitly selected", () => {
const project = makeProject("t3code");
expect(resolveDraftProjectSelection(null, [project], [makeScope([project])])).toEqual({
kind: "select",
project,
});
});
it("opens the picker for multiple physical projects in one logical group", () => {
const projects = [makeProject("t3code"), makeProject("t3code-2"), makeProject("t3code-3")];
expect(resolveDraftProjectSelection(null, projects, [makeScope(projects)])).toEqual({
kind: "pick",
});
});
it("does not preserve a project key that is missing from the catalog", () => {
const project = makeProject("t3code");
expect(
resolveDraftProjectSelection("environment:removed", [project], [makeScope([project])]),
).toEqual({
kind: "select",
project,
});
});
});
@@ -1,34 +0,0 @@
import type { EnvironmentProject } from "@t3tools/client-runtime/state/shell";
import { scopedProjectKey } from "../../lib/scopedEntities";
import type { HomeProjectScope } from "../home/homeThreadList";
export type DraftProjectSelectionResolution =
| { readonly kind: "preserve" }
| { readonly kind: "select"; readonly project: EnvironmentProject }
| { readonly kind: "pick" };
export function getOnlySelectableProject(
projectScopes: ReadonlyArray<HomeProjectScope>,
): EnvironmentProject | null {
const onlyScope = projectScopes.length === 1 ? projectScopes[0] : null;
return onlyScope?.projects.length === 1 ? (onlyScope.projects[0] ?? null) : null;
}
export function resolveDraftProjectSelection(
selectedProjectKey: string | null,
projects: ReadonlyArray<EnvironmentProject>,
projectScopes: ReadonlyArray<HomeProjectScope>,
): DraftProjectSelectionResolution {
const hasExplicitProjectSelection =
selectedProjectKey !== null &&
projects.some(
(project) => scopedProjectKey(project.environmentId, project.id) === selectedProjectKey,
);
if (hasExplicitProjectSelection) {
return { kind: "preserve" };
}
const onlyProject = getOnlySelectableProject(projectScopes);
return onlyProject ? { kind: "select", project: onlyProject } : { kind: "pick" };
}
@@ -204,8 +204,6 @@ export const ThreadListV2PendingRow = memo(function ThreadListV2PendingRow(props
readonly pane?: "screen" | "sidebar";
/** Draws the "Pending" divider above the first queued row. */
readonly showPendingDivider: boolean;
/** Keeps row hairlines inside a section; section headers draw their own rule. */
readonly showTrailingDivider?: boolean;
readonly onSelectPendingTask: (pendingTask: PendingNewTask) => void;
readonly onDeletePendingTask: (pendingTask: PendingNewTask) => void;
}) {
@@ -293,9 +291,7 @@ export const ThreadListV2PendingRow = memo(function ThreadListV2PendingRow(props
) : (
<View className="bg-screen">
<View className="px-5 py-2.5">{rowContent}</View>
{props.showTrailingDivider !== false ? (
<View className="ml-5 h-px bg-border-subtle" />
) : null}
<View className="ml-5 h-px bg-border-subtle" />
</View>
)}
</Pressable>
@@ -331,8 +327,6 @@ export const ThreadListV2Row = memo(function ThreadListV2Row(props: {
into the drawer surface, selection filled with the accent color —
matching the v1 sidebar rows. */
readonly pane?: "screen" | "sidebar";
/** Keeps row hairlines inside a section; section headers draw their own rule. */
readonly showTrailingDivider?: boolean;
/** Highlights the thread open in the detail pane (iPad split view). The
compact Home list never sets it — phones navigate away on select. */
readonly selected?: boolean;
@@ -734,9 +728,7 @@ export const ThreadListV2Row = memo(function ThreadListV2Row(props: {
actions reveal behind the row. */
<View className="bg-screen">
<View className="px-5 py-2.5">{cardContent}</View>
{props.showTrailingDivider !== false ? (
<View className="ml-5 h-px bg-border-subtle" />
) : null}
<View className="ml-5 h-px bg-border-subtle" />
</View>
)}
</Pressable>
@@ -0,0 +1,192 @@
import { describe, expect, it } from "vite-plus/test";
import { EnvironmentId, ProjectId, ProviderInstanceId, ThreadId } from "@t3tools/contracts";
import { groupProjectsByRepository } from "./repositoryGroups";
import { EnvironmentProject, EnvironmentThreadShell } from "@t3tools/client-runtime/state/shell";
function makeProject(
input: Partial<EnvironmentProject> & Pick<EnvironmentProject, "environmentId" | "id" | "title">,
): EnvironmentProject {
return {
workspaceRoot: `/workspaces/${input.id}`,
repositoryIdentity: null,
defaultModelSelection: null,
scripts: [],
createdAt: "2026-04-01T00:00:00.000Z",
updatedAt: "2026-04-01T00:00:00.000Z",
...input,
};
}
function makeThread(
input: Partial<EnvironmentThreadShell> &
Pick<EnvironmentThreadShell, "environmentId" | "id" | "projectId" | "title" | "modelSelection">,
): EnvironmentThreadShell {
return {
runtimeMode: "full-access",
interactionMode: "default",
branch: null,
worktreePath: null,
latestTurn: null,
createdAt: "2026-04-01T00:00:00.000Z",
updatedAt: "2026-04-01T00:00:00.000Z",
archivedAt: null,
session: null,
latestUserMessageAt: null,
hasPendingApprovals: false,
hasPendingUserInput: false,
hasActionableProposedPlan: false,
...input,
settledOverride: input.settledOverride ?? null,
settledAt: input.settledAt ?? null,
};
}
describe("groupProjectsByRepository", () => {
it("groups projects across environments by repository identity", () => {
const repoIdentity = {
canonicalKey: "github.com/t3tools/t3code",
locator: {
source: "git-remote" as const,
remoteName: "origin",
remoteUrl: "[email protected]:t3tools/t3code.git",
},
provider: "github",
owner: "t3tools",
name: "t3code",
displayName: "T3 Code",
};
const projects = [
makeProject({
environmentId: EnvironmentId.make("env-local"),
id: ProjectId.make("project-local"),
title: "T3 Code",
repositoryIdentity: repoIdentity,
}),
makeProject({
environmentId: EnvironmentId.make("env-staging"),
id: ProjectId.make("project-staging"),
title: "T3 Code",
repositoryIdentity: repoIdentity,
}),
];
const threads = [
makeThread({
environmentId: EnvironmentId.make("env-staging"),
id: ThreadId.make("thread-2"),
projectId: ProjectId.make("project-staging"),
title: "Fix reconnect flow",
modelSelection: { instanceId: ProviderInstanceId.make("codex"), model: "gpt-5.4" },
updatedAt: "2026-04-02T12:00:00.000Z",
}),
makeThread({
environmentId: EnvironmentId.make("env-local"),
id: ThreadId.make("thread-1"),
projectId: ProjectId.make("project-local"),
title: "Polish mobile shell",
modelSelection: { instanceId: ProviderInstanceId.make("codex"), model: "gpt-5.4" },
updatedAt: "2026-04-03T12:00:00.000Z",
}),
];
const groups = groupProjectsByRepository({ projects, threads });
expect(groups).toHaveLength(1);
expect(groups[0]).toMatchObject({
key: "github.com/t3tools/t3code",
title: "T3 Code",
subtitle: "t3tools/t3code",
projectCount: 2,
threadCount: 2,
});
expect(
groups[0]?.projects.map((entry) => ({
environmentId: entry.project.environmentId,
latestActivityAt: entry.latestActivityAt,
threads: entry.threads.map((thread) => thread.id),
})),
).toEqual([
{
environmentId: "env-local",
latestActivityAt: "2026-04-03T12:00:00.000Z",
threads: ["thread-1"],
},
{
environmentId: "env-staging",
latestActivityAt: "2026-04-02T12:00:00.000Z",
threads: ["thread-2"],
},
]);
expect(groups[0]?.latestActivityAt).toBe("2026-04-03T12:00:00.000Z");
});
it("orders threads, projects, and repository groups by latest activity", () => {
const projects = [
makeProject({
environmentId: EnvironmentId.make("env-local"),
id: ProjectId.make("older-project"),
title: "Older",
}),
makeProject({
environmentId: EnvironmentId.make("env-local"),
id: ProjectId.make("newer-project"),
title: "Newer",
}),
];
const threads = [
makeThread({
environmentId: EnvironmentId.make("env-local"),
id: ThreadId.make("older-thread"),
projectId: ProjectId.make("older-project"),
title: "Older thread",
modelSelection: { instanceId: ProviderInstanceId.make("codex"), model: "gpt-5.4" },
updatedAt: "2026-04-02T12:00:00.000Z",
}),
makeThread({
environmentId: EnvironmentId.make("env-local"),
id: ThreadId.make("newer-thread"),
projectId: ProjectId.make("older-project"),
title: "Newer thread",
modelSelection: { instanceId: ProviderInstanceId.make("codex"), model: "gpt-5.4" },
updatedAt: "2026-04-04T12:00:00.000Z",
}),
makeThread({
environmentId: EnvironmentId.make("env-local"),
id: ThreadId.make("newest-thread"),
projectId: ProjectId.make("newer-project"),
title: "Newest thread",
modelSelection: { instanceId: ProviderInstanceId.make("codex"), model: "gpt-5.4" },
updatedAt: "2026-04-05T12:00:00.000Z",
}),
];
const groups = groupProjectsByRepository({ projects, threads });
expect(groups.map((group) => group.title)).toEqual(["Newer", "Older"]);
expect(groups[1]?.projects[0]?.threads.map((thread) => thread.id)).toEqual([
"newer-thread",
"older-thread",
]);
});
it("falls back to a scoped project key when repository identity is unavailable", () => {
const projects = [
makeProject({
environmentId: EnvironmentId.make("env-local"),
id: ProjectId.make("project-local"),
title: "Scratchpad",
}),
];
const groups = groupProjectsByRepository({ projects, threads: [] });
expect(groups).toHaveLength(1);
expect(groups[0]?.key).toBe("env-local:project-local");
expect(groups[0]?.title).toBe("Scratchpad");
expect(groups[0]?.subtitle).toBeNull();
});
});
+131
View File
@@ -0,0 +1,131 @@
import * as Order from "effect/Order";
import * as Arr from "effect/Array";
import type { RepositoryIdentity } from "@t3tools/contracts";
import { scopedProjectKey } from "./scopedEntities";
import { EnvironmentProject, EnvironmentThreadShell } from "@t3tools/client-runtime/state/shell";
const DateDescending = Order.flip(Order.Date);
export interface RepositoryProjectGroup {
readonly key: string;
readonly project: EnvironmentProject;
readonly threads: ReadonlyArray<EnvironmentThreadShell>;
readonly latestActivityAt: string;
}
export interface RepositoryGroup {
readonly key: string;
readonly title: string;
readonly subtitle: string | null;
readonly repositoryIdentity: RepositoryIdentity | null;
readonly projectCount: number;
readonly threadCount: number;
readonly latestActivityAt: string;
readonly projects: ReadonlyArray<RepositoryProjectGroup>;
}
function compareIsoDateDescending(left: string, right: string): number {
return new Date(right).getTime() - new Date(left).getTime();
}
function deriveRepositoryGroupKey(project: EnvironmentProject): string {
return (
project.repositoryIdentity?.canonicalKey ?? scopedProjectKey(project.environmentId, project.id)
);
}
function deriveRepositoryTitle(project: EnvironmentProject): string {
const identity = project.repositoryIdentity;
return identity?.displayName ?? identity?.name ?? project.title;
}
function deriveRepositorySubtitle(identity: RepositoryIdentity | null | undefined): string | null {
if (!identity) {
return null;
}
if (identity.owner && identity.name) {
return `${identity.owner}/${identity.name}`;
}
return identity.canonicalKey;
}
function deriveProjectLatestActivity(
project: EnvironmentProject,
threads: ReadonlyArray<EnvironmentThreadShell>,
): string {
const latestThread = threads[0];
return latestThread?.updatedAt ?? latestThread?.createdAt ?? project.updatedAt;
}
export function groupProjectsByRepository(input: {
readonly projects: ReadonlyArray<EnvironmentProject>;
readonly threads: ReadonlyArray<EnvironmentThreadShell>;
}): ReadonlyArray<RepositoryGroup> {
const threadsByProjectKey = new Map<string, EnvironmentThreadShell[]>();
for (const thread of input.threads) {
const key = scopedProjectKey(thread.environmentId, thread.projectId);
const existing = threadsByProjectKey.get(key);
if (existing) {
existing.push(thread);
} else {
threadsByProjectKey.set(key, [thread]);
}
}
const grouped = new Map<string, RepositoryGroup>();
for (const project of input.projects) {
const key = deriveRepositoryGroupKey(project);
const projectKey = scopedProjectKey(project.environmentId, project.id);
const threads = Arr.sortWith(
threadsByProjectKey.get(projectKey) ?? [],
(s) => new Date(s.updatedAt ?? s.createdAt),
DateDescending,
);
const latestActivityAt = deriveProjectLatestActivity(project, threads);
const projectGroup: RepositoryProjectGroup = {
key: projectKey,
project,
threads,
latestActivityAt,
};
const existing = grouped.get(key);
if (!existing) {
grouped.set(key, {
key,
title: deriveRepositoryTitle(project),
subtitle: deriveRepositorySubtitle(project.repositoryIdentity),
repositoryIdentity: project.repositoryIdentity ?? null,
projectCount: 1,
threadCount: threads.length,
latestActivityAt,
projects: [projectGroup],
});
continue;
}
grouped.set(key, {
...existing,
title: existing.repositoryIdentity ? existing.title : deriveRepositoryTitle(project),
subtitle: existing.subtitle ?? deriveRepositorySubtitle(project.repositoryIdentity),
repositoryIdentity: existing.repositoryIdentity ?? project.repositoryIdentity ?? null,
projectCount: existing.projectCount + 1,
threadCount: existing.threadCount + threads.length,
latestActivityAt:
compareIsoDateDescending(existing.latestActivityAt, latestActivityAt) > 0
? latestActivityAt
: existing.latestActivityAt,
projects: Arr.sortWith(
[...existing.projects, projectGroup],
(s) => new Date(s.latestActivityAt),
DateDescending,
),
});
}
return Arr.sortWith(grouped.values(), (s) => new Date(s.latestActivityAt), DateDescending);
}
@@ -5,7 +5,6 @@ import * as Option from "effect/Option";
import * as Ref from "effect/Ref";
import * as Schema from "effect/Schema";
import * as Semaphore from "effect/Semaphore";
import type { SidebarProjectGroupingMode } from "@t3tools/contracts";
import * as MobileDatabase from "./mobile-database";
import * as MobileSecureStorage from "./mobile-secure-storage";
@@ -23,9 +22,7 @@ export interface Preferences {
readonly codeWordBreak?: boolean;
readonly connectOnboardingOptOutAccounts?: ReadonlyArray<string>;
readonly collapsedProjectGroups?: readonly string[];
/** @deprecated Kept temporarily so older OTA bundles retain the selected mode. */
readonly projectGroupingEnabled?: boolean;
readonly projectGroupingMode?: SidebarProjectGroupingMode;
/**
* Device-local mirror of the web beta's `sidebarV2Enabled`. Mobile has no
* client-settings sync, so the flat v2 thread list is opted out of per
@@ -83,7 +80,6 @@ function sanitizePreferences(parsed: Preferences): Preferences {
connectOnboardingOptOutAccounts?: ReadonlyArray<string>;
collapsedProjectGroups?: readonly string[];
projectGroupingEnabled?: boolean;
projectGroupingMode?: SidebarProjectGroupingMode;
threadListV2Enabled?: boolean;
} = {};
@@ -114,13 +110,6 @@ function sanitizePreferences(parsed: Preferences): Preferences {
if (typeof parsed.projectGroupingEnabled === "boolean") {
preferences.projectGroupingEnabled = parsed.projectGroupingEnabled;
}
if (
parsed.projectGroupingMode === "repository" ||
parsed.projectGroupingMode === "repository_path" ||
parsed.projectGroupingMode === "separate"
) {
preferences.projectGroupingMode = parsed.projectGroupingMode;
}
if (typeof parsed.threadListV2Enabled === "boolean") {
preferences.threadListV2Enabled = parsed.threadListV2Enabled;
}
@@ -1,33 +0,0 @@
import type { ProjectGroupingSettings } from "@t3tools/client-runtime/state/project-grouping";
import type { SidebarProjectGroupingMode } from "@t3tools/contracts";
import type { Preferences } from "../persistence/mobile-preferences";
export const DEFAULT_MOBILE_PROJECT_GROUPING_SETTINGS: ProjectGroupingSettings = {
sidebarProjectGroupingMode: "repository",
sidebarProjectGroupingOverrides: {},
};
export function resolveMobileProjectGroupingSettings(
preferences: Preferences,
): ProjectGroupingSettings {
return {
sidebarProjectGroupingMode:
preferences.projectGroupingMode ??
(preferences.projectGroupingEnabled === false ? "separate" : "repository"),
sidebarProjectGroupingOverrides: {},
};
}
/**
* Dual-writes the legacy boolean for one release so an OTA rollback to an
* older mobile bundle preserves the user's grouping choice.
*/
export function mobileProjectGroupingModePatch(
mode: SidebarProjectGroupingMode,
): Partial<Preferences> {
return {
projectGroupingMode: mode,
projectGroupingEnabled: mode !== "separate",
};
}
@@ -1,33 +0,0 @@
import { describe, expect, it } from "vite-plus/test";
import {
mobileProjectGroupingModePatch,
resolveMobileProjectGroupingSettings,
} from "./project-grouping.logic";
describe("mobile project grouping preferences", () => {
it("maps the legacy boolean while preferring the new mode", () => {
expect(resolveMobileProjectGroupingSettings({}).sidebarProjectGroupingMode).toBe("repository");
expect(
resolveMobileProjectGroupingSettings({ projectGroupingEnabled: false })
.sidebarProjectGroupingMode,
).toBe("separate");
expect(
resolveMobileProjectGroupingSettings({
projectGroupingEnabled: false,
projectGroupingMode: "repository_path",
}).sidebarProjectGroupingMode,
).toBe("repository_path");
});
it("dual-writes the legacy boolean for rollback compatibility", () => {
expect(mobileProjectGroupingModePatch("separate")).toEqual({
projectGroupingMode: "separate",
projectGroupingEnabled: false,
});
expect(mobileProjectGroupingModePatch("repository_path")).toEqual({
projectGroupingMode: "repository_path",
projectGroupingEnabled: true,
});
});
});
-17
View File
@@ -1,17 +0,0 @@
import { useAtomValue } from "@effect/atom-react";
import { AsyncResult } from "effect/unstable/reactivity";
import { mobilePreferencesAtom } from "./preferences";
import {
DEFAULT_MOBILE_PROJECT_GROUPING_SETTINGS,
resolveMobileProjectGroupingSettings,
} from "./project-grouping.logic";
export * from "./project-grouping.logic";
export function useMobileProjectGroupingSettings() {
const preferencesResult = useAtomValue(mobilePreferencesAtom);
return AsyncResult.isSuccess(preferencesResult)
? resolveMobileProjectGroupingSettings(preferencesResult.value)
: DEFAULT_MOBILE_PROJECT_GROUPING_SETTINGS;
}
+45 -3
View File
@@ -6,6 +6,7 @@ import * as NodePath from "node:path";
import * as NodeServices from "@effect/platform-node/NodeServices";
import * as NetService from "@t3tools/shared/Net";
import { TailscaleCommandExitError } from "@t3tools/tailscale";
import { assert, describe, expect, it } from "@effect/vitest";
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
@@ -22,6 +23,7 @@ import {
DevServerNotProxiableError,
resolveDirectPairingBaseUrl,
resolveTailscaleLocalTarget,
tailscaleServeFailedError,
} from "./pair.ts";
const CliRuntimeLayer = Layer.mergeAll(NodeServices.layer, NetService.layer);
@@ -50,6 +52,45 @@ describe("pair base URL selection", () => {
});
describe("pair tailscale local target", () => {
it("surfaces the operator fix from safe structural error fields", () => {
const cause = new TailscaleCommandExitError({
executable: "tailscale",
subcommand: "serve",
argumentCount: 4,
exitCode: 1,
stderrLength: 24,
stderrDiagnostic: "permission-denied",
});
const failure = tailscaleServeFailedError(443, cause);
expect(failure).toMatchObject({
exitCode: 1,
stderrDiagnostic: "permission-denied",
cause,
});
expect(failure.message).toBe(
"tailscale serve failed with code 1 for HTTPS port 443: access denied. Run `sudo tailscale set --operator=$USER`, then retry.",
);
});
it("keeps Windows permission guidance free of Unix-only commands", () => {
const cause = new TailscaleCommandExitError({
executable: "tailscale.exe",
subcommand: "serve",
argumentCount: 4,
exitCode: 1,
stderrLength: 24,
stderrDiagnostic: "permission-denied",
});
const failure = tailscaleServeFailedError(443, cause);
expect(failure).toMatchObject({ executable: "tailscale.exe", cause });
expect(failure.message).toContain("Grant this Windows user permission");
expect(failure.message).not.toContain("sudo");
});
it("proxies the dev web port for dev servers", () => {
expect(resolveTailscaleLocalTarget({ ...baseState, devUrl: "http://localhost:5733/" })).toEqual(
{ localPort: 5_733 },
@@ -205,7 +246,8 @@ describe("t3 pair", () => {
const rendered = String(
typeof error === "object" && error !== null && "cause" in error ? error.cause : error,
);
assert.include(rendered, "No running T3 Code server found.");
assert.include(rendered, "No usable T3 Code server runtime state found.");
assert.include(rendered, "--base-dir");
assert.include(rendered, "npx t3 serve");
assert.include(rendered, "npx t3 connect");
}).pipe(Effect.provide(NodeServices.layer)),
@@ -236,7 +278,7 @@ describe("t3 pair", () => {
const rendered = String(
typeof error === "object" && error !== null && "cause" in error ? error.cause : error,
);
assert.include(rendered, "No running T3 Code server found.");
assert.include(rendered, "No usable T3 Code server runtime state found.");
}),
).pipe(Effect.provide(NodeServices.layer)),
);
@@ -262,7 +304,7 @@ describe("t3 pair", () => {
const rendered = String(
typeof error === "object" && error !== null && "cause" in error ? error.cause : error,
);
assert.include(rendered, "No running T3 Code server found.");
assert.include(rendered, "No usable T3 Code server runtime state found.");
}).pipe(Effect.provide(NodeServices.layer)),
);
});
+38 -8
View File
@@ -20,6 +20,8 @@ import {
DEFAULT_TAILSCALE_SERVE_PORT,
ensureTailscaleServe,
readTailscaleStatus,
TailscaleCommandExitError,
TailscaleStderrDiagnostic,
} from "@t3tools/tailscale";
import * as Config from "effect/Config";
import * as Console from "effect/Console";
@@ -76,9 +78,10 @@ export class NoRunningServerError extends Schema.TaggedErrorClass<NoRunningServe
) {
override get message(): string {
return [
"No running T3 Code server found.",
"No usable T3 Code server runtime state found.",
...this.checkedStatePaths.map((statePath) => ` checked ${statePath}`),
"Start one with `npx t3 serve`, or connect this machine with T3 Connect: `npx t3 connect`.",
"If a server is running, pass its T3 home with `--base-dir`; its runtime state may be missing or stale.",
"Otherwise start one with `npx t3 serve`, or connect this machine with T3 Connect: `npx t3 connect`.",
].join("\n");
}
}
@@ -114,13 +117,44 @@ export class ServesOtherEnvironmentError extends Schema.TaggedErrorClass<ServesO
export class TailscaleServeFailedError extends Schema.TaggedErrorClass<TailscaleServeFailedError>()(
"TailscaleServeFailedError",
{ servePort: Schema.Number, cause: Schema.Defect() },
{
servePort: Schema.Number,
executable: Schema.optional(Schema.Literals(["tailscale", "tailscale.exe"])),
exitCode: Schema.optional(Schema.Number),
stderrDiagnostic: Schema.optional(TailscaleStderrDiagnostic),
cause: Schema.Defect(),
},
) {
override get message(): string {
if (this.stderrDiagnostic === "permission-denied") {
const exitDetail = this.exitCode === undefined ? "" : ` with code ${String(this.exitCode)}`;
if (this.executable === "tailscale.exe") {
return `tailscale serve failed${exitDetail} for HTTPS port ${String(this.servePort)}: access denied. Grant this Windows user permission to manage Tailscale, then retry.`;
}
return `tailscale serve failed${exitDetail} for HTTPS port ${String(this.servePort)}: access denied. Run \`sudo tailscale set --operator=$USER\`, then retry.`;
}
return `tailscale serve failed for HTTPS port ${String(this.servePort)}. Run \`tailscale serve --https=${String(this.servePort)} --bg <local-url>\` by hand to see why.`;
}
}
const isTailscaleCommandExitError = Schema.is(TailscaleCommandExitError);
export function tailscaleServeFailedError(
servePort: number,
cause: unknown,
): TailscaleServeFailedError {
const exitDetails = isTailscaleCommandExitError(cause)
? {
executable: cause.executable,
exitCode: cause.exitCode,
...(cause.stderrDiagnostic === undefined
? {}
: { stderrDiagnostic: cause.stderrDiagnostic }),
}
: {};
return new TailscaleServeFailedError({ servePort, cause, ...exitDetails });
}
export class ServePortOccupiedError extends Schema.TaggedErrorClass<ServePortOccupiedError>()(
"ServePortOccupiedError",
{ servePort: Schema.Number },
@@ -409,11 +443,7 @@ const resolveTailscalePairingBase = Effect.fn("pair.resolveTailscalePairingBase"
localPort: localTarget.localPort,
servePort: input.servePort,
...(localTarget.localHost !== undefined ? { localHost: localTarget.localHost } : {}),
}).pipe(
Effect.mapError(
(cause) => new TailscaleServeFailedError({ servePort: input.servePort, cause }),
),
);
}).pipe(Effect.mapError((cause) => tailscaleServeFailedError(input.servePort, cause)));
notes.push(
`Tailscale Serve now maps ${baseUrl} to this server and persists across restarts. Remove it with \`tailscale serve --https=${String(input.servePort)} off\`.`,
);
+41 -1
View File
@@ -1,6 +1,6 @@
import { assert, it } from "@effect/vitest";
import { formatServiceStatus } from "./service.ts";
import { formatServiceStatus, serviceDowngradeRefusal } from "./service.ts";
const status = {
supported: true,
@@ -8,6 +8,7 @@ const status = {
current: true,
unitPath: "/home/me/.config/systemd/user/t3code.service",
logPath: "/home/me/.t3/userdata/logs/boot-service.log",
installedVersion: "0.0.29",
} as const;
it("reports the installed service version and host paths", () => {
@@ -35,3 +36,42 @@ it("explains service availability without systemd", () => {
"Supported on: Linux with systemd",
);
});
it("reports a newer installed service without recommending latest", () => {
const output = formatServiceStatus(
{ ...status, current: false, installedVersion: "0.0.32-nightly.1" },
"0.0.31",
);
assert.include(output, "[email protected] (newer than this [email protected] CLI)");
assert.include(output, "npx [email protected] service update");
assert.notInclude(output, "npx t3@latest service update");
});
it("refuses service downgrades unless explicitly allowed", () => {
const refusal = serviceDowngradeRefusal({
installedVersion: "0.0.32-nightly.1",
targetVersion: "0.0.31",
allowDowngrade: false,
});
assert.instanceOf(refusal, Error);
assert.deepInclude(refusal, {
_tag: "ServiceDowngradeRefusedError",
installedVersion: "0.0.32-nightly.1",
targetVersion: "0.0.31",
});
assert.isNull(
serviceDowngradeRefusal({
installedVersion: "0.0.32-nightly.1",
targetVersion: "0.0.31",
allowDowngrade: true,
}),
);
assert.isNull(
serviceDowngradeRefusal({
installedVersion: undefined,
targetVersion: "0.0.31",
allowDowngrade: false,
}),
);
});
+89 -9
View File
@@ -1,11 +1,13 @@
import * as Console from "effect/Console";
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
import * as Schema from "effect/Schema";
import * as Terminal from "effect/Terminal";
import { Command, GlobalFlag, Prompt } from "effect/unstable/cli";
import { Command, Flag, GlobalFlag, Prompt } from "effect/unstable/cli";
import packageJson from "../../package.json" with { type: "json" };
import * as BootService from "../cloud/bootService.ts";
import { compareExactServiceVersions } from "../cloud/serviceProtocol.ts";
import type * as ServerConfig from "../config.ts";
import * as ProcessRunner from "../processRunner.ts";
import { projectLocationFlags, resolveCliAuthConfig } from "./config.ts";
@@ -28,13 +30,50 @@ export type ServiceReconcileResult =
readonly plan: BootService.BootServicePlan;
};
export class ServiceDowngradeRefusedError extends Schema.TaggedErrorClass<ServiceDowngradeRefusedError>()(
"ServiceDowngradeRefusedError",
{
installedVersion: Schema.String,
targetVersion: Schema.String,
},
) {
override get message(): string {
return `Refusing to replace t3@${this.installedVersion} with older t3@${this.targetVersion}. Re-run with --allow-downgrade to continue.`;
}
}
export function serviceDowngradeRefusal(input: {
readonly installedVersion: string | undefined;
readonly targetVersion: string;
readonly allowDowngrade: boolean;
}): ServiceDowngradeRefusedError | null {
return input.installedVersion !== undefined &&
!input.allowDowngrade &&
compareExactServiceVersions(input.targetVersion, input.installedVersion) < 0
? new ServiceDowngradeRefusedError({
installedVersion: input.installedVersion,
targetVersion: input.targetVersion,
})
: null;
}
/** Install, update, or repair the service using the CLI version running this command. */
export const reconcileService = Effect.fn("cli.service.reconcile")(function* () {
export const reconcileService = Effect.fn("cli.service.reconcile")(function* (options?: {
readonly allowDowngrade?: boolean;
}) {
const service = yield* BootService.BootService;
const status = yield* service.status;
if (status.installed && status.current) {
return { changed: false, status } satisfies ServiceReconcileResult;
}
const downgradeRefusal = serviceDowngradeRefusal({
installedVersion: status.installedVersion,
targetVersion: packageJson.version,
allowDowngrade: options?.allowDowngrade === true,
});
if (downgradeRefusal !== null) {
return yield* downgradeRefusal;
}
const plan = yield* service.install;
return {
changed: true,
@@ -53,9 +92,23 @@ export function formatServiceStatus(
if (!status.installed) {
return "T3 Code service\n Status: not installed\n Next: Run `t3 service install`.";
}
const installedVersion = status.installedVersion ?? cliVersion;
if (
!status.current &&
status.installedVersion !== undefined &&
compareExactServiceVersions(status.installedVersion, cliVersion) > 0
) {
return [
"T3 Code service",
` Status: installed · t3@${installedVersion} (newer than this t3@${cliVersion} CLI)`,
` Unit: ${status.unitPath}`,
` Logs: ${status.logPath}`,
` Next: Use \`npx t3@${installedVersion} service update\` to repair it, or pass \`--allow-downgrade\` explicitly.`,
].join("\n");
}
return [
"T3 Code service",
` Status: ${status.current ? `installed · t3@${cliVersion}` : "needs an update or repair"}`,
` Status: ${status.current ? `installed · t3@${installedVersion}` : "needs an update or repair"}`,
` Unit: ${status.unitPath}`,
` Logs: ${status.logPath}`,
...(status.current ? [] : [" Next: Run `npx t3@latest service update`."]),
@@ -71,13 +124,21 @@ const runServiceCommand = Effect.fn("cli.service.run")(function* <A, E>(
return yield* run.pipe(Effect.provide(bootServiceLayer(config)));
});
const serviceInstallCommand = Command.make("install", projectLocationFlags).pipe(
const serviceReconcileFlags = {
...projectLocationFlags,
allowDowngrade: Flag.boolean("allow-downgrade").pipe(
Flag.withDescription("Allow replacing a newer installed service with this older CLI version."),
Flag.withDefault(false),
),
};
const serviceInstallCommand = Command.make("install", serviceReconcileFlags).pipe(
Command.withDescription("Install T3 Code as a background service for this user."),
Command.withHandler((flags) =>
runServiceCommand(
flags,
Effect.gen(function* () {
const result = yield* reconcileService();
const result = yield* reconcileService({ allowDowngrade: flags.allowDowngrade });
if (!result.changed) {
yield* Console.log(
`T3 Code service is already installed with t3@${packageJson.version}.`,
@@ -92,7 +153,7 @@ const serviceInstallCommand = Command.make("install", projectLocationFlags).pipe
),
);
const serviceUpdateCommand = Command.make("update", projectLocationFlags).pipe(
const serviceUpdateCommand = Command.make("update", serviceReconcileFlags).pipe(
Command.withDescription(
"Update or repair the background service using this CLI version. Use `npx t3@latest service update` for the latest release.",
),
@@ -100,7 +161,7 @@ const serviceUpdateCommand = Command.make("update", projectLocationFlags).pipe(
runServiceCommand(
flags,
Effect.gen(function* () {
const result = yield* reconcileService();
const result = yield* reconcileService({ allowDowngrade: flags.allowDowngrade });
if (!result.changed) {
yield* Console.log(`T3 Code service is already using t3@${packageJson.version}.`);
return;
@@ -144,7 +205,8 @@ const serviceStatusCommand = Command.make("status", projectLocationFlags).pipe(
export const offerServiceDuringOnboarding = Effect.gen(function* () {
const service = yield* BootService.BootService;
const { supported, installed, current } = yield* service.status;
const status = yield* service.status;
const { supported, installed, current } = status;
if (!supported) {
return false;
}
@@ -152,6 +214,18 @@ export const offerServiceDuringOnboarding = Effect.gen(function* () {
yield* Console.log("T3 Code is already set up to run in the background on this machine.");
return true;
}
if (
installed &&
status.installedVersion !== undefined &&
compareExactServiceVersions(status.installedVersion, packageJson.version) > 0
) {
yield* Console.log(
`A newer t3@${status.installedVersion} background service is installed; leaving it unchanged.`,
);
// This CLI cannot verify that the newer unit is healthy, so keep the
// manual `serve` fallback visible instead of claiming background readiness.
return false;
}
const wanted = yield* Prompt.run(
Prompt.confirm({
message: installed
@@ -174,7 +248,11 @@ export const offerServiceDuringOnboarding = Effect.gen(function* () {
});
export const recoverServiceOnboardingOffer = <R>(
offer: Effect.Effect<boolean, BootService.BootServiceError | Terminal.QuitError, R>,
offer: Effect.Effect<
boolean,
BootService.BootServiceError | ServiceDowngradeRefusedError | Terminal.QuitError,
R
>,
) =>
offer.pipe(
Effect.catchTags({
@@ -187,6 +265,8 @@ export const recoverServiceOnboardingOffer = <R>(
Console.warn(`Background setup did not finish: ${error.message}`).pipe(Effect.as(false)),
BootServiceUpdatePendingError: (error) =>
Console.warn(`Background setup did not finish: ${error.message}`).pipe(Effect.as(false)),
ServiceDowngradeRefusedError: (error) =>
Console.warn(`Background setup did not finish: ${error.message}`).pipe(Effect.as(false)),
}),
);
+20 -1
View File
@@ -105,7 +105,10 @@ it.layer(NodeServices.layer)("boot service install", (it) => {
activeVersion: "1.2.3",
});
expect(yield* fs.readFileString(plan.launcherPath)).toBe("export {};\n");
expect((yield* service.status).current).toBe(true);
expect(yield* service.status).toMatchObject({
current: true,
installedVersion: "1.2.3",
});
// @effect-diagnostics-next-line preferSchemaOverJson:off - fixed launcher-owned test document.
const pendingState = JSON.stringify({
protocol: SERVICE_LAUNCHER_PROTOCOL,
@@ -137,6 +140,22 @@ it.layer(NodeServices.layer)("boot service install", (it) => {
}),
);
it.effect("reports the installed version across launcher protocol revisions", () =>
Effect.gen(function* () {
const { service, fs, statePath } = yield* makeHarness();
yield* service.install;
yield* fs.writeFileString(
statePath,
`{"protocol":${String(SERVICE_LAUNCHER_PROTOCOL + 1)},"activeVersion":"9.9.9"}`,
);
expect(yield* service.status).toMatchObject({
current: false,
installedVersion: "9.9.9",
});
}),
);
it.effect("restarts an installed service when repair fails", () =>
Effect.gen(function* () {
const { service, commands, control } = yield* makeHarness();
+6
View File
@@ -21,6 +21,7 @@ import {
SERVICE_LAUNCHER_PROTOCOL,
SERVICE_STATE_FILE,
parseServiceState,
serviceStateActiveVersion,
serviceStateHasPendingUpdate,
type ServiceState,
} from "./serviceProtocol.ts";
@@ -130,6 +131,7 @@ export interface BootServiceStatus {
readonly supported: boolean;
readonly installed: boolean;
readonly current: boolean;
readonly installedVersion?: string;
readonly unitPath: string;
readonly logPath: string;
}
@@ -390,9 +392,13 @@ export const make = Effect.fn("cloud.boot_service.make")(function* (input: {
fs.readFileString(statePath).pipe(Effect.option),
]);
const state = Option.isSome(stateText) ? parseServiceState(stateText.value) : undefined;
const installedVersion = Option.isSome(stateText)
? serviceStateActiveVersion(stateText.value)
: undefined;
return {
supported: true,
installed: true,
...(installedVersion === undefined ? {} : { installedVersion }),
current:
unit === renderBootServiceUnit(plan) &&
launcherExists &&
+149 -9
View File
@@ -19,12 +19,19 @@ import * as ServerEnvironment from "../environment/ServerEnvironment.ts";
import { CLOUD_CLI_DESIRED_LINK_SECRET } from "./CliState.ts";
import * as CliTokenManager from "./CliTokenManager.ts";
import type { RelayLinkProofRequest } from "@t3tools/contracts/relay";
import { CLOUD_ENDPOINT_RUNTIME_CONFIG, RELAY_URL_SECRET } from "./config.ts";
import {
CLOUD_ENDPOINT_RUNTIME_CONFIG,
CLOUD_LINKED_USER_ID,
decodeRuntimeConfig,
RELAY_ENVIRONMENT_CREDENTIAL_SECRET,
RELAY_URL_SECRET,
} from "./config.ts";
import {
consumeCloudReplayGuards,
isSupportedLinkProviderKind,
linkProofScopes,
reconcileDesiredCloudLink,
managedEndpointOriginsEqual,
reconcileCloudLinkOnStartup,
releaseManagedTunnelOnShutdown,
} from "./http.ts";
import * as ManagedEndpointRuntime from "./ManagedEndpointRuntime.ts";
@@ -79,6 +86,18 @@ it("preserves messages surfaced by cloud 500 responses", () => {
]);
});
it("compares managed endpoint origins without hostname formatting drift", () => {
const desired = { localHttpHost: "127.0.0.1", localHttpPort: 7331 } as const;
expect(managedEndpointOriginsEqual(undefined, desired)).toBe(false);
expect(
managedEndpointOriginsEqual({ localHttpHost: "[127.0.0.1]", localHttpPort: 7331 }, desired),
).toBe(true);
expect(
managedEndpointOriginsEqual({ localHttpHost: "127.0.0.1", localHttpPort: 7332 }, desired),
).toBe(false);
});
describe("consumeCloudReplayGuards", () => {
it.effect("reports already-created guards as replay conflicts", () =>
Effect.gen(function* () {
@@ -172,20 +191,25 @@ describe("relay request tracing", () => {
);
});
describe("reconcileDesiredCloudLink", () => {
it.effect("requires stored CLI authorization without exposing an HTTP endpoint", () =>
describe("reconcileCloudLinkOnStartup", () => {
it.effect("restores a desired CLI link before attempting origin repair", () =>
Effect.gen(function* () {
const error = yield* Effect.flip(reconcileDesiredCloudLink("http://127.0.0.1:3774"));
const error = yield* Effect.flip(reconcileCloudLinkOnStartup("http://127.0.0.1:3774"));
expect(error).toMatchObject({
_tag: "EnvironmentHttpUnauthorizedError",
message: "Run `t3 connect link` to authorize this environment.",
});
}).pipe(
Effect.provideService(
ServerSecretStore.ServerSecretStore,
makeSecretStore(unusedSecretStoreOperation),
),
Effect.provideService(ServerSecretStore.ServerSecretStore, {
...makeSecretStore(unusedSecretStoreOperation),
get: (name) =>
Effect.succeed(
name === CLOUD_CLI_DESIRED_LINK_SECRET
? Option.some(new TextEncoder().encode("managed"))
: Option.none(),
),
}),
Effect.provideService(
ServerEnvironment.ServerEnvironment,
ServerEnvironment.ServerEnvironment.of({
@@ -222,6 +246,122 @@ describe("reconcileDesiredCloudLink", () => {
);
});
describe("reconcileManagedEndpointOrigin", () => {
it.effect("uses the environment credential and persists the reconciled origin", () => {
const initialSecrets: ReadonlyArray<readonly [string, string]> = [
[
CLOUD_ENDPOINT_RUNTIME_CONFIG,
JSON.stringify({
providerKind: "cloudflare_tunnel",
connectorToken: "old-connector-token",
}),
],
[RELAY_URL_SECRET, "https://relay.example.test"],
[RELAY_ENVIRONMENT_CREDENTIAL_SECRET, "environment-credential"],
[CLOUD_LINKED_USER_ID, "user_123"],
];
const values = new Map<string, Uint8Array>(
initialSecrets.map(([name, value]) => [name, new TextEncoder().encode(value)] as const),
);
const store: ServerSecretStore.ServerSecretStore["Service"] = {
get: (name) => Effect.sync(() => Option.fromNullishOr(values.get(name))),
set: (name, value) =>
Effect.sync(() => {
values.set(name, value);
}),
create: unusedSecretStoreOperation,
getOrCreateRandom: unusedSecretStoreOperation,
remove: unusedSecretStoreOperation,
};
const requests: Array<HttpClientRequest.HttpClientRequest> = [];
const applied: Array<unknown> = [];
return Effect.gen(function* () {
expect(yield* reconcileCloudLinkOnStartup("http://127.0.0.1:4555")).toBe(true);
expect(requests).toHaveLength(1);
expect(requests[0]?.url).toBe(
"https://relay.example.test/v1/environments/env_123/managed-endpoint/reconcile",
);
expect(requests[0]?.headers.authorization).toBe("Bearer environment-credential");
expect(applied).toEqual([
{
providerKind: "cloudflare_tunnel",
connectorToken: "fresh-connector-token",
tunnelId: "tunnel-123",
tunnelName: "tunnel-name",
origin: { localHttpHost: "127.0.0.1", localHttpPort: 4555 },
},
]);
const persisted = decodeRuntimeConfig(
new TextDecoder().decode(values.get(CLOUD_ENDPOINT_RUNTIME_CONFIG)),
);
expect(Option.getOrNull(persisted)?.origin).toEqual({
localHttpHost: "127.0.0.1",
localHttpPort: 4555,
});
}).pipe(
Effect.provideService(ServerSecretStore.ServerSecretStore, store),
Effect.provideService(
ServerEnvironment.ServerEnvironment,
ServerEnvironment.ServerEnvironment.of({
getEnvironmentId: Effect.succeed(EnvironmentId.make("env_123")),
getDescriptor: unusedSecretStoreOperation(),
}),
),
Effect.provideService(
ManagedEndpointRuntime.CloudManagedEndpointRuntime,
ManagedEndpointRuntime.CloudManagedEndpointRuntime.of({
applyConfig: (config) =>
Effect.sync(() => {
applied.push(config);
return {
status: "running",
providerKind: "cloudflare_tunnel",
pid: 123,
} as const;
}),
}),
),
Effect.provideService(
EnvironmentAuth.EnvironmentAuth,
EnvironmentAuth.EnvironmentAuth.of({} as EnvironmentAuth.EnvironmentAuth["Service"]),
),
Effect.provideService(
CliTokenManager.CloudCliTokenManager,
CliTokenManager.CloudCliTokenManager.of({
get: unusedSecretStoreOperation(),
getExisting: unusedSecretStoreOperation(),
hasCredential: unusedSecretStoreOperation(),
store: unusedSecretStoreOperation,
clear: unusedSecretStoreOperation(),
}),
),
Effect.provideService(
HttpClient.HttpClient,
HttpClient.make((request) =>
Effect.sync(() => {
requests.push(request);
return HttpClientResponse.fromWeb(
request,
Response.json({
endpointRuntime: {
providerKind: "cloudflare_tunnel",
connectorToken: "fresh-connector-token",
tunnelId: "tunnel-123",
tunnelName: "tunnel-name",
origin: { localHttpHost: "127.0.0.1", localHttpPort: 4555 },
},
}),
);
}),
),
),
Effect.provide(NodeServices.layer),
);
});
});
describe("releaseManagedTunnelOnShutdown", () => {
const cliToken: CliTokenManager.PersistedToken = {
accessToken: "cli-access-token",
+116 -5
View File
@@ -22,6 +22,7 @@ import {
RelayEnvironmentConfigRequest,
RelayEnvironmentLinkChallengeResponse,
RelayEnvironmentLinkResponse,
RelayManagedEndpointReconcileResponse,
RelayEnvironmentMintResponseProofPayload,
type RelayEnvironmentMintResponse as RelayEnvironmentMintResponseShape,
RelayEnvironmentLinkProof,
@@ -62,6 +63,7 @@ import {
CLOUD_ENDPOINT_RUNTIME_CONFIG,
CLOUD_LINKED_USER_ID,
CLOUD_MINT_PUBLIC_KEY,
decodeRuntimeConfig,
encodeEndpointRuntimeConfigJson,
PUBLISH_AGENT_ACTIVITY_SECRET,
RELAY_ENVIRONMENT_CREDENTIAL_SECRET,
@@ -627,6 +629,115 @@ export const reconcileDesiredCloudLink = Effect.fn("environment.cloud.reconcileD
},
);
function managedEndpointOriginFromLocalUrl(localUrl: URL): RelayManagedEndpointOrigin {
return {
localHttpHost: localUrl.hostname,
localHttpPort: endpointRequestPort(localUrl),
};
}
export function managedEndpointOriginsEqual(
left: RelayManagedEndpointOrigin | undefined,
right: RelayManagedEndpointOrigin,
): boolean {
return (
left !== undefined &&
normalizeHostname(left.localHttpHost) === normalizeHostname(right.localHttpHost) &&
left.localHttpPort === right.localHttpPort
);
}
const reconcileManagedEndpointOriginWith = Effect.fn(
"environment.cloud.reconcileManagedEndpointOriginWith",
)(function* (dependencies: CloudHttpDependencies, localOrigin: string) {
const localUrl = yield* Effect.try({
try: () => new URL(localOrigin),
catch: () =>
new EnvironmentHttpBadRequestError({
message: "Could not resolve local environment origin.",
}),
});
if (localUrl.origin !== localOrigin) {
return yield* new EnvironmentHttpBadRequestError({
message: "Could not resolve local environment origin.",
});
}
const desiredOrigin = managedEndpointOriginFromLocalUrl(localUrl);
const storedConfigBytes = yield* dependencies.secrets.get(CLOUD_ENDPOINT_RUNTIME_CONFIG);
const storedConfig = Option.isSome(storedConfigBytes)
? decodeRuntimeConfig(bytesToString(storedConfigBytes.value))
: Option.none();
if (Option.isSome(storedConfigBytes) && Option.isNone(storedConfig)) {
return yield* new EnvironmentHttpInternalServerError({
message: "Stored managed endpoint runtime configuration is invalid.",
});
}
const config = Option.getOrNull(storedConfig);
const desiredManagedLink =
(yield* readCliDesiredCloudLink) && (yield* readCliDesiredLinkMode) === "managed";
if (config?.providerKind !== "cloudflare_tunnel" && !desiredManagedLink) {
return false;
}
if (managedEndpointOriginsEqual(config?.origin, desiredOrigin)) {
return false;
}
const relayUrl = yield* dependencies.secrets.get(RELAY_URL_SECRET);
const environmentCredential = yield* dependencies.secrets.get(
RELAY_ENVIRONMENT_CREDENTIAL_SECRET,
);
const cloudUserId = yield* dependencies.secrets.get(CLOUD_LINKED_USER_ID);
if (
Option.isNone(relayUrl) ||
Option.isNone(environmentCredential) ||
Option.isNone(cloudUserId)
) {
return yield* new EnvironmentHttpUnauthorizedError({
message: "This managed environment is missing its T3 Connect credentials. Link it again.",
});
}
const environmentId = yield* dependencies.environment.getEnvironmentId;
const response = yield* relayClientRequest(dependencies, {
url: `${bytesToString(relayUrl.value)}/v1/environments/${encodeURIComponent(environmentId)}/managed-endpoint/reconcile`,
token: bytesToString(environmentCredential.value),
payload: {
cloudUserId: bytesToString(cloudUserId.value),
origin: desiredOrigin,
},
schema: RelayManagedEndpointReconcileResponse,
});
const status = yield* dependencies.endpointRuntime.applyConfig(response.endpointRuntime);
if (status.status !== "running") {
return yield* new EnvironmentCloudEndpointUnavailableError({
message: "Managed endpoint runtime could not be started after origin reconciliation.",
endpointRuntimeStatus: status,
});
}
const encoded = yield* encodeEndpointRuntimeConfigJson(response.endpointRuntime);
yield* dependencies.secrets.set(CLOUD_ENDPOINT_RUNTIME_CONFIG, stringToBytes(encoded));
return true;
});
export const reconcileManagedEndpointOrigin = Effect.fn(
"environment.cloud.reconcileManagedEndpointOrigin",
)(function* (localOrigin: string) {
return yield* reconcileManagedEndpointOriginWith(yield* cloudHttpDependencies, localOrigin);
});
/** Restores CLI-desired links first, then repairs origin drift for links that
are owned by web or mobile and therefore have no CLI desired-link marker. */
export const reconcileCloudLinkOnStartup = Effect.fn(
"environment.cloud.reconcileCloudLinkOnStartup",
)(function* (localOrigin: string) {
const dependencies = yield* cloudHttpDependencies;
if (yield* readCliDesiredCloudLink) {
yield* reconcileDesiredCloudLinkWith(dependencies, localOrigin);
return true;
}
return yield* reconcileManagedEndpointOriginWith(dependencies, localOrigin);
});
// Cloudflare bills per provisioned tunnel, so an environment that goes offline
// must not leave its tunnel behind. Releasing deletes only the tunnel — the
// relay keeps the link and its hostname reservation, and the next startup's
@@ -641,11 +752,11 @@ export const releaseManagedTunnelOnShutdown = Effect.fn(
if (Option.isNone(runtimeConfig)) {
return false;
}
// Only CLI-desired managed links release on shutdown, because the startup
// reconcile that provisions the replacement tunnel only runs for them. A
// link installed by a web/mobile client comes back after a restart by
// reapplying the stored connector token — it has no boot-time re-provision
// path — so its tunnel must survive the restart. (Unlink still deletes it.)
// Only CLI-desired managed links release on shutdown. Their desired-link
// marker lets startup re-provision after this function removes the dead
// runtime config. Web/mobile links have no equivalent marker, so they keep
// the tunnel and stored connector token across restarts. (Unlink still
// deletes it.)
if (!(yield* readCliDesiredCloudLink) || (yield* readCliDesiredLinkMode) !== "managed") {
return false;
}
+14
View File
@@ -180,6 +180,20 @@ export function serviceStateHasPendingUpdate(value: string): boolean {
}
}
/** Reads the active version across launcher protocol revisions for downgrade protection. */
export function serviceStateActiveVersion(value: string): string | undefined {
try {
const parsed: unknown = JSON.parse(value);
return isRecord(parsed) &&
typeof parsed.activeVersion === "string" &&
isExactServiceVersion(parsed.activeVersion)
? parsed.activeVersion
: undefined;
} catch {
return undefined;
}
}
export function decodeServiceLauncherContext(value: string): ServiceLauncherContext | undefined {
let parsed: unknown;
try {
+7 -12
View File
@@ -83,13 +83,12 @@ import * as ServerSecretStore from "./auth/ServerSecretStore.ts";
import * as EnvironmentAuth from "./auth/EnvironmentAuth.ts";
import {
connectHttpApiLayer,
reconcileDesiredCloudLink,
reconcileCloudLinkOnStartup,
releaseManagedTunnelOnShutdown,
} from "./cloud/http.ts";
import { serverRelayBrokerTracingLayer } from "./cloud/relayTracing.ts";
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 ServiceLauncherClient from "./cloud/serviceLauncherClient.ts";
import * as ProcessDiagnostics from "./diagnostics/ProcessDiagnostics.ts";
@@ -579,17 +578,11 @@ export const makeServerLayer = Layer.unwrap(
Effect.asVoid,
),
);
if (!(yield* CloudCliState.readCliDesiredCloudLink)) return;
const server = yield* HttpServer.HttpServer;
const address = server.address;
if (typeof address === "string" || !("port" in address)) return;
// 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(
yield* Effect.sleep("250 millis").pipe(
Effect.andThen(reconcileCloudLinkOnStartup(`http://127.0.0.1:${address.port}`)),
Effect.retry({
while: (error) =>
error._tag !== "EnvironmentHttpBadRequestError" &&
@@ -602,9 +595,11 @@ export const makeServerLayer = Layer.unwrap(
Schedule.upTo({ duration: "10 minutes" }),
),
}),
Effect.tap(() => Effect.logInfo("T3 Connect desired link reconciled on startup")),
Effect.tap((reconciled) =>
reconciled ? Effect.logInfo("T3 Connect link reconciled on startup") : Effect.void,
),
Effect.catch((cause) =>
Effect.logWarning("Failed to reconcile T3 Connect desired link on startup", {
Effect.logWarning("Failed to reconcile T3 Connect link on startup", {
cause,
}),
),
+11 -5
View File
@@ -7,6 +7,7 @@ import {
ProviderInstanceId,
ThreadId,
} from "@t3tools/contracts";
import { HostProcessEnvironment } from "@t3tools/shared/hostProcess";
import * as Console from "effect/Console";
import * as Context from "effect/Context";
import * as Crypto from "effect/Crypto";
@@ -36,11 +37,14 @@ import * as EnvironmentAuth from "./auth/EnvironmentAuth.ts";
import * as ProviderSessionReaper from "./provider/Services/ProviderSessionReaper.ts";
import { forkParked } from "./serverActivation.ts";
import * as ServiceLauncherClient from "./cloud/serviceLauncherClient.ts";
import { BOOT_SERVICE_UNIT_ENV, BOOT_SERVICE_UNIT_FILE } from "./cloud/bootService.ts";
import {
formatHeadlessServeOutput,
formatManagedHeadlessServeOutput,
formatHostForUrl,
isWildcardHost,
issueHeadlessServeAccessInfo,
resolveHeadlessServeConnectionString,
} from "./startupAccess.ts";
export class ServerRuntimeStartupError extends Schema.TaggedErrorClass<ServerRuntimeStartupError>()(
@@ -307,6 +311,9 @@ export const make = (options?: StartupOptions) =>
const serverEnvironment = yield* ServerEnvironment.ServerEnvironment;
const crypto = yield* Crypto.Crypto;
const launcher = yield* ServiceLauncherClient.ServiceLauncherClient;
const hostEnvironment = yield* HostProcessEnvironment;
const managedServiceStartup =
launcher.managed || hostEnvironment[BOOT_SERVICE_UNIT_ENV] === BOOT_SERVICE_UNIT_FILE;
const commandGate = yield* makeCommandGate;
const httpListening = yield* Deferred.make<void>();
@@ -406,11 +413,10 @@ export const make = (options?: StartupOptions) =>
Effect.ignoreCause({ log: true }),
);
if (serverConfig.startupPresentation === "headless") {
const accessInfo = yield* issueHeadlessServeAccessInfo();
yield* runStartupPhase(
"headless.output",
Console.log(formatHeadlessServeOutput(accessInfo)),
);
const output = managedServiceStartup
? formatManagedHeadlessServeOutput(yield* resolveHeadlessServeConnectionString)
: formatHeadlessServeOutput(yield* issueHeadlessServeAccessInfo());
yield* runStartupPhase("headless.output", Console.log(output));
} else {
const startupBrowserTarget = yield* resolveStartupBrowserTarget;
if (serverConfig.mode !== "desktop") {
+12
View File
@@ -3,6 +3,7 @@ import { assert, expect, it } from "@effect/vitest";
import {
buildPairingUrl,
formatHeadlessServeOutput,
formatManagedHeadlessServeOutput,
renderTerminalQrCode,
resolveHeadlessConnectionHost,
resolveHeadlessConnectionString,
@@ -77,3 +78,14 @@ it("formats headless serve output with the connection string, token, pairing url
expect(output).toContain("Pairing URL: http://192.168.1.42:3773/pair#token=PAIRCODE");
assert.isTrue(output.includes("█") || output.includes("▀") || output.includes("▄"));
});
it("formats managed service output without mintable pairing material", () => {
const output = formatManagedHeadlessServeOutput("http://127.0.0.1:3773");
expect(output).toContain("Connection string: http://127.0.0.1:3773");
expect(output).toContain("Run `npx t3 pair` to create a pairing URL.");
expect(output).not.toContain("Token:");
expect(output).not.toContain("Pairing URL:");
expect(output).not.toContain("#token=");
assert.isFalse(output.includes("█") || output.includes("▀") || output.includes("▄"));
});
+15 -3
View File
@@ -130,14 +130,26 @@ export const formatHeadlessServeOutput = (accessInfo: HeadlessServeAccessInfo):
"",
].join("\n");
export const issueHeadlessServeAccessInfo = Effect.fn("issueHeadlessServeAccessInfo")(function* () {
export const formatManagedHeadlessServeOutput = (connectionString: string): string =>
[
"T3 Code server is ready.",
`Connection string: ${connectionString}`,
"Run `npx t3 pair` to create a pairing URL.",
"",
].join("\n");
export const resolveHeadlessServeConnectionString = Effect.gen(function* () {
const serverConfig = yield* ServerConfig;
const httpServer = yield* HttpServer.HttpServer;
const serverAuth = yield* EnvironmentAuth.EnvironmentAuth;
const connectionString = resolveHeadlessConnectionString(
return resolveHeadlessConnectionString(
serverConfig.host,
resolveListeningPort(httpServer.address, serverConfig.port),
);
});
export const issueHeadlessServeAccessInfo = Effect.fn("issueHeadlessServeAccessInfo")(function* () {
const serverAuth = yield* EnvironmentAuth.EnvironmentAuth;
const connectionString = yield* resolveHeadlessServeConnectionString;
const issued = yield* serverAuth.issueStartupPairingCredential();
return {
-43
View File
@@ -1,7 +1,6 @@
import { describe, expect, it } from "vite-plus/test";
import {
areFontAdvancesMonospace,
clampCodeFontSize,
clampInterfaceFontSize,
clampPromptFontSize,
@@ -10,22 +9,8 @@ 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();
@@ -69,34 +54,6 @@ 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);
+5 -39
View File
@@ -25,22 +25,6 @@ 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 "";
@@ -181,22 +165,6 @@ 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
@@ -214,15 +182,13 @@ 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.
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;
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;
} catch {
return true;
}
+67 -1
View File
@@ -299,10 +299,12 @@ import {
} from "./ui/alert-dialog";
import { Tooltip, TooltipPopup, TooltipTrigger } from "./ui/tooltip";
import { ServerUpdateAction, ServerUpdateProgress } from "./ServerUpdateAction";
import { APP_STAGE_LABEL, APP_VERSION } from "../branding";
import {
buildVersionMismatchDismissalKey,
dismissVersionMismatch,
isVersionMismatchDismissed,
resolveCompatibilityChannelMismatch,
resolveServerConfigVersionMismatch,
resolveServerSelfUpdateCapability,
serverUpdateGuidance,
@@ -1908,6 +1910,14 @@ function ChatViewContent(props: ChatViewProps) {
unavailableConnection !== null &&
(unavailableConnection.phase === "connecting" ||
unavailableConnection.phase === "reconnecting");
const compatibilityChannelMismatch =
unavailableConnection?.blockedReason === "unsupported"
? resolveCompatibilityChannelMismatch({
clientVersion: APP_VERSION,
clientStageLabel: APP_STAGE_LABEL,
serverVersion: unavailableConnection.serverVersion,
})
: null;
// Reconnecting to a version-skewed server with no update in flight
// usually means the server is restarting mid-update and a refresh wiped
// the in-memory update state. Fold the reconnect and version banners
@@ -1934,6 +1944,59 @@ function ChatViewContent(props: ChatViewProps) {
title: `${unavailableConnection.phase === "connecting" ? "Connecting" : "Reconnecting"} to ${activeEnvironmentUnavailableState.label}`,
description: "It may be finishing an update. One moment.",
});
} else if (compatibilityChannelMismatch) {
items.push({
id: `environment-unavailable:${activeEnvironmentUnavailableState.environmentId}`,
variant: "error",
icon: <TriangleAlertIcon />,
title: "Client and server channels differ",
description: (
<div className="mt-1 min-w-0 space-y-2">
<p>
{compatibilityChannelMismatch.newerSide === "server"
? `This client is older. Update it to match the ${compatibilityChannelMismatch.serverChannel} server.`
: compatibilityChannelMismatch.newerSide === "client"
? `The server is older. Update it to match this ${compatibilityChannelMismatch.clientChannel} client.`
: "Pick Stable or Nightly for both installations."}
</p>
<div className="grid grid-cols-[3rem_minmax(0,1fr)_auto] gap-x-3 gap-y-1.5 border-y border-current/15 py-2 text-xs">
<span className="text-muted-foreground">Client</span>
<code className="truncate text-foreground">
{compatibilityChannelMismatch.clientVersion}
</code>
<span className="font-medium text-foreground">
{compatibilityChannelMismatch.clientChannel}
</span>
<span className="text-muted-foreground">Server</span>
<code className="truncate text-foreground">
{compatibilityChannelMismatch.serverVersion}
</code>
<span className="font-medium text-foreground">
{compatibilityChannelMismatch.serverChannel}
</span>
</div>
</div>
),
actions: (
<>
{compatibilityChannelMismatch.newerSide === "client" ? (
<ServerUpdateAction
environmentId={activeEnvironmentUnavailableState.environmentId}
serverLabel={`${activeEnvironmentUnavailableState.label} server`}
selfUpdate={null}
targetVersion={compatibilityChannelMismatch.clientVersion}
/>
) : null}
<Button
size="xs"
variant="outline"
onClick={() => void navigate({ to: "/settings/connections" })}
>
Connections
</Button>
</>
),
});
} else {
items.push({
id: `environment-unavailable:${activeEnvironmentUnavailableState.environmentId}`,
@@ -1972,7 +2035,10 @@ function ChatViewContent(props: ChatViewProps) {
serverUpdateEnvironmentId &&
!reconnectingThroughVersionSkew &&
(serverUpdateState.status !== "idle" ||
(showVersionMismatchBanner && versionMismatch && versionMismatchDismissKey))
(compatibilityChannelMismatch === null &&
showVersionMismatchBanner &&
versionMismatch &&
versionMismatchDismissKey))
) {
const updateInProgress = serverUpdateState.status === "running";
const updateFailed = serverUpdateState.status === "failed";
@@ -18,7 +18,6 @@ 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,
@@ -58,7 +57,6 @@ 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";
@@ -66,7 +64,6 @@ 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;
@@ -244,7 +241,6 @@ export function shouldHandleTerminalExit(
}
interface TerminalViewportProps {
advancedTypography: boolean;
threadRef: ScopedThreadRef;
threadId: ThreadId;
terminalId: string;
@@ -268,7 +264,6 @@ interface TerminalLaunchLocation {
}
export function TerminalViewport({
advancedTypography,
threadRef,
threadId,
terminalId,
@@ -317,12 +312,10 @@ export function TerminalViewport({
onAddTerminalContext(selection);
});
const readTerminalLabel = useEffectEvent(() => terminalLabel);
const terminalFontFamily = useClientSettings((settings) =>
resolveTerminalFontPreference({
advanced: advancedTypography,
code: settings.fontFamilyCode,
terminal: settings.fontFamilyTerminal,
}),
// 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 terminalFontSize = useClientSettings((settings) => settings.fontSizeTerminal);
const terminalFontRef = useRef({ family: terminalFontFamily, size: terminalFontSize });
@@ -928,11 +921,6 @@ 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,
@@ -1369,7 +1357,6 @@ export default function ThreadTerminalDrawer({
>
<div className="h-full p-1">
<TerminalViewport
advancedTypography={advancedTypography}
threadRef={threadRef}
threadId={threadId}
terminalId={terminalId}
@@ -1397,7 +1384,6 @@ export default function ThreadTerminalDrawer({
) : (
<div className="h-full p-1">
<TerminalViewport
advancedTypography={advancedTypography}
key={resolvedActiveTerminalId}
threadRef={threadRef}
threadId={threadId}
+9 -32
View File
@@ -108,24 +108,13 @@ import { basenameOfPath } from "../../pierre-icons";
import { cn, randomUUID } from "~/lib/utils";
import { Separator } from "../ui/separator";
type ComposerCommandMenuPosition = {
bottom: number;
left: number;
maxHeight: number;
width: number;
};
function composerCommandMenuPositionsEqual(
a: ComposerCommandMenuPosition,
b: ComposerCommandMenuPosition,
): boolean {
return (
a.bottom === b.bottom && a.left === b.left && a.maxHeight === b.maxHeight && a.width === b.width
);
}
function ComposerCommandMenuLayer(props: { anchor: HTMLElement | null; children: ReactNode }) {
const [position, setPosition] = useState<ComposerCommandMenuPosition | null>(null);
const [position, setPosition] = useState<{
bottom: number;
left: number;
maxHeight: number;
width: number;
} | null>(null);
useLayoutEffect(() => {
const anchor = props.anchor;
@@ -136,15 +125,12 @@ function ComposerCommandMenuLayer(props: { anchor: HTMLElement | null; children:
const updatePosition = () => {
const rect = anchor.getBoundingClientRect();
const next = {
setPosition({
bottom: window.innerHeight - rect.top + 8,
left: rect.left,
maxHeight: Math.max(96, rect.top - 24),
width: rect.width,
};
setPosition((current) =>
current && composerCommandMenuPositionsEqual(current, next) ? current : next,
);
});
};
updatePosition();
@@ -153,16 +139,7 @@ function ComposerCommandMenuLayer(props: { anchor: HTMLElement | null; children:
const observer =
typeof ResizeObserver === "undefined" ? null : new ResizeObserver(updatePosition);
if (observer) {
// The composer is centered and capped at a max width, so opening a side
// panel slides it sideways without ever resizing it. Watching the anchor
// alone would leave the menu behind; the ancestors are what shrink, and
// they resize on every frame of the panel animation.
observer.observe(anchor);
for (let element = anchor.parentElement; element; element = element.parentElement) {
observer.observe(element);
}
}
observer?.observe(anchor);
return () => {
observer?.disconnect();
@@ -101,8 +101,7 @@ export function DraftHeroHeadline({
<Menu>
<MenuTrigger
aria-label={hasResolvedProject ? "Change project" : "Choose a project"}
className="pointer-events-auto inline-block max-w-64 truncate border-foreground/60 border-b border-dotted align-bottom text-foreground transition-colors hover:border-foreground/80 focus-visible:rounded-sm focus-visible:outline-hidden focus-visible:ring-2 focus-visible:ring-ring"
title={activeProjectDisplayName ?? undefined}
className="pointer-events-auto inline cursor-pointer border-foreground/60 border-b border-dotted text-foreground transition-colors hover:border-foreground/80 focus-visible:rounded-sm focus-visible:outline-hidden focus-visible:ring-2 focus-visible:ring-ring"
>
{activeProjectDisplayName ?? "Choose a project"}
</MenuTrigger>
@@ -123,9 +122,7 @@ export function DraftHeroHeadline({
{projectPickerEntries.map(({ group }) => {
return (
<MenuRadioItem key={group.projectKey} value={group.projectKey} closeOnClick>
<span className="block min-w-0 truncate" title={group.displayName}>
{group.displayName}
</span>
<span className="min-w-0 truncate">{group.displayName}</span>
</MenuRadioItem>
);
})}
@@ -541,10 +541,6 @@ 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) => {
@@ -714,7 +710,7 @@ export const ModelPickerContent = memo(function ModelPickerContent(props: {
<LegendList<string>
ref={modelListRef}
data={filteredItemKeys}
extraData={modelListExtraData}
extraData={favoritesSet}
keyExtractor={(modelKey) => modelKey}
renderItem={({ item: modelKey, index }) => {
if (legacySection?.key === modelKey) {
@@ -120,26 +120,11 @@ export function CodeFontPreview() {
);
}
// 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_PROMPT = "\x1b[2m$\x1b[0m ";
const TERMINAL_PREVIEW_TRANSCRIPT =
`${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}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;
/** The surface treats an omitted family or size as "use the built-in default". */
@@ -240,7 +225,7 @@ export function TerminalFontPreview({ family, size }: { family: string; size: nu
return (
<div
ref={mountRef}
className="relative mt-1 mb-2 h-52 overflow-hidden rounded-lg border border-border"
className="relative mt-1 mb-2 h-36 overflow-hidden rounded-lg border border-border"
aria-label="Terminal font preview"
/>
);
@@ -115,8 +115,6 @@ import {
isFontFamilyAvailable,
isMonospaceFamily,
resolveDefaultFamilyLabel,
resolveTerminalFontPreference,
TYPOGRAPHY_ADVANCED_STORAGE_KEY,
} from "../../appearanceFonts";
import { CodeFontPreview, PromptFontPreview, TerminalFontPreview } from "./SettingsFontPreviews";
import { discoverInstalledFonts, FontFamilyPicker, useFontEnumeration } from "./FontFamilyPicker";
@@ -1153,8 +1151,10 @@ function useFontDefaultFamilies() {
return {
sans: defaults.sans,
code: defaults.code,
// The composer inherits whatever the interface preference resolves to.
// The composer inherits whatever the interface preference resolves to;
// the terminal inherits the monospace preference the same way.
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, independent from code blocks and diffs."
defaultFamily={defaults.code}
description="Terminal output. Follows the monospace font unless set."
defaultFamily={defaults.monoFamily}
value={settings.fontFamilyTerminal}
onValueChange={(fontFamilyTerminal) => updateSettings({ fontFamilyTerminal })}
requireMonospace
@@ -1258,11 +1258,7 @@ function TerminalFontRow() {
}}
preview={
<TerminalFontPreview
family={resolveTerminalFontPreference({
advanced: true,
code: settings.fontFamilyCode,
terminal: settings.fontFamilyTerminal,
})}
family={settings.fontFamilyTerminal.trim() || settings.fontFamilyCode}
size={settings.fontSizeTerminal}
/>
}
@@ -1354,11 +1350,7 @@ function SimpleFontRows() {
<>
<CodeFontPreview />
<TerminalFontPreview
family={resolveTerminalFontPreference({
advanced: false,
code: settings.fontFamilyCode,
terminal: settings.fontFamilyTerminal,
})}
family={settings.fontFamilyTerminal.trim() || settings.fontFamilyCode}
size={settings.fontSizeTerminal}
/>
</>
@@ -1378,6 +1370,8 @@ 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
@@ -1386,11 +1380,7 @@ const ADVANCED_TYPOGRAPHY_TARGET_IDS: ReadonlySet<string> = new Set([
* target exists to scroll to.
*/
function TypographySection() {
const [advanced, setAdvanced] = useLocalStorage(
TYPOGRAPHY_ADVANCED_STORAGE_KEY,
false,
Schema.Boolean,
);
const [advanced, setAdvanced] = useLocalStorage(TYPOGRAPHY_ADVANCED_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
+11
View File
@@ -12,6 +12,7 @@ import {
canRetainCachedPlatformRegistrationAfterRefreshFailure,
canReuseCachedPlatformRegistration,
primaryRegistrationToRetainAfterTopologyRead,
primaryRegistrationRefreshAtEpochMs,
provisionDesktopSshEnvironment,
readPrimaryEnvironmentTargetResult,
secondaryRegistrationsToRetainAfterTopologyRead,
@@ -222,4 +223,14 @@ describe("primary topology cache", () => {
}),
).toBeUndefined();
});
it("periodically refreshes primary descriptor metadata", () => {
const discoveredAtEpochMs = 10_000;
const refreshAtEpochMs = primaryRegistrationRefreshAtEpochMs(discoveredAtEpochMs);
const refreshable = { ...cached, refreshAtEpochMs };
expect(refreshAtEpochMs).toBe(40_000);
expect(canReuseCachedPlatformRegistration(refreshable, cached.signature, 39_999)).toBe(true);
expect(canReuseCachedPlatformRegistration(refreshable, cached.signature, 40_000)).toBe(false);
});
});
+19 -3
View File
@@ -295,6 +295,7 @@ const loadPrimaryConnectionRegistration = Effect.fn(
label: descriptor.label,
httpBaseUrl: resolved.target.httpBaseUrl,
wsBaseUrl: resolved.target.wsBaseUrl,
serverVersion: descriptor.serverVersion,
}),
});
});
@@ -358,11 +359,17 @@ const loadSecondaryConnectionRegistration = Effect.fn(
});
// Poll cadence for the desktop bootstrap topology. There is no change event on
// the bridge, so the renderer polls; successful registrations are cached by a
// signature of their endpoint + token until bearer credentials approach expiry.
// the bridge, so the renderer polls. Primary descriptor metadata refreshes
// periodically; secondary registrations refresh before bearer credentials
// expire.
const PLATFORM_POLL_INTERVAL = "3 seconds";
const PRIMARY_REGISTRATION_REFRESH_INTERVAL_MS = 30_000;
const SECONDARY_BEARER_REFRESH_SKEW_MS = 5_000;
export function primaryRegistrationRefreshAtEpochMs(discoveredAtEpochMs: number): number {
return discoveredAtEpochMs + PRIMARY_REGISTRATION_REFRESH_INTERVAL_MS;
}
export function secondaryBearerExpiresAtEpochMs(
issuedAtEpochMs: number,
expiresInSeconds: number,
@@ -505,9 +512,18 @@ const platformConnectionSourceLayer = Layer.effect(
Effect.option,
);
if (Option.isSome(built)) {
const cacheEntry = { signature, registration: built.value };
const cacheEntry = {
signature,
registration: built.value,
refreshAtEpochMs: primaryRegistrationRefreshAtEpochMs(nowEpochMs),
};
next.set(PRIMARY_LOCAL_ENVIRONMENT_ID, cacheEntry);
registrations.push(built.value);
} else if (cached?.signature === signature) {
// A descriptor refresh should not remove a live primary. Keep the
// old registration and retry on the next topology poll.
next.set(PRIMARY_LOCAL_ENVIRONMENT_ID, cached);
registrations.push(cached.registration);
}
}
}
-3
View File
@@ -1,5 +1,4 @@
export {
buildProjectGroups,
deriveLogicalProjectKey,
deriveLogicalProjectKeyFromRef,
deriveLogicalProjectKeyFromSettings,
@@ -12,6 +11,4 @@ export {
selectProjectGroupingSettings,
type ProjectGroupingMode,
type ProjectGroupingSettings,
type ProjectGroup,
type ProjectGroupMember,
} from "@t3tools/client-runtime/state/project-grouping";
+138 -33
View File
@@ -1,5 +1,11 @@
import { scopeProjectRef } from "@t3tools/client-runtime/environment";
import type { EnvironmentId, ScopedProjectRef } from "@t3tools/contracts";
import { buildProjectGroups, type ProjectGroupingSettings } from "./logicalProject";
import {
deriveLogicalProjectKeyFromSettings,
derivePhysicalProjectKey,
deriveProjectGroupLabel,
type ProjectGroupingSettings,
} from "./logicalProject";
import type { Project } from "./types";
export type EnvironmentPresence = "local-only" | "remote-only" | "mixed";
@@ -31,21 +37,77 @@ export interface SidebarProjectPickerEntry {
isPreferred: boolean;
}
interface SidebarProjectGroupCandidate {
readonly logicalKey: string;
readonly project: Project;
}
function getProjectFreshnessTime(project: Project): number {
const updatedAtTime = Date.parse(project.updatedAt);
if (Number.isFinite(updatedAtTime)) {
return updatedAtTime;
}
const createdAtTime = Date.parse(project.createdAt);
return Number.isFinite(createdAtTime) ? createdAtTime : 0;
}
function shouldReplaceDuplicateMember(input: {
existingMember: Project;
candidateMember: Project;
primaryEnvironmentId: EnvironmentId | null;
}): boolean {
if (
input.primaryEnvironmentId !== null &&
input.existingMember.environmentId !== input.primaryEnvironmentId &&
input.candidateMember.environmentId === input.primaryEnvironmentId
) {
return true;
}
const existingFreshness = getProjectFreshnessTime(input.existingMember);
const candidateFreshness = getProjectFreshnessTime(input.candidateMember);
if (candidateFreshness !== existingFreshness) {
return candidateFreshness > existingFreshness;
}
return input.candidateMember.id > input.existingMember.id;
}
function collectProjectWinnersByPhysicalKey(input: {
projects: ReadonlyArray<Project>;
settings: ProjectGroupingSettings;
primaryEnvironmentId: EnvironmentId | null;
}): Map<string, SidebarProjectGroupCandidate> {
const winnersByPhysicalKey = new Map<string, SidebarProjectGroupCandidate>();
for (const project of input.projects) {
const logicalKey = deriveLogicalProjectKeyFromSettings(project, input.settings);
const physicalProjectKey = derivePhysicalProjectKey(project);
const existing = winnersByPhysicalKey.get(physicalProjectKey);
if (!existing) {
winnersByPhysicalKey.set(physicalProjectKey, { logicalKey, project });
continue;
}
if (
shouldReplaceDuplicateMember({
existingMember: existing.project,
candidateMember: project,
primaryEnvironmentId: input.primaryEnvironmentId,
})
) {
winnersByPhysicalKey.set(physicalProjectKey, { logicalKey, project });
}
}
return winnersByPhysicalKey;
}
export function buildPhysicalToLogicalProjectKeyMap(input: {
projects: ReadonlyArray<Project>;
settings: ProjectGroupingSettings;
primaryEnvironmentId: EnvironmentId | null;
}): Map<string, string> {
const mapping = new Map<string, string>();
const groups = buildProjectGroups({
projects: input.projects,
settings: input.settings,
preferredEnvironmentId: input.primaryEnvironmentId,
});
for (const group of groups) {
for (const member of group.members) {
mapping.set(member.physicalProjectKey, group.key);
}
for (const [physicalProjectKey, winner] of collectProjectWinnersByPhysicalKey(input)) {
mapping.set(physicalProjectKey, winner.logicalKey);
}
return mapping;
}
@@ -61,24 +123,59 @@ export function buildSidebarProjectSnapshots(input: {
// legacy behavior.
isDesktopLocalEnvironment?: (environmentId: EnvironmentId) => boolean;
}): SidebarProjectSnapshot[] {
return buildProjectGroups({
projects: input.projects,
settings: input.settings,
preferredEnvironmentId: input.primaryEnvironmentId,
}).map((group): SidebarProjectSnapshot => {
const members = group.members.map(
({ physicalProjectKey, project }): SidebarProjectGroupMember => ({
...project,
physicalProjectKey,
environmentLabel: input.resolveEnvironmentLabel(project.environmentId),
}),
);
const winnersByPhysicalKey = collectProjectWinnersByPhysicalKey(input);
const groupedMembers = new Map<string, SidebarProjectGroupMember[]>();
for (const { logicalKey, project } of winnersByPhysicalKey.values()) {
const member: SidebarProjectGroupMember = {
...project,
physicalProjectKey: derivePhysicalProjectKey(project),
environmentLabel: input.resolveEnvironmentLabel(project.environmentId),
};
const existingMembers = groupedMembers.get(logicalKey);
if (existingMembers) {
existingMembers.push(member);
} else {
groupedMembers.set(logicalKey, [member]);
}
}
const projectRefsByLogicalKey = new Map<string, ScopedProjectRef[]>();
const seenProjectRefs = new Set<string>();
for (const project of input.projects) {
const physicalProjectKey = derivePhysicalProjectKey(project);
const logicalKey =
winnersByPhysicalKey.get(physicalProjectKey)?.logicalKey ??
deriveLogicalProjectKeyFromSettings(project, input.settings);
const projectRefKey = `${project.environmentId}:${project.id}`;
if (seenProjectRefs.has(projectRefKey)) continue;
seenProjectRefs.add(projectRefKey);
const projectRef = scopeProjectRef(project.environmentId, project.id);
const existingRefs = projectRefsByLogicalKey.get(logicalKey);
if (existingRefs) {
existingRefs.push(projectRef);
} else {
projectRefsByLogicalKey.set(logicalKey, [projectRef]);
}
}
const result: SidebarProjectSnapshot[] = [];
const seen = new Set<string>();
for (const project of input.projects) {
const logicalKey = deriveLogicalProjectKeyFromSettings(project, input.settings);
if (seen.has(logicalKey)) {
continue;
}
seen.add(logicalKey);
const members = groupedMembers.get(logicalKey) ?? [];
const representative =
members.find(
(member) =>
member.environmentId === group.representative.environmentId &&
member.id === group.representative.id,
) ?? members[0]!;
(input.primaryEnvironmentId
? members.find((member) => member.environmentId === input.primaryEnvironmentId)
: null) ?? members[0];
if (!representative) {
continue;
}
const hasLocal =
input.primaryEnvironmentId !== null &&
@@ -99,19 +196,27 @@ export function buildSidebarProjectSnapshots(input: {
remoteMembers.length > 0 &&
remoteMembers.every((member) => isDesktopLocal(member.environmentId));
return {
result.push({
...representative,
projectKey: group.key,
displayName: group.label,
projectKey: logicalKey,
displayName:
members.length > 1
? deriveProjectGroupLabel({
representative,
members,
})
: representative.title,
groupedProjectCount: members.length,
environmentPresence:
hasLocal && hasRemote ? "mixed" : hasRemote ? "remote-only" : "local-only",
allRemoteMembersAreDesktopLocal,
memberProjects: members,
memberProjectRefs: group.memberProjectRefs,
memberProjectRefs: projectRefsByLogicalKey.get(logicalKey) ?? [],
remoteEnvironmentLabels,
};
});
});
}
return result;
}
export function buildSidebarProjectPickerEntries(input: {
@@ -71,62 +71,6 @@ describe("ghosttyTextRunEnd", () => {
});
describe("renderGhosttySnapshot", () => {
it("underlines every cell in a hovered wrapped link", () => {
const fillRectCalls: number[][] = [];
const context = {
canvas: { width: 200, height: 80 },
beginPath: () => {},
clip: () => {},
fillRect: (...args: number[]) => fillRectCalls.push(args),
fillText: () => {},
rect: () => {},
resetTransform: () => {},
restore: () => {},
save: () => {},
set fillStyle(_value: string) {},
set font(_value: string) {},
set textBaseline(_value: string) {},
} as unknown as CanvasRenderingContext2D;
const snapshot: GhosttySnapshot = {
cols: 4,
rows: 2,
foreground: { r: 255, g: 255, b: 255 },
background: { r: 0, g: 0, b: 0 },
cursor: { r: 255, g: 255, b: 255 },
cursorX: -1,
cursorY: -1,
cursorVisible: false,
cursorBlinking: false,
cursorStyle: 1,
dirtyRows: new Set([0, 1]),
rowData: [0, 1].map(() => ({
cells: [cell("a"), cell("b"), cell("c"), cell("d")],
text: "abcd",
isWrapContinuation: false,
wrapsToNext: false,
})),
};
renderGhosttySnapshot({
context,
snapshot,
metrics: { width: 10, height: 20, baseline: 15 },
fontSize: 12,
fontFamily: "monospace",
padding: 4,
forceFull: false,
cursorOn: false,
hoveredLinkRange: { start: { x: 2, y: 0 }, end: { x: 1, y: 1 } },
});
expect(fillRectCalls.filter(([, , , height]) => height === 1)).toEqual([
[24, 22, 10, 1],
[34, 22, 10, 1],
[4, 42, 10, 1],
[14, 42, 10, 1],
]);
});
it("constrains text runs and cursor glyphs to their terminal cells", () => {
const fillTextCalls: unknown[][] = [];
const context = {
+2 -19
View File
@@ -12,11 +12,6 @@ export interface GhosttyCellMetrics {
readonly baseline: number;
}
export interface GhosttyCellRange {
readonly start: { readonly x: number; readonly y: number };
readonly end: { readonly x: number; readonly y: number };
}
const DEFAULT_SELECTION_BACKGROUND = "rgba(72, 122, 191, 0.35)";
function cssColor(color: GhosttyColor): string {
@@ -103,7 +98,6 @@ export function renderGhosttySnapshot(options: {
readonly previousCursorY?: number | null;
readonly focused?: boolean;
readonly selectionBackground?: string;
readonly hoveredLinkRange?: GhosttyCellRange | null;
/** Vertical origin of row 0; defaults to the horizontal padding. */
readonly originY?: number;
}): void {
@@ -120,7 +114,6 @@ export function renderGhosttySnapshot(options: {
} = options;
const focused = options.focused ?? true;
const selectionBackground = options.selectionBackground ?? DEFAULT_SELECTION_BACKGROUND;
const hoveredLinkRange = options.hoveredLinkRange ?? null;
const originY = options.originY ?? padding;
const rowsToDraw = forceFull
? Array.from({ length: snapshot.rows }, (_, index) => index)
@@ -223,20 +216,10 @@ export function renderGhosttySnapshot(options: {
for (let column = 0; column < row.cells.length; column += 1) {
const cell = row.cells[column];
const hoveredLink =
hoveredLinkRange !== null &&
rowIndex >= hoveredLinkRange.start.y &&
rowIndex <= hoveredLinkRange.end.y &&
(rowIndex > hoveredLinkRange.start.y || column >= hoveredLinkRange.start.x) &&
(rowIndex < hoveredLinkRange.end.y || column <= hoveredLinkRange.end.x);
if (!cell || (!cell.underline && !cell.strikethrough && !cell.overline && !hoveredLink)) {
continue;
}
if (!cell || (!cell.underline && !cell.strikethrough && !cell.overline)) continue;
context.fillStyle = cssColor(cell.foreground);
const left = padding + column * metrics.width;
if (cell.underline || hoveredLink) {
context.fillRect(left, top + metrics.height - 2, metrics.width, 1);
}
if (cell.underline) context.fillRect(left, top + metrics.height - 2, metrics.width, 1);
if (cell.strikethrough) {
context.fillRect(left, top + Math.floor(metrics.height * 0.55), metrics.width, 1);
}
+20 -70
View File
@@ -1,4 +1,4 @@
import { describe, expect, it, vi } from "vite-plus/test";
import { describe, expect, it } from "vite-plus/test";
import type { GhosttyCell, GhosttyRow } from "./core";
import {
@@ -11,18 +11,15 @@ import {
isTerminalCopyShortcut,
isTerminalLinkPointerGesture,
isTerminalPasteShortcut,
loadTerminalFontFamily,
shouldBlinkTerminalCursor,
shouldReportTerminalMouse,
shouldShowTerminalLinkHover,
terminalGridCellAt,
terminalScrollbarGeometry,
terminalScrollbarOffsetAtPointer,
terminalLinkAtColumn,
terminalLinkAtPosition,
terminalLinkAtPositionWithRange,
terminalContentOriginY,
terminalFontFamily,
fittedTerminalFontSize,
terminalFontSize,
terminalWheelArrowData,
terminalWheelDeltaRows,
@@ -59,32 +56,6 @@ describe("isTerminalAltGraphText", () => {
});
});
describe("terminalGridCellAt", () => {
const options = {
bounds: { left: 100, top: 200 },
cols: 3,
rows: 2,
metrics: { width: 10, height: 20 },
padding: 4,
originY: 24,
};
it("maps points inside the rendered grid without clamping its padding", () => {
expect(terminalGridCellAt({ ...options, clientX: 104, clientY: 224 })).toEqual({
x: 0,
y: 0,
});
expect(terminalGridCellAt({ ...options, clientX: 133, clientY: 263 })).toEqual({
x: 2,
y: 1,
});
expect(terminalGridCellAt({ ...options, clientX: 103, clientY: 224 })).toBeNull();
expect(terminalGridCellAt({ ...options, clientX: 104, clientY: 223 })).toBeNull();
expect(terminalGridCellAt({ ...options, clientX: 134, clientY: 224 })).toBeNull();
expect(terminalGridCellAt({ ...options, clientX: 104, clientY: 264 })).toBeNull();
});
});
describe("shouldBlinkTerminalCursor", () => {
const blinking = {
focused: true,
@@ -128,10 +99,6 @@ describe("terminalLinkAtColumn", () => {
expect(terminalLinkAtColumn(row, 2)).toBe("https://t3.codes");
expect(terminalLinkAtColumn(row, cells.length - 1)).toBe("https://t3.codes");
expect(terminalLinkAtColumn(row, 0)).toBeNull();
expect(terminalLinkAtPositionWithRange([row], 0, 8)?.range).toEqual({
start: { x: 2, y: 0 },
end: { x: cells.length - 1, y: 0 },
});
});
it("uses shared path matching and reconstructs soft-wrapped links", () => {
@@ -152,13 +119,6 @@ describe("terminalLinkAtColumn", () => {
expect(terminalLinkAtPosition(rows, 1, 4)).toBe("https://example.com/reference");
expect(terminalLinkAtPosition(rows, 2, 2)).toBe("~/project/file");
expect(terminalLinkAtPosition(rows, 3, 4)).toBe("C:\\repo\\file.ts");
expect(terminalLinkAtPositionWithRange(rows, 1, 4)).toEqual({
text: "https://example.com/reference",
range: {
start: { x: 0, y: 0 },
end: { x: 12, y: 1 },
},
});
});
it("refuses links truncated at the viewport edges instead of mis-resolving", () => {
@@ -285,37 +245,9 @@ describe("application mouse reporting", () => {
it("maps browser buttons to Ghostty's button enum", () => {
expect([0, 1, 2, 3, 4, 5].map(ghosttyMouseButton)).toEqual([1, 3, 2, 4, 5, null]);
});
it("only shows link hover during mouse tracking when the link modifier is held", () => {
expect(shouldShowTerminalLinkHover(false, false)).toBe(true);
expect(shouldShowTerminalLinkHover(false, true)).toBe(true);
expect(shouldShowTerminalLinkHover(true, false)).toBe(false);
expect(shouldShowTerminalLinkHover(true, true)).toBe(true);
});
});
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);
@@ -342,6 +274,24 @@ 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);
+72 -250
View File
@@ -10,7 +10,6 @@ import {
measureGhosttyCell,
renderGhosttySnapshot,
terminalGridSize,
type GhosttyCellRange,
type GhosttyCellMetrics,
} from "./renderer";
import symbolsFontUrl from "./fonts/SymbolsNerdFontMono-Regular.woff2?url";
@@ -36,13 +35,6 @@ 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 {
@@ -85,13 +77,6 @@ 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.
@@ -102,31 +87,43 @@ 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 uncheckedTerminalFontFamily(custom);
return `${custom}, ${TERMINAL_GLYPH_FALLBACKS}`;
}
/** 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.
/**
* 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;
}
return (environment?.resolve ?? terminalFontFamily)(family);
return size;
}
export function terminalFontSize(size?: number): number {
@@ -208,28 +205,6 @@ export function terminalScrollbarOffsetAtPointer(
return Math.round((thumbTop / travel) * geometry.maxOffset);
}
export function terminalGridCellAt(options: {
bounds: { left: number; top: number };
clientX: number;
clientY: number;
cols: number;
rows: number;
metrics: Pick<GhosttyCellMetrics, "width" | "height">;
padding: number;
originY: number;
}): { x: number; y: number } | null {
const { bounds, clientX, clientY, cols, rows, metrics, padding, originY } = options;
const gridX = clientX - bounds.left - padding;
const gridY = clientY - bounds.top - originY;
if (gridX < 0 || gridY < 0 || gridX >= cols * metrics.width || gridY >= rows * metrics.height) {
return null;
}
return {
x: Math.floor(gridX / metrics.width),
y: Math.floor(gridY / metrics.height),
};
}
function terminalRowText(row: GhosttySnapshot["rowData"][number], trimRight: boolean): string {
const text = row.cells.map((cell) => cell.text || " ").join("");
return trimRight ? text.trimEnd() : text;
@@ -248,27 +223,6 @@ export function terminalLinkAtPosition(
rowIndex: number,
column: number,
): string | null {
return terminalLinkAtPositionWithRange(rows, rowIndex, column)?.text ?? null;
}
export interface TerminalLinkWithRange {
readonly text: string;
readonly range: GhosttyCellRange;
}
function terminalColumnAtOffset(row: GhosttySnapshot["rowData"][number], offset: number): number {
for (let column = 0; column < row.cells.length; column += 1) {
const nextOffset = terminalColumnOffset(row, column + 1);
if (offset < nextOffset) return column;
}
return Math.max(0, row.cells.length - 1);
}
export function terminalLinkAtPositionWithRange(
rows: GhosttySnapshot["rowData"],
rowIndex: number,
column: number,
): TerminalLinkWithRange | null {
const wrappedLine = collectWrappedTerminalLinkLine(rowIndex + 1, (index) => {
const row = rows[index];
if (!row) return null;
@@ -297,28 +251,7 @@ export function terminalLinkAtPositionWithRange(
if (offset >= match.start && offset < match.end) {
// A truncated tail must not activate as a complete link.
if (match.end === wrappedLine.text.length && continuesBelowViewport) return null;
const startSegment = wrappedLine.segments.find(
(value) => match.start >= value.startIndex && match.start < value.endIndex,
);
const endSegment = wrappedLine.segments.find(
(value) => match.end - 1 >= value.startIndex && match.end - 1 < value.endIndex,
);
const startRow = startSegment ? rows[startSegment.bufferLineNumber - 1] : undefined;
const endRow = endSegment ? rows[endSegment.bufferLineNumber - 1] : undefined;
if (!startSegment || !endSegment || !startRow || !endRow) return null;
return {
text: match.text,
range: {
start: {
x: terminalColumnAtOffset(startRow, match.start - startSegment.startIndex),
y: startSegment.bufferLineNumber - 1,
},
end: {
x: terminalColumnAtOffset(endRow, match.end - 1 - endSegment.startIndex),
y: endSegment.bufferLineNumber - 1,
},
},
};
return match.text;
}
}
return null;
@@ -405,13 +338,6 @@ export function isTerminalLinkPointerGesture(
: event.ctrlKey && !event.metaKey;
}
export function shouldShowTerminalLinkHover(
mouseTracking: boolean,
linkModifierActive: boolean,
): boolean {
return !mouseTracking || linkModifierActive;
}
export function ghosttyMouseButton(button: number): number | null {
switch (button) {
case 0:
@@ -481,10 +407,9 @@ 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;
@@ -519,9 +444,6 @@ export class GhosttyTerminalSurface {
private mouseReportingPointerId: number | null = null;
private mouseReportingButton: number | null = null;
private linkActivationPointerId: number | null = null;
private hoveredLink: TerminalLinkWithRange | null = null;
private hoverPointer: { x: number; y: number } | null = null;
private linkModifierActive = false;
private selectionClickSequence: TerminalSelectionClickSequence | null = null;
private selectionMoved = false;
private composing = false;
@@ -548,7 +470,6 @@ export class GhosttyTerminalSurface {
context: CanvasRenderingContext2D,
core: GhosttyTerminalCore,
metrics: GhosttyCellMetrics,
fontFamily: string,
options: GhosttyTerminalSurfaceOptions,
) {
this.mount = mount;
@@ -561,9 +482,9 @@ export class GhosttyTerminalSurface {
this.metrics = metrics;
this.options = options;
this.theme = options.theme;
this.fontFamily = fontFamily;
this.requestedFontFamily = options.font?.family;
this.fontFamily = terminalFontFamily(options.font?.family);
this.fontSize = terminalFontSize(options.font?.size);
this.requestedFontSize = this.fontSize;
this.resizeObserver = new ResizeObserver(() => this.fit());
this.installEvents();
this.watchDevicePixelRatio();
@@ -604,20 +525,16 @@ export class GhosttyTerminalSurface {
const context = canvas.getContext("2d", { alpha: false });
if (!context) throw new Error("Canvas 2D is unavailable");
// 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 fontFamily = terminalFontFamily(options.font?.family);
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(
@@ -637,7 +554,6 @@ export class GhosttyTerminalSurface {
context,
core,
metrics,
fontFamily,
options,
);
surface.fit();
@@ -676,16 +592,19 @@ 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;
this.pendingFontEpoch = epoch;
const fontFamily = await loadTerminalFontFamily(font.family, fontSize);
try {
await document.fonts.load(`${fontSize}px ${fontFamily}`);
} catch {
// Metrics fall back to whichever faces are already available.
}
if (this.disposed || epoch !== this.fontEpoch) return;
this.pendingFontEpoch = null;
this.fontFamily = fontFamily;
this.requestedFontFamily = font.family;
this.requestedFontSize = fontSize;
this.fontSize = fontSize;
this.applyFontMetrics();
}
@@ -712,17 +631,6 @@ 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);
@@ -741,6 +649,22 @@ 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));
@@ -891,7 +815,6 @@ export class GhosttyTerminalSurface {
}
private readonly onKeyDown = (event: KeyboardEvent) => {
this.updateLinkModifier(event);
// Presses handled outside the terminal must also swallow their release:
// beforeKey runs side effects (keybindings, navigation sends), so it cannot
// be consulted again on keyup, and Kitty report-event-types sessions would
@@ -943,7 +866,6 @@ export class GhosttyTerminalSurface {
};
private readonly onKeyUp = (event: KeyboardEvent) => {
this.updateLinkModifier(event);
if (this.suppressedKeyCodes.delete(event.code)) return;
if (event.isComposing || this.composing || event.key === "Process" || event.keyCode === 229) {
return;
@@ -965,8 +887,6 @@ export class GhosttyTerminalSurface {
private readonly onBlur = () => {
this.focused = false;
this.linkModifierActive = false;
this.refreshHoveredLink();
// Suppressions survive blur deliberately: a shortcut that moves focus (for
// example terminal-toggle) must still swallow its own keyup if focus comes
// back before release. Stale entries are harmless — an encoding keydown
@@ -1048,7 +968,6 @@ export class GhosttyTerminalSurface {
if (button === null) return;
event.preventDefault();
event.stopPropagation();
this.clearHoveredLink("default");
this.mouseReportingPointerId = event.pointerId;
this.mouseReportingButton = button;
this.sendMouse("press", button, event);
@@ -1063,7 +982,6 @@ export class GhosttyTerminalSurface {
this.canvas.setPointerCapture(event.pointerId);
return;
}
this.clearHoveredLink();
const cell = this.cellAt(event.clientX, event.clientY);
this.selectionMoved = false;
this.selectionClickSequence = advanceTerminalSelectionClickSequence(
@@ -1111,11 +1029,6 @@ export class GhosttyTerminalSurface {
shouldReportTerminalMouse(this.core.isMouseAnyEventTracking(), event)
) {
event.preventDefault();
this.hoverPointer = { x: event.clientX, y: event.clientY };
this.linkModifierActive = isTerminalLinkPointerGesture(event);
// A drag whose press was already sent to the terminal application cannot
// turn into link activation midway through, so link feedback would lie.
this.setHoveredLink(null);
this.canvas.style.cursor = "default";
this.sendMouse("motion", this.buttonFromButtons(event.buttons), event);
return;
@@ -1124,7 +1037,6 @@ export class GhosttyTerminalSurface {
this.updateHoverCursor(event);
return;
}
this.clearHoveredLink();
this.selectionPointer = { x: event.clientX, y: event.clientY };
const bounds = this.canvas.getBoundingClientRect();
this.setSelectionAutoscroll(
@@ -1185,50 +1097,10 @@ export class GhosttyTerminalSurface {
}
private updateHoverCursor(event: PointerEvent): void {
this.hoverPointer = { x: event.clientX, y: event.clientY };
this.linkModifierActive = isTerminalLinkPointerGesture(event);
this.refreshHoveredLink();
}
private updateLinkModifier(event: Pick<KeyboardEvent, "ctrlKey" | "metaKey">): void {
const active = isTerminalLinkPointerGesture(event);
if (active === this.linkModifierActive) return;
this.linkModifierActive = active;
this.refreshHoveredLink();
}
private readonly onPointerLeave = () => {
this.clearHoveredLink();
};
private clearHoveredLink(cursor = ""): void {
this.hoverPointer = null;
this.setHoveredLink(null);
this.canvas.style.cursor = cursor;
}
private refreshHoveredLink(): void {
const pointer = this.hoverPointer;
const link =
pointer && shouldShowTerminalLinkHover(this.core.isMouseTracking(), this.linkModifierActive)
? this.linkAt(pointer.x, pointer.y)
: null;
this.setHoveredLink(link);
}
private setHoveredLink(link: TerminalLinkWithRange | null): void {
const previous = this.hoveredLink;
const unchanged =
previous?.text === link?.text &&
previous?.range.start.x === link?.range.start.x &&
previous?.range.start.y === link?.range.start.y &&
previous?.range.end.x === link?.range.end.x &&
previous?.range.end.y === link?.range.end.y;
this.canvas.style.cursor = link ? "pointer" : "";
if (unchanged) return;
this.hoveredLink = link;
this.forceFullRender = true;
this.requestRender();
const overLink =
isTerminalLinkPointerGesture(event) && this.linkAt(event.clientX, event.clientY) !== null;
const cursor = overLink ? "pointer" : "";
if (this.canvas.style.cursor !== cursor) this.canvas.style.cursor = cursor;
}
private readonly onPointerUp = (event: PointerEvent) => {
@@ -1242,7 +1114,7 @@ export class GhosttyTerminalSurface {
}
if (event.type !== "pointercancel") {
const link = this.linkAt(event.clientX, event.clientY);
if (link) this.options.onLinkActivate(link.text, event);
if (link) this.options.onLinkActivate(link, event);
}
return;
}
@@ -1255,13 +1127,6 @@ export class GhosttyTerminalSurface {
if (this.canvas.hasPointerCapture(event.pointerId)) {
this.canvas.releasePointerCapture(event.pointerId);
}
if (event.type === "pointercancel") {
this.clearHoveredLink();
} else {
this.hoverPointer = { x: event.clientX, y: event.clientY };
this.linkModifierActive = isTerminalLinkPointerGesture(event);
this.refreshHoveredLink();
}
return;
}
if (this.canvas.hasPointerCapture(event.pointerId)) {
@@ -1388,7 +1253,6 @@ export class GhosttyTerminalSurface {
this.input.addEventListener("compositionend", this.onCompositionEnd);
this.canvas.addEventListener("pointerdown", this.onPointerDown);
this.canvas.addEventListener("pointermove", this.onPointerMove);
this.canvas.addEventListener("pointerleave", this.onPointerLeave);
this.canvas.addEventListener("pointerup", this.onPointerUp);
this.canvas.addEventListener("pointercancel", this.onPointerUp);
this.canvas.addEventListener("wheel", this.onWheel, { passive: false });
@@ -1412,7 +1276,6 @@ export class GhosttyTerminalSurface {
this.input.removeEventListener("compositionend", this.onCompositionEnd);
this.canvas.removeEventListener("pointerdown", this.onPointerDown);
this.canvas.removeEventListener("pointermove", this.onPointerMove);
this.canvas.removeEventListener("pointerleave", this.onPointerLeave);
this.canvas.removeEventListener("pointerup", this.onPointerUp);
this.canvas.removeEventListener("pointercancel", this.onPointerUp);
this.canvas.removeEventListener("wheel", this.onWheel);
@@ -1515,7 +1378,6 @@ export class GhosttyTerminalSurface {
this.originY = nextOriginY;
this.forceFullRender = true;
}
this.refreshHoveredLink();
renderGhosttySnapshot({
context: this.context,
snapshot: this.snapshot,
@@ -1528,7 +1390,6 @@ export class GhosttyTerminalSurface {
cursorOn: this.cursorOn,
previousCursorY: this.renderedCursorY,
focused: this.focused,
hoveredLinkRange: this.hoveredLink?.range ?? null,
...(this.theme.selectionBackground !== undefined
? { selectionBackground: this.theme.selectionBackground }
: {}),
@@ -1605,51 +1466,12 @@ export class GhosttyTerminalSurface {
};
}
private linkAt(clientX: number, clientY: number): TerminalLinkWithRange | null {
private linkAt(clientX: number, clientY: number): string | null {
if (!this.snapshot) return null;
const cell = terminalGridCellAt({
bounds: this.canvas.getBoundingClientRect(),
clientX,
clientY,
cols: this.cols,
rows: this.rows,
metrics: this.metrics,
padding: CONTENT_PADDING,
originY: this.originY,
});
if (!cell) return null;
const cell = this.cellAt(clientX, clientY);
const explicitHyperlink = this.core.hyperlinkAt(cell.x, cell.y);
if (explicitHyperlink) {
const start = { ...cell };
const end = { ...cell };
while (true) {
const previous =
start.x > 0
? { x: start.x - 1, y: start.y }
: start.y > 0 && this.snapshot.rowData[start.y]?.isWrapContinuation
? { x: this.cols - 1, y: start.y - 1 }
: null;
if (!previous || this.core.hyperlinkAt(previous.x, previous.y) !== explicitHyperlink) break;
start.x = previous.x;
start.y = previous.y;
}
while (true) {
const next =
end.x + 1 < this.cols
? { x: end.x + 1, y: end.y }
: end.y + 1 < this.rows && this.snapshot.rowData[end.y]?.wrapsToNext
? { x: 0, y: end.y + 1 }
: null;
if (!next || this.core.hyperlinkAt(next.x, next.y) !== explicitHyperlink) break;
end.x = next.x;
end.y = next.y;
}
return {
text: explicitHyperlink,
range: { start, end },
};
}
return terminalLinkAtPositionWithRange(this.snapshot.rowData, cell.y, cell.x);
if (explicitHyperlink) return explicitHyperlink;
return terminalLinkAtPosition(this.snapshot.rowData, cell.y, cell.x);
}
private sendMouse(
+81
View File
@@ -7,6 +7,7 @@ import {
buildVersionMismatchDismissalKey,
dismissVersionMismatch,
isVersionMismatchDismissed,
resolveCompatibilityChannelMismatch,
resolveServerConfigVersionMismatch,
resolveServerSelfUpdateCapability,
resolveVersionMismatch,
@@ -26,6 +27,86 @@ describe("versionSkew", () => {
});
});
it("calls out a stable client connected to a nightly server", () => {
expect(
resolveCompatibilityChannelMismatch({
clientVersion: "0.0.32",
clientStageLabel: "Latest",
serverVersion: "0.0.33-nightly.20260803.4",
}),
).toEqual({
clientVersion: "0.0.32",
clientChannel: "Stable",
serverVersion: "0.0.33-nightly.20260803.4",
serverChannel: "Nightly",
newerSide: "server",
});
});
it("calls out a nightly client connected to a stable server", () => {
expect(
resolveCompatibilityChannelMismatch({
clientVersion: "0.0.33-nightly.20260803.4",
clientStageLabel: "Nightly",
serverVersion: "0.0.32",
}),
).toEqual({
clientVersion: "0.0.33-nightly.20260803.4",
clientChannel: "Nightly",
serverVersion: "0.0.32",
serverChannel: "Stable",
newerSide: "client",
});
});
it("uses semver precedence when the channels differ at the same release", () => {
expect(
resolveCompatibilityChannelMismatch({
clientVersion: "0.0.32",
clientStageLabel: "Latest",
serverVersion: "0.0.32-nightly.20260803.4",
}),
).toMatchObject({
newerSide: "client",
});
});
it("does not guess which side is newer when a version cannot be compared", () => {
expect(
resolveCompatibilityChannelMismatch({
clientVersion: "not-semver",
clientStageLabel: "Latest",
serverVersion: "0.0.33-nightly.20260803.4",
}),
).toMatchObject({
newerSide: null,
});
});
it("keeps same-channel and development incompatibilities generic", () => {
expect(
resolveCompatibilityChannelMismatch({
clientVersion: "0.0.32",
clientStageLabel: "Latest",
serverVersion: "0.0.31",
}),
).toBeNull();
expect(
resolveCompatibilityChannelMismatch({
clientVersion: "0.0.32",
clientStageLabel: "Dev",
serverVersion: "0.0.33-nightly.20260803.4",
}),
).toBeNull();
expect(
resolveCompatibilityChannelMismatch({
clientVersion: "0.0.32",
clientStageLabel: "Latest",
serverVersion: "0.0.0",
}),
).toBeNull();
});
it("reads the server version from config descriptors", () => {
expect(
resolveServerConfigVersionMismatch({
+67
View File
@@ -1,4 +1,5 @@
import type { EnvironmentId, ServerConfig, ServerSelfUpdateCapability } from "@t3tools/contracts";
import { compareSemverVersions, parseSemver } from "@t3tools/shared/semver";
import * as Schema from "effect/Schema";
import { APP_VERSION } from "./branding";
@@ -10,6 +11,16 @@ export interface VersionMismatch {
readonly hint: string;
}
export type CompatibilityChannel = "Stable" | "Nightly";
export interface CompatibilityChannelMismatch {
readonly clientVersion: string;
readonly clientChannel: CompatibilityChannel;
readonly serverVersion: string;
readonly serverChannel: CompatibilityChannel;
readonly newerSide: "client" | "server" | null;
}
export const VERSION_MISMATCH_DISMISSALS_STORAGE_KEY = "t3code:version-mismatch-dismissals:v1";
const VersionMismatchDismissalsSchema = Schema.Struct({
@@ -23,6 +34,62 @@ function normalizeVersion(version: string | null | undefined): string | null {
return trimmed && trimmed.length > 0 ? trimmed : null;
}
function compatibilityChannel(
version: string,
stageLabel?: string | null,
): CompatibilityChannel | null {
const normalizedStage = stageLabel?.trim().toLowerCase();
if (normalizedStage === "dev" || version === "0.0.0" || /-(?:dev|test)(?:\.|$)/i.test(version)) {
return null;
}
if (normalizedStage === "nightly" || /-nightly(?:\.|$)/i.test(version)) {
return "Nightly";
}
return "Stable";
}
function newerCompatibilitySide(
clientVersion: string,
serverVersion: string,
): CompatibilityChannelMismatch["newerSide"] {
if (!parseSemver(clientVersion) || !parseSemver(serverVersion)) {
return null;
}
const comparison = compareSemverVersions(clientVersion, serverVersion);
return comparison === 0 ? null : comparison > 0 ? "client" : "server";
}
export function resolveCompatibilityChannelMismatch({
clientVersion,
clientStageLabel,
serverVersion,
}: {
readonly clientVersion: string | null | undefined;
readonly clientStageLabel: string | null | undefined;
readonly serverVersion: string | null | undefined;
}): CompatibilityChannelMismatch | null {
const normalizedClientVersion = normalizeVersion(clientVersion);
const normalizedServerVersion = normalizeVersion(serverVersion);
if (!normalizedClientVersion || !normalizedServerVersion) {
return null;
}
const clientChannel = compatibilityChannel(normalizedClientVersion, clientStageLabel);
const serverChannel = compatibilityChannel(normalizedServerVersion);
if (!clientChannel || !serverChannel || clientChannel === serverChannel) {
return null;
}
return {
clientVersion: normalizedClientVersion,
clientChannel,
serverVersion: normalizedServerVersion,
serverChannel,
newerSide: newerCompatibilitySide(normalizedClientVersion, normalizedServerVersion),
};
}
export function resolveVersionMismatch(
serverVersion: string | null | undefined,
): VersionMismatch | null {
+3 -4
View File
@@ -34,15 +34,14 @@ This document covers the unified release workflow for stable and nightly desktop
## Required release credentials
Stable releases require these GitHub Actions secrets in addition to the platform and deployment
The release workflow requires these GitHub Actions secrets in addition to the platform and deployment
credentials documented below:
- `RELEASE_APP_ID`
- `RELEASE_APP_PRIVATE_KEY`
The finalize job uses them to commit and push aligned package versions to `main` as the Release App.
GitHub Release publication uses the repository-scoped workflow token so it has a rate-limit quota
independent from the shared Release App installation.
The GitHub Release job uses them to mint the token that publishes release assets. Stable releases use
them again in the finalize job, which can commit and push aligned package versions to `main`.
## T3 Connect relay deployment
+15
View File
@@ -23,6 +23,21 @@ Update or repair it:
npx t3@latest service update
```
The command installs the same T3 Code version as the CLI you ran. This makes nightly and pinned
installations predictable:
```sh
npx t3@nightly service update
npx t3@1.2.3 service update
```
An older CLI will not replace a newer installed service by accident. If you intentionally need to
downgrade, run the exact older version and pass `--allow-downgrade`:
```sh
npx t3@1.2.3 service update --allow-downgrade
```
Stop it and remove it from startup:
```sh
@@ -0,0 +1,7 @@
CREATE TABLE "relay_environment_lifecycle_leases" (
"user_id" varchar(191),
"environment_id" varchar(191),
"owner_id" varchar(64) NOT NULL,
"expires_at" varchar(64) NOT NULL,
CONSTRAINT "relay_environment_lifecycle_leases_pkey" PRIMARY KEY("user_id","environment_id")
);
+82
View File
@@ -0,0 +1,82 @@
import { expect, it } from "@effect/vitest";
import type { SQL } from "drizzle-orm";
import { PgDialect } from "drizzle-orm/pg-core";
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
import * as Result from "effect/Result";
import * as RelayDb from "./db.ts";
import { relayEnvironmentLifecycleLeases } from "./persistence/schema.ts";
it.effect("leases lifecycle work without changing its transaction boundary", () => {
const calls: Array<string> = [];
let ownerId = "";
let insertedExpiresAt: SQL | undefined;
let updatedExpiresAt: SQL | undefined;
let leaseExpiryCondition: SQL | undefined;
const db = {
$client: {
withTransaction: <A, E, R>(effect: Effect.Effect<A, E, R>) =>
Effect.sync(() => {
calls.push("transaction");
}).pipe(Effect.andThen(effect)),
},
insert: (table: unknown) => {
expect(table).toBe(relayEnvironmentLifecycleLeases);
return {
values: (values: { readonly ownerId: string; readonly expiresAt: SQL }) => {
ownerId = values.ownerId;
insertedExpiresAt = values.expiresAt;
calls.push("acquire");
return {
onConflictDoUpdate: (config: {
readonly set: { readonly expiresAt: SQL };
readonly setWhere: SQL;
}) => {
updatedExpiresAt = config.set.expiresAt;
leaseExpiryCondition = config.setWhere;
return {
returning: () => Effect.succeed([{ ownerId }]),
};
},
};
},
};
},
delete: (table: unknown) => {
expect(table).toBe(relayEnvironmentLifecycleLeases);
return {
where: () =>
Effect.sync(() => {
calls.push("release");
}),
};
},
} as unknown as RelayDb.RelayDb["Service"];
const layer = RelayDb.RelayTransactions.layer.pipe(
Layer.provide(Layer.succeed(RelayDb.RelayDb, db)),
);
return Effect.gen(function* () {
const transactions = yield* RelayDb.RelayTransactions;
const result = yield* Effect.result(
transactions.withEnvironmentLock(
{ userId: "user-1", environmentId: "environment-1" },
Effect.sync(() => {
calls.push("work");
}).pipe(Effect.andThen(Effect.fail("expected failure" as const))),
),
);
expect(Result.isFailure(result)).toBe(true);
expect(ownerId).not.toBe("");
expect(calls).toEqual(["acquire", "work", "release"]);
const dialect = new PgDialect();
expect(dialect.sqlToQuery(insertedExpiresAt!).sql).toContain("now() + interval '30 seconds'");
expect(dialect.sqlToQuery(updatedExpiresAt!).sql).toContain("now() + interval '30 seconds'");
expect(dialect.sqlToQuery(leaseExpiryCondition!)).toEqual({
sql: '"relay_environment_lifecycle_leases"."expires_at"::timestamptz <= now()',
params: [],
});
}).pipe(Effect.provide(layer));
});
+82
View File
@@ -8,8 +8,12 @@ import type { EffectPgDatabase } from "drizzle-orm/effect-postgres";
import * as Context from "effect/Context";
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
import * as Random from "effect/Random";
import * as Schema from "effect/Schema";
import { and, eq, sql } from "drizzle-orm";
import { relayDatabaseMode } from "./dbConfig.ts";
import { relayEnvironmentLifecycleLeases } from "./persistence/schema.ts";
export class RelayDb extends Context.Service<
RelayDb,
@@ -18,10 +22,87 @@ export class RelayDb extends Context.Service<
}
>()("t3code-relay/db/RelayDb") {}
export class EnvironmentLifecycleLeasePersistenceError extends Schema.TaggedErrorClass<EnvironmentLifecycleLeasePersistenceError>()(
"EnvironmentLifecycleLeasePersistenceError",
{
userId: Schema.String,
environmentId: Schema.String,
cause: Schema.Defect(),
},
) {
override get message(): string {
return `Failed to acquire the lifecycle lease for user '${this.userId}', environment '${this.environmentId}'`;
}
}
function withEnvironmentLock<A, E, R>(
db: RelayDb["Service"],
input: { readonly userId: string; readonly environmentId: string },
effect: Effect.Effect<A, E, R>,
): Effect.Effect<A, E | EnvironmentLifecycleLeasePersistenceError, R> {
return Effect.gen(function* () {
const ownerId = `${yield* Random.nextInt}:${yield* Random.nextInt}`;
const acquire = (): Effect.Effect<void, EnvironmentLifecycleLeasePersistenceError> =>
Effect.suspend(() =>
Effect.gen(function* () {
const expiresAt = sql<string>`to_char((now() + interval '30 seconds') at time zone 'UTC', 'YYYY-MM-DD"T"HH24:MI:SS.MS"Z"')`;
const rows = yield* db
.insert(relayEnvironmentLifecycleLeases)
.values({ ...input, ownerId, expiresAt })
.onConflictDoUpdate({
target: [
relayEnvironmentLifecycleLeases.userId,
relayEnvironmentLifecycleLeases.environmentId,
],
set: { ownerId, expiresAt },
setWhere: sql`${relayEnvironmentLifecycleLeases.expiresAt}::timestamptz <= now()`,
})
.returning({ ownerId: relayEnvironmentLifecycleLeases.ownerId })
.pipe(
Effect.mapError(
(cause) => new EnvironmentLifecycleLeasePersistenceError({ ...input, cause }),
),
);
if (rows[0]?.ownerId !== ownerId) {
yield* Effect.sleep("50 millis");
return yield* acquire();
}
}),
);
const release = db
.delete(relayEnvironmentLifecycleLeases)
.where(
and(
eq(relayEnvironmentLifecycleLeases.userId, input.userId),
eq(relayEnvironmentLifecycleLeases.environmentId, input.environmentId),
eq(relayEnvironmentLifecycleLeases.ownerId, ownerId),
),
)
.pipe(
Effect.catch((error) =>
Effect.logWarning("failed to release relay environment lifecycle lease", {
...input,
ownerId,
error,
}),
),
);
// Public relay requests are capped at nine seconds. A 30-second lease keeps
// a live request fenced while guaranteeing crash recovery without manual
// connection cleanup or provider I/O inside a transaction.
yield* acquire();
return yield* effect.pipe(Effect.ensuring(release));
});
}
export class RelayTransactions extends Context.Service<
RelayTransactions,
{
readonly withTransaction: RelayDb["Service"]["$client"]["withTransaction"];
readonly withEnvironmentLock: <A, E, R>(
input: { readonly userId: string; readonly environmentId: string },
effect: Effect.Effect<A, E, R>,
) => Effect.Effect<A, E | EnvironmentLifecycleLeasePersistenceError, R>;
}
>()("t3code-relay/db/RelayTransactions") {
static readonly layer = Layer.effect(
@@ -30,6 +111,7 @@ export class RelayTransactions extends Context.Service<
const db = yield* RelayDb;
return RelayTransactions.of({
withTransaction: db.$client.withTransaction,
withEnvironmentLock: (input, effect) => withEnvironmentLock(db, input, effect),
});
}),
);
@@ -17,6 +17,7 @@ import * as RelayTokens from "../auth/RelayTokens.ts";
import * as EnvironmentCredentials from "./EnvironmentCredentials.ts";
import * as EnvironmentLinks from "./EnvironmentLinks.ts";
import * as RelayConfiguration from "../Config.ts";
import * as RelayDb from "../db.ts";
import * as EnvironmentLinker from "./EnvironmentLinker.ts";
import * as ManagedEndpointProvider from "./ManagedEndpointProvider.ts";
@@ -110,6 +111,7 @@ function testLayer(input?: {
readonly upsert?: EnvironmentLinks.EnvironmentLinks["Service"]["upsert"];
readonly consume?: DpopProofs.DpopProofReplay["Service"]["consume"];
readonly deprovision?: ManagedEndpointProvider.ManagedEndpointProvider["Service"]["deprovision"];
readonly withEnvironmentLock?: RelayDb.RelayTransactions["Service"]["withEnvironmentLock"];
}) {
return EnvironmentLinker.layer.pipe(
Layer.provideMerge(RelayTokens.layer),
@@ -149,14 +151,19 @@ function testLayer(input?: {
runtime: { providerKind: "cloudflare_tunnel", connectorToken: "connector-token" },
}),
}),
Layer.succeed(RelayDb.RelayTransactions, {
withTransaction: (effect) => effect,
withEnvironmentLock: input?.withEnvironmentLock ?? ((_input, effect) => effect),
}),
),
),
);
}
describe("EnvironmentLinker", () => {
it.effect("uses verified JWT claims when linking an environment", () => {
it.effect("persists verified JWT claims while holding the environment lock", () => {
let persistedEnvironmentId: string | null = null;
let lockHeld = false;
return Effect.gen(function* () {
const { request, payload } = yield* makeRequest;
const linker = yield* EnvironmentLinker.EnvironmentLinker;
@@ -164,13 +171,26 @@ describe("EnvironmentLinker", () => {
expect(result.environmentId).toBe(payload.environmentId);
expect(result.environmentCredential).toBe("t3env_credential_secret");
expect(persistedEnvironmentId).toBe(payload.environmentId);
expect(lockHeld).toBe(false);
}).pipe(
Effect.provide(
testLayer({
upsert: (input) =>
Effect.sync(() => {
expect(lockHeld).toBe(true);
persistedEnvironmentId = input.proof.environmentId;
}),
withEnvironmentLock: (_input, effect) =>
Effect.sync(() => {
lockHeld = true;
}).pipe(
Effect.andThen(effect),
Effect.ensuring(
Effect.sync(() => {
lockHeld = false;
}),
),
),
}),
),
);
@@ -21,6 +21,7 @@ import * as EnvironmentCredentials from "./EnvironmentCredentials.ts";
import * as EnvironmentLinks from "./EnvironmentLinks.ts";
import * as ManagedEndpointProvider from "./ManagedEndpointProvider.ts";
import * as RelayConfiguration from "../Config.ts";
import * as RelayDb from "../db.ts";
export class EnvironmentLinkProofExpired extends Schema.TaggedErrorClass<EnvironmentLinkProofExpired>()(
"EnvironmentLinkProofExpired",
@@ -68,6 +69,7 @@ export type EnvironmentLinkError =
| DpopProofs.DpopProofReplayPersistenceError
| EnvironmentLinks.EnvironmentLinkUpsertPersistenceError
| EnvironmentCredentials.EnvironmentCredentialCreatePersistenceError
| RelayDb.EnvironmentLifecycleLeasePersistenceError
| ManagedEndpointProvider.ManagedEndpointProviderError;
export class EnvironmentLinker extends Context.Service<
@@ -142,6 +144,7 @@ const make = Effect.gen(function* () {
const proofReplay = yield* DpopProofs.DpopProofReplay;
const relayTokens = yield* RelayTokens.RelayTokens;
const config = yield* RelayConfiguration.RelayConfiguration;
const transactions = yield* RelayDb.RelayTransactions;
return EnvironmentLinker.of({
link: Effect.fn("relay.environment_linker.link")(function* (input) {
@@ -287,58 +290,63 @@ const make = Effect.gen(function* () {
stage: "validate_origin",
});
}
// Downgrading a managed link to publish-only must release the tunnel and
// DNS that were provisioned for it — nothing else cleans them up until a
// full unlink. Best effort: a cleanup failure must not block the link
// itself, and the provider treats an absent allocation as already
// deprovisioned, so retrying on every non-tunnel link is cheap.
if (!input.request.managedTunnelsEnabled) {
yield* managedEndpointProvider
.deprovision({
userId: input.userId,
environmentId: verified.environmentId,
})
.pipe(
Effect.tapError((error) =>
Effect.logWarning("managed endpoint deprovision on publish-only link failed", {
return yield* transactions.withEnvironmentLock(
{ userId: input.userId, environmentId: verified.environmentId },
Effect.gen(function* () {
// Downgrading a managed link to publish-only must release the tunnel and
// DNS that were provisioned for it — nothing else cleans them up until a
// full unlink. Best effort: a cleanup failure must not block the link
// itself, and the provider treats an absent allocation as already
// deprovisioned, so retrying on every non-tunnel link is cheap.
if (!input.request.managedTunnelsEnabled) {
yield* managedEndpointProvider
.deprovision({
userId: input.userId,
environmentId: verified.environmentId,
errorTag: error._tag,
}),
),
Effect.ignore,
);
}
const provisioned = input.request.managedTunnelsEnabled
? yield* managedEndpointProvider.provision({
userId: input.userId,
})
.pipe(
Effect.tapError((error) =>
Effect.logWarning("managed endpoint deprovision on publish-only link failed", {
environmentId: verified.environmentId,
errorTag: error._tag,
}),
),
Effect.ignore,
);
}
const provisioned = input.request.managedTunnelsEnabled
? yield* managedEndpointProvider.provision({
userId: input.userId,
environmentId: verified.environmentId,
origin: verified.origin,
})
: null;
const endpoint = provisioned?.endpoint ?? verified.endpoint;
// The secure-endpoint requirement only matters when the relay advertises
// this endpoint for other devices to reach (managed tunnel). Publish-only
// links are reached out of band (e.g. Tailscale) and their stored endpoint
// is never used for routing, so a nominal endpoint is acceptable.
if (input.request.managedTunnelsEnabled && !isSecureManagedEndpoint(endpoint)) {
return yield* new EnvironmentLinkProofInvalid({
userId: input.userId,
environmentId: verified.environmentId,
reason: "endpoint_not_secure",
stage: "validate_endpoint",
});
}
yield* links.upsert({ ...input, proof: verified, endpoint });
const environmentCredential = yield* credentials.create({
environmentId: verified.environmentId,
origin: verified.origin,
})
: null;
const endpoint = provisioned?.endpoint ?? verified.endpoint;
// The secure-endpoint requirement only matters when the relay advertises
// this endpoint for other devices to reach (managed tunnel). Publish-only
// links are reached out of band (e.g. Tailscale) and their stored endpoint
// is never used for routing, so a nominal endpoint is acceptable.
if (input.request.managedTunnelsEnabled && !isSecureManagedEndpoint(endpoint)) {
return yield* new EnvironmentLinkProofInvalid({
userId: input.userId,
environmentId: verified.environmentId,
reason: "endpoint_not_secure",
stage: "validate_endpoint",
});
}
yield* links.upsert({ ...input, proof: verified, endpoint });
const environmentCredential = yield* credentials.create({
environmentId: verified.environmentId,
environmentPublicKey: verified.environmentPublicKey,
});
return {
environmentId: verified.environmentId,
endpoint,
endpointRuntime: provisioned?.runtime ?? null,
environmentCredential,
};
environmentPublicKey: verified.environmentPublicKey,
});
return {
environmentId: verified.environmentId,
endpoint,
endpointRuntime: provisioned?.runtime ?? null,
environmentCredential,
};
}),
);
}),
});
});
@@ -342,6 +342,10 @@ describe("ManagedEndpointProvider", () => {
});
expect(result.runtime.connectorToken).toBe("connector-token");
expect(result.runtime.origin).toEqual({
localHttpHost: "127.0.0.1",
localHttpPort: 3773,
});
}).pipe(Effect.provide(layer));
});
@@ -370,6 +374,7 @@ describe("ManagedEndpointProvider", () => {
connectorToken: "connector-token",
tunnelId: "tunnel-id",
tunnelName: expectedManagedTunnelName("env_ABC"),
origin: { localHttpHost: "127.0.0.1", localHttpPort: 3773 },
},
});
expect(dnsCalls).toEqual([
@@ -851,6 +851,7 @@ export const make = Effect.gen(function* () {
connectorToken,
tunnelId: tunnel.id,
tunnelName: tunnel.name,
origin: input.origin,
},
} satisfies ManagedEndpointProvisioningResult;
}),
+70 -1
View File
@@ -23,6 +23,7 @@ import {
relayDocsRedirectRoute,
relayEnvironmentAuthLayer,
relayNotFoundRoute,
reconcileManagedEndpointRecord,
revokeEnvironmentLinkRecord,
traceRelayHttpRequestWith,
unlinkEnvironmentRecord,
@@ -163,17 +164,20 @@ describe("relay environment authentication", () => {
function relayUnlinkTestLayer(input?: {
readonly withTransaction?: RelayDb.RelayTransactions["Service"]["withTransaction"];
readonly withEnvironmentLock?: RelayDb.RelayTransactions["Service"]["withEnvironmentLock"];
readonly getForUser?: EnvironmentLinks.EnvironmentLinks["Service"]["getForUser"];
readonly revokeForUser?: EnvironmentLinks.EnvironmentLinks["Service"]["revokeForUser"];
readonly revokeCredential?: EnvironmentCredentials.EnvironmentCredentials["Service"]["revokeForEnvironmentPublicKey"];
readonly prepareDeprovision?: ManagedEndpointProvider.ManagedEndpointProvider["Service"]["prepareDeprovision"];
readonly deprovision?: ManagedEndpointProvider.ManagedEndpointProvider["Service"]["deprovision"];
readonly provision?: ManagedEndpointProvider.ManagedEndpointProvider["Service"]["provision"];
}) {
return Layer.mergeAll(
Layer.succeed(
RelayDb.RelayTransactions,
RelayDb.RelayTransactions.of({
withTransaction: input?.withTransaction ?? ((effect) => effect),
withEnvironmentLock: input?.withEnvironmentLock ?? ((_input, effect) => effect),
}),
),
Layer.succeed(
@@ -199,7 +203,7 @@ function relayUnlinkTestLayer(input?: {
Layer.succeed(
ManagedEndpointProvider.ManagedEndpointProvider,
ManagedEndpointProvider.ManagedEndpointProvider.of({
provision: () => Effect.die("unused provision"),
provision: input?.provision ?? (() => Effect.die("unused provision")),
prepareDeprovision: input?.prepareDeprovision ?? (() => Effect.succeed(null)),
deprovision: input?.deprovision ?? (() => Effect.void),
release: () => Effect.die("unused release"),
@@ -275,16 +279,29 @@ describe("relay environment unlink", () => {
}),
).toBe(true);
expect(calls).toEqual([
"lock",
"prepare",
"lookup",
"transaction",
"link",
"credential",
"unlock",
"deprovision",
]);
}).pipe(
Effect.provide(
relayUnlinkTestLayer({
withEnvironmentLock: (_input, effect) =>
Effect.sync(() => {
calls.push("lock");
}).pipe(
Effect.andThen(effect),
Effect.ensuring(
Effect.sync(() => {
calls.push("unlock");
}),
),
),
withTransaction: (effect) => {
calls.push("transaction");
return effect;
@@ -395,6 +412,58 @@ describe("relay environment unlink", () => {
});
});
describe("managed endpoint reconciliation", () => {
it.effect("holds the environment lock across authorization and provisioning", () => {
const calls: Array<string> = [];
return Effect.gen(function* () {
const result = yield* reconcileManagedEndpointRecord({
userId: "user-1",
environmentId: "environment-1",
environmentPublicKey: "public-key",
origin: { localHttpHost: "127.0.0.1", localHttpPort: 3773 },
});
expect(result.runtime.connectorToken).toBe("connector-token");
expect(calls).toEqual(["lock", "lookup", "provision", "unlock"]);
}).pipe(
Effect.provide(
relayUnlinkTestLayer({
withEnvironmentLock: (_input, effect) =>
Effect.sync(() => {
calls.push("lock");
}).pipe(
Effect.andThen(effect),
Effect.ensuring(
Effect.sync(() => {
calls.push("unlock");
}),
),
),
getForUser: () =>
Effect.sync(() => {
calls.push("lookup");
return linkedEnvironmentRecord;
}),
provision: ({ origin }) =>
Effect.sync(() => {
calls.push("provision");
return {
endpoint: linkedEnvironmentRecord.endpoint,
runtime: {
providerKind: "cloudflare_tunnel" as const,
connectorToken: "connector-token",
tunnelId: "tunnel-1",
tunnelName: "environment-1-tunnel",
origin,
},
};
}),
}),
),
);
});
});
describe("relay request tracing", () => {
it.effect(
"does not parent endpoint spans to an ambient parent captured while building handlers",
+96 -24
View File
@@ -47,6 +47,7 @@ import {
RelayEnvironmentPrincipal,
type RelayEnvironmentConnectRequest,
type RelayDpopAccessTokenScope,
type RelayManagedEndpointOrigin,
RelayInternalError,
} from "@t3tools/contracts/relay";
import { normalizeRelayIssuer } from "@t3tools/shared/relayJwt";
@@ -432,38 +433,63 @@ export const revokeEnvironmentLinkRecord = Effect.fn(
export const unlinkEnvironmentRecord = Effect.fn("relay.api.client.unlinkEnvironmentRecord")(
function* (input: { readonly userId: string; readonly environmentId: string }) {
const transactions = yield* RelayDb.RelayTransactions;
const links = yield* EnvironmentLinks.EnvironmentLinks;
const managedEndpointProvider = yield* ManagedEndpointProvider.ManagedEndpointProvider;
const deprovisionTarget = yield* managedEndpointProvider.prepareDeprovision({
userId: input.userId,
environmentId: input.environmentId,
});
const link = yield* links.getForUser({
userId: input.userId,
environmentId: input.environmentId,
});
const unlinked =
link === null
? false
: yield* revokeEnvironmentLinkRecord({
userId: input.userId,
environmentId: link.environmentId,
environmentPublicKey: link.environmentPublicKey,
});
// External teardown cannot share the SQL transaction. Run it only after
// revocation commits so a database failure leaves a fully usable active
// link. Still run teardown when the link is already revoked, allowing a
// retry to finish cleanup after an earlier Cloudflare failure.
const { deprovisionTarget, unlinked } = yield* transactions.withEnvironmentLock(
input,
Effect.gen(function* () {
const deprovisionTarget = yield* managedEndpointProvider.prepareDeprovision(input);
const link = yield* links.getForUser(input);
const unlinked =
link === null
? false
: yield* revokeEnvironmentLinkRecord({
userId: input.userId,
environmentId: link.environmentId,
environmentPublicKey: link.environmentPublicKey,
});
return { deprovisionTarget, unlinked };
}),
);
// External teardown runs after revocation commits and releases the lock.
// Its captured allocation generation keeps a concurrent relink safe while
// still allowing a retry to finish an earlier incomplete cleanup.
yield* managedEndpointProvider.deprovision({
userId: input.userId,
environmentId: input.environmentId,
...input,
target: deprovisionTarget,
});
return unlinked;
},
);
export const reconcileManagedEndpointRecord = Effect.fn(
"relay.api.server.reconcileManagedEndpointRecord",
)(function* (input: {
readonly userId: string;
readonly environmentId: string;
readonly environmentPublicKey: string;
readonly origin: RelayManagedEndpointOrigin;
}) {
const transactions = yield* RelayDb.RelayTransactions;
const links = yield* EnvironmentLinks.EnvironmentLinks;
const managedEndpointProvider = yield* ManagedEndpointProvider.ManagedEndpointProvider;
return yield* transactions.withEnvironmentLock(
input,
Effect.gen(function* () {
const link = yield* links.getForUser(input);
if (
link === null ||
link.environmentPublicKey !== input.environmentPublicKey ||
link.endpoint.providerKind !== "cloudflare_tunnel"
) {
return yield* new HttpApiError.Unauthorized({});
}
return yield* managedEndpointProvider.provision(input);
}),
);
});
export const mobileApi = HttpApiBuilder.group(
RelayApi,
"mobile",
@@ -856,7 +882,7 @@ export const serverApi = HttpApiBuilder.group(
Effect.fnUntraced(function* (handlers) {
const publisher = yield* AgentActivityPublisher.AgentActivityPublisher;
const publishSignatures = yield* EnvironmentPublishSignatures.EnvironmentPublishSignatures;
return handlers.handle(
const publishHandlers = handlers.handle(
"publishAgentActivity",
Effect.fn("relay.api.server.publishAgentActivity")(
function* (args) {
@@ -984,6 +1010,51 @@ export const serverApi = HttpApiBuilder.group(
mapRelayCommonApiErrors("not_authorized"),
),
);
return publishHandlers.handle(
"reconcileManagedEndpoint",
Effect.fn("relay.api.server.reconcileManagedEndpoint")(
function* ({ params, payload }) {
const principal = yield* RelayEnvironmentPrincipal;
if (principal.environmentId !== params.environmentId) {
return yield* new HttpApiError.Unauthorized({});
}
const result = yield* reconcileManagedEndpointRecord({
userId: payload.cloudUserId,
environmentId: params.environmentId,
environmentPublicKey: principal.environmentPublicKey,
origin: payload.origin,
});
return { endpointRuntime: result.runtime };
},
mapErrorTags({
ManagedEndpointProvisioningNotConfigured: (_error, traceId) =>
new RelayEnvironmentLinkUnavailableError({
code: "environment_link_unavailable",
reason: "managed_endpoint_not_configured",
traceId,
}),
ManagedEndpointProvisioningFailed: (_error, traceId) =>
new RelayEnvironmentLinkUnavailableError({
code: "environment_link_unavailable",
reason: "managed_endpoint_provisioning_failed",
traceId,
}),
ManagedEndpointOriginNotAllowed: (_error, traceId) =>
new RelayEnvironmentLinkProofInvalidError({
code: "environment_link_proof_invalid",
reason: "origin_not_allowed",
traceId,
}),
ManagedTunnelLimitExceeded: (limitError, traceId) =>
new RelayEnvironmentLinkLimitExceededError({
code: "environment_link_limit_exceeded",
maxTunnels: limitError.maxTunnels,
traceId,
}),
}),
mapRelayCommonApiErrors("not_authorized"),
),
);
}),
);
@@ -1025,6 +1096,7 @@ const RelayCommonPersistenceError = Schema.Union([
AgentActivityRows.AgentActivityRowListPersistenceError,
LiveActivities.LiveActivityDeliveryMarkPersistenceError,
DeliveryAttempts.DeliveryAttemptRecordPersistenceError,
RelayDb.EnvironmentLifecycleLeasePersistenceError,
]);
type RelayCommonPersistenceError = typeof RelayCommonPersistenceError.Type;
const isRelayCommonPersistenceError = Schema.is(RelayCommonPersistenceError);
+11
View File
@@ -83,6 +83,17 @@ export const relayEnvironmentLinks = pgTable(
],
);
export const relayEnvironmentLifecycleLeases = pgTable(
"relay_environment_lifecycle_leases",
{
userId: varchar("user_id", { length: 191 }).notNull(),
environmentId: varchar("environment_id", { length: 191 }).notNull(),
ownerId: varchar("owner_id", { length: 64 }).notNull(),
expiresAt: varchar("expires_at", { length: 64 }).notNull(),
},
(table) => [primaryKey({ columns: [table.userId, table.environmentId] })],
);
export const relayManagedEndpointAllocations = pgTable(
"relay_managed_endpoint_allocations",
{
@@ -231,8 +231,9 @@ describe("RemoteEnvironmentAuthorization", () => {
}),
);
it.effect("reuses a valid persisted environment token without contacting the relay", () =>
it.effect("refreshes the descriptor while reusing a valid environment token", () =>
Effect.gen(function* () {
const refreshedServerVersion = "0.0.1";
const cached = new TokenStore.RemoteDpopAccessToken({
environmentId: ENVIRONMENT_ID,
label: DESCRIPTOR.label,
@@ -243,7 +244,10 @@ describe("RemoteEnvironmentAuthorization", () => {
});
const harness = yield* makeHarness({
initialToken: cached,
responses: [websocketTicket("cached-ticket")],
responses: [
websocketTicket("cached-ticket"),
Response.json({ ...DESCRIPTOR, serverVersion: refreshedServerVersion }),
],
});
const authorized = yield* Effect.gen(function* () {
@@ -255,11 +259,15 @@ describe("RemoteEnvironmentAuthorization", () => {
}).pipe(Effect.provide(harness.layer));
expect(authorized.socketUrl).toContain("wsTicket=cached-ticket");
expect(authorized.serverVersion).toBe(refreshedServerVersion);
expect(yield* Ref.get(harness.bootstrapCalls)).toBe(0);
expect(harness.fetch.calls).toHaveLength(1);
expect(harness.fetch.calls).toHaveLength(2);
expect(String(harness.fetch.calls[0]?.[0])).toBe(
"https://environment.example.test/api/auth/websocket-ticket",
);
expect(String(harness.fetch.calls[1]?.[0])).toBe(
"https://environment.example.test/.well-known/t3/environment",
);
}),
);
@@ -291,6 +299,7 @@ describe("RemoteEnvironmentAuthorization", () => {
}).pipe(Effect.provide(harness.layer));
expect(authorized.socketUrl).toContain("wsTicket=fresh-ticket");
expect(authorized.serverVersion).toBe(DESCRIPTOR.serverVersion);
expect(yield* Ref.get(harness.bootstrapCalls)).toBe(1);
expect((yield* Ref.get(harness.tokens)).get(ENVIRONMENT_ID)).toEqual(
expect.objectContaining({
@@ -380,6 +389,44 @@ describe("RemoteEnvironmentAuthorization", () => {
}),
);
it.effect("keeps a valid cached token when descriptor refresh fails transiently", () =>
Effect.gen(function* () {
const cached = new TokenStore.RemoteDpopAccessToken({
environmentId: ENVIRONMENT_ID,
label: DESCRIPTOR.label,
endpoint: ENDPOINT,
accessToken: "cached-access-token",
expiresAtEpochMs: Number.MAX_SAFE_INTEGER,
dpopThumbprint: "thumbprint-1",
});
const harness = yield* makeHarness({
initialToken: cached,
responses: [
websocketTicket("cached-ticket"),
new Response("endpoint unavailable", { status: 503 }),
],
});
const authorized = yield* Effect.gen(function* () {
const remote = yield* RemoteEnvironmentAuthorization.RemoteEnvironmentAuthorization;
return yield* remote.authorizeDpop({
expectedEnvironmentId: ENVIRONMENT_ID,
obtainBootstrap: harness.obtainBootstrap,
});
}).pipe(Effect.provide(harness.layer));
expect(authorized.socketUrl).toContain("wsTicket=cached-ticket");
expect(authorized.serverVersion).toBeUndefined();
expect(yield* Ref.get(harness.bootstrapCalls)).toBe(0);
expect((yield* Ref.get(harness.tokens)).get(ENVIRONMENT_ID)).toEqual(
expect.objectContaining({
accessToken: "cached-access-token",
}),
);
expect(harness.fetch.calls).toHaveLength(2);
}),
);
it.effect("does not persist a refreshed token until its websocket ticket succeeds", () =>
Effect.gen(function* () {
const harness = yield* makeHarness({
@@ -33,6 +33,7 @@ export interface RelayEnvironmentAuthorization {
export interface AuthorizedRemoteEnvironment {
readonly environmentId: EnvironmentId;
readonly label: string;
readonly serverVersion?: string;
readonly httpBaseUrl: string;
readonly socketUrl: string;
readonly httpAuthorization: PreparedHttpAuthorization;
@@ -138,6 +139,7 @@ export const make = Effect.gen(function* () {
return {
environmentId: descriptor.environmentId,
label: descriptor.label,
serverVersion: descriptor.serverVersion,
httpBaseUrl: input.httpBaseUrl,
socketUrl,
httpAuthorization: {
@@ -212,6 +214,33 @@ export const make = Effect.gen(function* () {
CACHED_ENDPOINT_SOCKET_TIMEOUT_MS,
).pipe(Effect.result);
if (Result.isSuccess(cachedSocket)) {
const cachedDescriptor = yield* fetchDescriptor(cached.value.endpoint.httpBaseUrl).pipe(
Effect.provideService(HttpClient.HttpClient, httpClient),
Effect.result,
);
if (Result.isSuccess(cachedDescriptor)) {
const descriptor = cachedDescriptor.success;
if (descriptor.environmentId !== input.expectedEnvironmentId) {
return yield* environmentMismatchError({
expected: input.expectedEnvironmentId,
actual: descriptor.environmentId,
});
}
return {
environmentId: descriptor.environmentId,
label: descriptor.label,
serverVersion: descriptor.serverVersion,
httpBaseUrl: cached.value.endpoint.httpBaseUrl,
socketUrl: cachedSocket.success,
httpAuthorization: {
_tag: "Dpop" as const,
accessToken: cached.value.accessToken,
},
};
}
if (cachedDescriptor.failure._tag === "ConnectionBlockedError") {
return yield* cachedDescriptor.failure;
}
return {
environmentId: cached.value.environmentId,
label: cached.value.label,
@@ -222,8 +251,7 @@ export const make = Effect.gen(function* () {
accessToken: cached.value.accessToken,
},
};
}
if (cachedSocket.failure._tag === "ConnectionBlockedError") {
} else if (cachedSocket.failure._tag === "ConnectionBlockedError") {
return yield* mapDpopSocketError(cachedSocket.failure);
}
yield* tokenStore
@@ -286,6 +314,7 @@ export const make = Effect.gen(function* () {
return {
environmentId: descriptor.environmentId,
label: descriptor.label,
serverVersion: descriptor.serverVersion,
httpBaseUrl: bootstrap.endpoint.httpBaseUrl,
socketUrl,
httpAuthorization: {
@@ -12,6 +12,7 @@ export class PrimaryConnectionTarget extends Schema.TaggedClass<PrimaryConnectio
...ConnectionTargetBase,
httpBaseUrl: Schema.String,
wsBaseUrl: Schema.String,
serverVersion: Schema.optionalKey(Schema.String),
},
) {}
@@ -94,6 +95,7 @@ export class ConnectionBlockedError extends Schema.TaggedErrorClass<ConnectionBl
reason: ConnectionBlockedReason,
detail: Schema.String,
traceId: Schema.optionalKey(Schema.String),
serverVersion: Schema.optionalKey(Schema.String),
},
) {
override get message(): string {
@@ -119,6 +121,7 @@ export interface PreparedConnection {
readonly httpBaseUrl: string;
readonly socketUrl: string;
readonly httpAuthorization: PreparedHttpAuthorization | null;
readonly serverVersion?: string;
readonly target: ConnectionTarget;
}
@@ -5,6 +5,7 @@ import * as Option from "effect/Option";
import { BearerConnectionProfile, type ConnectionCatalogEntry } from "./catalog.ts";
import {
BearerConnectionTarget,
ConnectionBlockedError,
ConnectionTransientError,
type SupervisorConnectionState,
} from "./model.ts";
@@ -119,6 +120,28 @@ describe("connection presentation", () => {
});
});
it("preserves compatibility metadata for blocked connections", () => {
expect(
presentConnectionState(
supervisorState({
phase: "blocked",
stage: null,
lastFailure: new ConnectionBlockedError({
reason: "unsupported",
detail: "The client and server could not agree on the RPC protocol.",
serverVersion: "0.0.32-nightly.20260803.4",
}),
}),
),
).toEqual({
phase: "error",
error: "The client and server could not agree on the RPC protocol.",
traceId: null,
blockedReason: "unsupported",
serverVersion: "0.0.32-nightly.20260803.4",
});
});
it("gives offline status precedence in global messaging", () => {
expect(connectionPhaseMessage("connected", TARGET.label, "offline")).toBe("You are offline");
});
@@ -2,7 +2,7 @@ import type { ServerConfig } from "@t3tools/contracts";
import * as Option from "effect/Option";
import type { ConnectionCatalogEntry } from "./catalog.ts";
import type { NetworkStatus, SupervisorConnectionState } from "./model.ts";
import type { ConnectionBlockedReason, NetworkStatus, SupervisorConnectionState } from "./model.ts";
export type EnvironmentConnectionPhase =
| "available"
@@ -16,6 +16,8 @@ export interface EnvironmentConnectionPresentation {
readonly phase: EnvironmentConnectionPhase;
readonly error: string | null;
readonly traceId: string | null;
readonly blockedReason?: ConnectionBlockedReason;
readonly serverVersion?: string;
}
export interface EnvironmentPresentation {
@@ -46,12 +48,22 @@ export function presentConnectionState(
error: state.lastFailure?.message ?? null,
traceId: state.lastFailure?.traceId ?? null,
};
case "blocked":
case "blocked": {
const failure = state.lastFailure;
return {
phase: "error",
error: state.lastFailure?.message ?? null,
traceId: state.lastFailure?.traceId ?? null,
error: failure?.message ?? null,
traceId: failure?.traceId ?? null,
...(failure?._tag === "ConnectionBlockedError"
? {
blockedReason: failure.reason,
...(failure.serverVersion === undefined
? {}
: { serverVersion: failure.serverVersion }),
}
: {}),
};
}
}
}
@@ -210,6 +210,7 @@ describe("ConnectionResolver", () => {
label: "Primary",
httpBaseUrl: "http://127.0.0.1:3777",
wsBaseUrl: "ws://127.0.0.1:3777",
serverVersion: "0.0.32-nightly.20260803.4",
});
expect(yield* broker.prepare(catalogEntry(target))).toEqual({
@@ -218,6 +219,7 @@ describe("ConnectionResolver", () => {
httpBaseUrl: "http://127.0.0.1:3777",
socketUrl: "ws://127.0.0.1:3777/ws",
httpAuthorization: null,
serverVersion: "0.0.32-nightly.20260803.4",
target,
});
}),
@@ -69,6 +69,7 @@ const makePrimaryBroker = Effect.fn("clientRuntime.connection.broker.makePrimary
httpBaseUrl: target.httpBaseUrl,
socketUrl: primarySocketUrl(target),
httpAuthorization: null,
...(target.serverVersion === undefined ? {} : { serverVersion: target.serverVersion }),
target,
} satisfies PreparedConnection;
}
@@ -133,6 +134,9 @@ const makeBearerBroker = Effect.fn("clientRuntime.connection.broker.makeBearer")
httpBaseUrl: authorized.httpBaseUrl,
socketUrl: authorized.socketUrl,
httpAuthorization: authorized.httpAuthorization,
...(authorized.serverVersion === undefined
? {}
: { serverVersion: authorized.serverVersion }),
target,
} satisfies PreparedConnection;
});
@@ -178,6 +182,9 @@ const makeRelayBroker = Effect.fn("clientRuntime.connection.broker.makeRelay")(f
httpBaseUrl: authorized.httpBaseUrl,
socketUrl: authorized.socketUrl,
httpAuthorization: authorized.httpAuthorization,
...(authorized.serverVersion === undefined
? {}
: { serverVersion: authorized.serverVersion }),
target,
} satisfies PreparedConnection;
},
@@ -236,6 +243,9 @@ const makeSshBroker = Effect.fn("clientRuntime.connection.broker.makeSsh")(funct
httpBaseUrl: authorized.httpBaseUrl,
socketUrl: authorized.socketUrl,
httpAuthorization: authorized.httpAuthorization,
...(authorized.serverVersion === undefined
? {}
: { serverVersion: authorized.serverVersion }),
target,
} satisfies PreparedConnection;
});
@@ -14,6 +14,7 @@ import * as TestClock from "effect/testing/TestClock";
import * as Socket from "effect/unstable/socket/Socket";
import {
ConnectionBlockedError,
ConnectionTransientError,
PrimaryConnectionTarget,
type PreparedConnection,
@@ -360,6 +361,53 @@ describe("RpcSessionFactory", () => {
),
);
it.effect("parks malformed or incompatible RPC responses as unsupported", () =>
Effect.gen(function* () {
const { factory, sockets } = yield* makeFactory();
const serverVersion = "0.0.32-nightly.20260803.4";
const error = yield* Effect.scoped(
Effect.gen(function* () {
const session = yield* factory.connect({ ...PREPARED, serverVersion });
const readyFiber = yield* Effect.forkChild(Effect.flip(session.ready));
const socket = yield* awaitSocket(sockets);
socket.open();
yield* completeInitialConfig(socket, {});
return yield* Fiber.join(readyFiber);
}),
);
expect(error).toBeInstanceOf(ConnectionBlockedError);
expect(error).toMatchObject({
reason: "unsupported",
serverVersion,
message:
"The client and server could not agree on the RPC protocol. Update the older side, then reconnect.",
});
}),
);
it.effect("treats malformed RPC transport messages as retryable", () =>
Effect.gen(function* () {
const { factory, sockets } = yield* makeFactory();
const error = yield* Effect.scoped(
Effect.gen(function* () {
const session = yield* factory.connect(PREPARED);
const readyFiber = yield* Effect.forkChild(Effect.flip(session.ready));
const socket = yield* awaitSocket(sockets);
socket.open();
yield* awaitRequest(socket);
socket.serverMessage("not-json");
return yield* Fiber.join(readyFiber);
}),
);
expect(error).toBeInstanceOf(ConnectionTransientError);
expect(error).toMatchObject({ reason: "transport" });
}),
);
it.effect("fails readiness when the websocket never opens", () =>
Effect.gen(function* () {
const { factory, sockets } = yield* makeFactory();
+40 -6
View File
@@ -1,9 +1,12 @@
import { type ServerConfig, WS_METHODS } from "@t3tools/contracts";
import * as Cause from "effect/Cause";
import * as Context from "effect/Context";
import * as Deferred from "effect/Deferred";
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
import * as Result from "effect/Result";
import * as Schedule from "effect/Schedule";
import * as Schema from "effect/Schema";
import type * as Scope from "effect/Scope";
import * as RpcClient from "effect/unstable/rpc/RpcClient";
import * as RpcSerialization from "effect/unstable/rpc/RpcSerialization";
@@ -44,6 +47,15 @@ type InitialConfigError = Effect.Error<
>;
type ProbeError = Effect.Error<ReturnType<WsRpcProtocolClient[typeof WS_METHODS.serverProbe]>>;
function unsupportedProtocolError(serverVersion: string | undefined): ConnectionBlockedError {
return new ConnectionBlockedError({
reason: "unsupported",
detail:
"The client and server could not agree on the RPC protocol. Update the older side, then reconnect.",
...(serverVersion === undefined ? {} : { serverVersion }),
});
}
function mapSessionRpcError(error: InitialConfigError | ProbeError): ConnectionAttemptError {
switch (error._tag) {
case "EnvironmentAuthorizationError":
@@ -65,6 +77,21 @@ function mapSessionRpcError(error: InitialConfigError | ProbeError): ConnectionA
}
}
function mapRpcSchemaDefect<A, E, R>(
effect: Effect.Effect<A, E, R>,
serverVersion: string | undefined,
): Effect.Effect<A, E | ConnectionBlockedError, R> {
return effect.pipe(
Effect.catchCause((cause): Effect.Effect<never, E | ConnectionBlockedError> => {
const defect = Cause.findDefect(cause);
if (Result.isSuccess(defect) && Schema.isSchemaError(defect.success)) {
return Effect.fail(unsupportedProtocolError(serverVersion));
}
return Effect.failCause(cause);
}),
);
}
export const make = Effect.gen(function* () {
const webSocketConstructor = yield* Socket.WebSocketConstructor;
@@ -117,16 +144,23 @@ export const make = Effect.gen(function* () {
const initialConfig = yield* Effect.cached(
client[WS_METHODS.serverGetConfig]({}).pipe(
Effect.mapError(mapSessionRpcError),
(effect) => mapRpcSchemaDefect(effect, connection.serverVersion),
Effect.withSpan("environment.initialSync"),
),
);
const probe = initialConfig.pipe(
Effect.flatMap((config) =>
(config.environment.capabilities.connectionProbe === true
? client[WS_METHODS.serverProbe]({})
: client[WS_METHODS.serverGetConfig]({})
).pipe(Effect.mapError(mapSessionRpcError)),
),
Effect.flatMap((config) => {
if (config.environment.capabilities.connectionProbe === true) {
return client[WS_METHODS.serverProbe]({}).pipe(
Effect.mapError(mapSessionRpcError),
(effect) => mapRpcSchemaDefect(effect, connection.serverVersion),
);
}
return client[WS_METHODS.serverGetConfig]({}).pipe(
Effect.mapError(mapSessionRpcError),
(effect) => mapRpcSchemaDefect(effect, connection.serverVersion),
);
}),
Effect.asVoid,
Effect.withSpan("clientRuntime.connection.rpcSession.probe"),
);
@@ -1,194 +0,0 @@
import { EnvironmentId, ProjectId } from "@t3tools/contracts";
import { describe, expect, it } from "vite-plus/test";
import type { EnvironmentProject } from "./models.ts";
import {
buildProjectGroups,
derivePhysicalProjectKey,
type ProjectGroupingSettings,
} from "./projectGrouping.ts";
const environmentId = EnvironmentId.make("environment");
const repositoryIdentity = {
canonicalKey: "github.com/t3tools/t3code",
locator: {
source: "git-remote" as const,
remoteName: "upstream",
remoteUrl: "https://github.com/t3tools/t3code.git",
},
provider: "github",
owner: "t3tools",
name: "t3code",
displayName: "T3 Code",
};
function makeProject(
id: string,
workspaceRoot: string,
overrides: Partial<EnvironmentProject> = {},
): EnvironmentProject {
return {
environmentId,
id: ProjectId.make(id),
title: id,
workspaceRoot,
repositoryIdentity,
defaultModelSelection: null,
scripts: [],
createdAt: "2026-07-01T00:00:00.000Z",
updatedAt: "2026-07-01T00:00:00.000Z",
...overrides,
};
}
function settings(
mode: ProjectGroupingSettings["sidebarProjectGroupingMode"],
overrides: ProjectGroupingSettings["sidebarProjectGroupingOverrides"] = {},
): ProjectGroupingSettings {
return {
sidebarProjectGroupingMode: mode,
sidebarProjectGroupingOverrides: overrides,
};
}
describe("buildProjectGroups", () => {
it("preserves every physical clone as a selectable member in repository modes", () => {
const projects = [
makeProject("t3code", "/work/t3code"),
makeProject("t3code-2", "/work/t3code-2"),
makeProject("t3code-3", "/work/t3code-3"),
];
for (const mode of ["repository", "repository_path"] as const) {
const groups = buildProjectGroups({ projects, settings: settings(mode) });
expect(groups).toHaveLength(1);
expect(groups[0]?.members.map((member) => member.project.id)).toEqual([
"t3code",
"t3code-2",
"t3code-3",
]);
expect(groups[0]?.memberProjectRefs).toHaveLength(3);
}
});
it("keeps physical clones in separate groups when requested", () => {
const projects = [
makeProject("t3code", "/work/t3code"),
makeProject("t3code-2", "/work/t3code-2"),
makeProject("t3code-3", "/work/t3code-3"),
];
const groups = buildProjectGroups({ projects, settings: settings("separate") });
expect(groups).toHaveLength(3);
expect(groups.flatMap((group) => group.members)).toHaveLength(3);
expect(groups.map((group) => group.label)).toEqual(["t3code", "t3code-2", "t3code-3"]);
});
it("applies a physical-project override without dropping its siblings", () => {
const first = makeProject("t3code", "/work/t3code");
const second = makeProject("t3code-2", "/work/t3code-2");
const third = makeProject("t3code-3", "/work/t3code-3");
const groups = buildProjectGroups({
projects: [first, second, third],
settings: settings("repository", {
[derivePhysicalProjectKey(second)]: "separate",
}),
});
expect(groups).toHaveLength(2);
expect(groups.flatMap((group) => group.members.map((member) => member.project.id))).toEqual([
"t3code",
"t3code-3",
"t3code-2",
]);
});
it("dedupes stale registrations at one physical path using the freshest project", () => {
const stale = makeProject("stale", "/work/t3code", {
repositoryIdentity: null,
updatedAt: "2026-07-01T00:00:00.000Z",
});
const fresh = makeProject("fresh", "/work/t3code/", {
updatedAt: "2026-07-02T00:00:00.000Z",
});
const groups = buildProjectGroups({
projects: [stale, fresh],
settings: settings("repository"),
});
expect(groups).toHaveLength(1);
expect(groups[0]?.members).toHaveLength(1);
expect(groups[0]?.representative.id).toBe("fresh");
expect(groups[0]?.memberProjectRefs).toHaveLength(2);
});
it("uses repository identity from a duplicate registration when the winner lacks it", () => {
const identified = makeProject("identified", "/work/t3code", {
updatedAt: "2026-07-01T00:00:00.000Z",
});
const freshUnidentified = makeProject("fresh", "/work/t3code/", {
repositoryIdentity: null,
updatedAt: "2026-07-02T00:00:00.000Z",
});
const sibling = makeProject("sibling", "/work/t3code-2");
const groups = buildProjectGroups({
projects: [identified, freshUnidentified, sibling],
settings: settings("repository"),
});
expect(groups).toHaveLength(1);
expect(groups[0]?.members.map((member) => member.project.id)).toEqual(["fresh", "sibling"]);
});
it("uses the freshest winner's repository identity when stale duplicates disagree", () => {
const staleIdentity = {
...repositoryIdentity,
canonicalKey: "github.com/t3tools/old-repository",
name: "old-repository",
displayName: "Old Repository",
};
const stale = makeProject("stale", "/work/t3code", {
repositoryIdentity: staleIdentity,
updatedAt: "2026-07-01T00:00:00.000Z",
});
const fresh = makeProject("fresh", "/work/t3code/", {
updatedAt: "2026-07-02T00:00:00.000Z",
});
const sibling = makeProject("sibling", "/work/t3code-2");
const groups = buildProjectGroups({
projects: [stale, fresh, sibling],
settings: settings("repository"),
});
expect(groups).toHaveLength(1);
expect(groups[0]?.members.map((member) => member.project.id)).toEqual(["fresh", "sibling"]);
});
it("uses the freshest identity-bearing duplicate when the winner lacks identity", () => {
const staleIdentity = {
...repositoryIdentity,
canonicalKey: "github.com/t3tools/old-repository",
name: "old-repository",
displayName: "Old Repository",
};
const staleIdentified = makeProject("stale-identified", "/work/t3code", {
repositoryIdentity: staleIdentity,
updatedAt: "2026-07-01T00:00:00.000Z",
});
const freshIdentified = makeProject("fresh-identified", "/work/t3code/", {
updatedAt: "2026-07-02T00:00:00.000Z",
});
const winner = makeProject("winner", "/work/t3code", {
repositoryIdentity: null,
updatedAt: "2026-07-03T00:00:00.000Z",
});
const sibling = makeProject("sibling", "/work/t3code-2");
const groups = buildProjectGroups({
projects: [staleIdentified, freshIdentified, winner, sibling],
settings: settings("repository"),
});
expect(groups).toHaveLength(1);
expect(groups[0]?.members.map((member) => member.project.id)).toEqual(["winner", "sibling"]);
});
});
@@ -1,9 +1,5 @@
import { scopedProjectKey, scopeProjectRef } from "../environment/scoped.ts";
import type {
EnvironmentId,
ScopedProjectRef,
SidebarProjectGroupingMode,
} from "@t3tools/contracts";
import type { ScopedProjectRef, SidebarProjectGroupingMode } from "@t3tools/contracts";
import type { ClientSettings } from "@t3tools/contracts/settings";
import type { EnvironmentProject } from "./models.ts";
@@ -185,141 +181,3 @@ export function deriveProjectGroupLabel(input: {
return input.representative.title;
}
export interface ProjectGroupMember<TProject extends EnvironmentProject = EnvironmentProject> {
readonly physicalProjectKey: string;
readonly project: TProject;
}
export interface ProjectGroup<TProject extends EnvironmentProject = EnvironmentProject> {
readonly key: string;
readonly label: string;
readonly representative: TProject;
readonly members: ReadonlyArray<ProjectGroupMember<TProject>>;
readonly memberProjectRefs: ReadonlyArray<ScopedProjectRef>;
}
function projectFreshnessTime(project: EnvironmentProject): number {
const updatedAtTime = Date.parse(project.updatedAt);
if (Number.isFinite(updatedAtTime)) {
return updatedAtTime;
}
const createdAtTime = Date.parse(project.createdAt);
return Number.isFinite(createdAtTime) ? createdAtTime : 0;
}
function shouldReplacePhysicalProjectWinner<TProject extends EnvironmentProject>(
existing: TProject,
candidate: TProject,
): boolean {
const freshnessDelta = projectFreshnessTime(candidate) - projectFreshnessTime(existing);
return freshnessDelta > 0 || (freshnessDelta === 0 && candidate.id > existing.id);
}
function selectProjectIdentitySource<TProject extends EnvironmentProject>(
projects: ReadonlyArray<TProject>,
winner: TProject,
): TProject {
if (winner.repositoryIdentity !== null) {
return winner;
}
let freshestIdentifiedProject: TProject | null = null;
for (const project of projects) {
if (project.repositoryIdentity === null) {
continue;
}
if (
freshestIdentifiedProject === null ||
shouldReplacePhysicalProjectWinner(freshestIdentifiedProject, project)
) {
freshestIdentifiedProject = project;
}
}
return freshestIdentifiedProject ?? winner;
}
/**
* Builds logical project groups without losing the physical projects that
* remain the actual navigation and task-creation targets.
*
* Presentation-specific metadata, filtering, and activity sorting stay in
* each client. Grouping modes, overrides, physical deduplication, labels, and
* member preservation live here so web and mobile cannot drift.
*/
export function buildProjectGroups<TProject extends EnvironmentProject>(input: {
readonly projects: ReadonlyArray<TProject>;
readonly settings: ProjectGroupingSettings;
readonly preferredEnvironmentId?: EnvironmentId | null;
}): ReadonlyArray<ProjectGroup<TProject>> {
const projectsByPhysicalKey = new Map<string, TProject[]>();
for (const project of input.projects) {
const physicalProjectKey = derivePhysicalProjectKey(project);
const existing = projectsByPhysicalKey.get(physicalProjectKey);
if (existing) {
existing.push(project);
} else {
projectsByPhysicalKey.set(physicalProjectKey, [project]);
}
}
const logicalKeyByPhysicalKey = new Map<string, string>();
const groupedMembers = new Map<string, ProjectGroupMember<TProject>[]>();
for (const [physicalProjectKey, physicalProjects] of projectsByPhysicalKey) {
const winner = physicalProjects.reduce((current, candidate) =>
shouldReplacePhysicalProjectWinner(current, candidate) ? candidate : current,
);
const identitySource = selectProjectIdentitySource(physicalProjects, winner);
const logicalKey = deriveLogicalProjectKey(identitySource, {
groupingMode: resolveProjectGroupingMode(winner, input.settings),
});
logicalKeyByPhysicalKey.set(physicalProjectKey, logicalKey);
const member = { physicalProjectKey, project: winner };
const existing = groupedMembers.get(logicalKey);
if (existing) {
existing.push(member);
} else {
groupedMembers.set(logicalKey, [member]);
}
}
const projectRefsByLogicalKey = new Map<string, ScopedProjectRef[]>();
const seenProjectRefs = new Set<string>();
for (const project of input.projects) {
const physicalProjectKey = derivePhysicalProjectKey(project);
const logicalKey =
logicalKeyByPhysicalKey.get(physicalProjectKey) ??
deriveLogicalProjectKeyFromSettings(project, input.settings);
const projectRefKey = scopedProjectKey(scopeProjectRef(project.environmentId, project.id));
if (seenProjectRefs.has(projectRefKey)) continue;
seenProjectRefs.add(projectRefKey);
const projectRef = scopeProjectRef(project.environmentId, project.id);
const existing = projectRefsByLogicalKey.get(logicalKey);
if (existing) {
existing.push(projectRef);
} else {
projectRefsByLogicalKey.set(logicalKey, [projectRef]);
}
}
const preferredEnvironmentId = input.preferredEnvironmentId ?? null;
return Array.from(groupedMembers, ([key, members]) => {
const representative =
(preferredEnvironmentId
? members.find((member) => member.project.environmentId === preferredEnvironmentId)?.project
: null) ?? members[0]!.project;
return {
key,
label:
members.length > 1
? deriveProjectGroupLabel({
representative,
members: members.map((member) => member.project),
})
: representative.title,
representative,
members,
memberProjectRefs: projectRefsByLogicalKey.get(key) ?? [],
};
});
}
@@ -7,16 +7,12 @@ 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";
@@ -34,7 +30,6 @@ import {
makeEnvironmentServerConfigState,
isLegacyUpdateHandoffLoss,
matchesServerUpdateReadyEvent,
nudgeReconnectDuringUpdateRestart,
projectServerWelcome,
resolveServerConfigValue,
resolveServerUpdateProgressResult,
@@ -76,56 +71,6 @@ 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);
+12 -36
View File
@@ -149,35 +149,6 @@ 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,
@@ -618,13 +589,18 @@ export function createServerEnvironmentAtoms<R, E>(
}),
);
// 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);
// 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,
);
const resumed = yield* environmentRegistry
.followStream(target.environmentId, subscribe(WS_METHODS.subscribeServerLifecycle, {}))
@@ -23,19 +23,6 @@ it("creates stable keys regardless of environment order", () => {
);
});
it("creates keys without array methods unavailable in Hermes", () => {
const descriptor = Object.getOwnPropertyDescriptor(Array.prototype, "toSorted");
Reflect.deleteProperty(Array.prototype, "toSorted");
try {
expect(makeThreadSearchKey([envB, envA], "needle")).toBe('[["env-a","env-b"],"needle"]');
} finally {
if (descriptor !== undefined) {
Reflect.defineProperty(Array.prototype, "toSorted", descriptor);
}
}
});
it("encodes scoped thread keys without delimiter collisions", () => {
const first = threadSearchMatchKey({
environmentId: EnvironmentId.make("env\u0000thread"),
@@ -28,7 +28,7 @@ export function makeThreadSearchKey(
query: string,
): string {
return JSON.stringify([
[...environmentIds].sort((left, right) => left.localeCompare(right)),
[...environmentIds].toSorted((left, right) => left.localeCompare(right)),
query,
]);
}
+27 -1
View File
@@ -156,9 +156,23 @@ export const RelayManagedEndpointRuntimeConfig = Schema.Struct({
connectorToken: TrimmedNonEmptyString,
tunnelId: Schema.optional(TrimmedNonEmptyString),
tunnelName: Schema.optional(TrimmedNonEmptyString),
// Optional for compatibility with runtime configs persisted by older servers.
origin: Schema.optional(RelayManagedEndpointOrigin),
});
export type RelayManagedEndpointRuntimeConfig = typeof RelayManagedEndpointRuntimeConfig.Type;
export const RelayManagedEndpointReconcileRequest = Schema.Struct({
cloudUserId: TrimmedNonEmptyString,
origin: RelayManagedEndpointOrigin,
});
export type RelayManagedEndpointReconcileRequest = typeof RelayManagedEndpointReconcileRequest.Type;
export const RelayManagedEndpointReconcileResponse = Schema.Struct({
endpointRuntime: RelayManagedEndpointRuntimeConfig,
});
export type RelayManagedEndpointReconcileResponse =
typeof RelayManagedEndpointReconcileResponse.Type;
export const RelayLinkProofRequest = Schema.Struct({
challenge: Schema.String,
relayIssuer: Schema.String,
@@ -1066,8 +1080,20 @@ export const RelayServerGroup = HttpApiGroup.make("server")
error: RelayAgentActivityPublishErrors,
},
).annotate(OpenApi.Summary, "Publish agent activity"),
HttpApiEndpoint.post(
"reconcileManagedEndpoint",
"/v1/environments/:environmentId/managed-endpoint/reconcile",
{
params: Schema.Struct({
environmentId: EnvironmentId,
}),
payload: RelayManagedEndpointReconcileRequest,
success: RelayManagedEndpointReconcileResponse,
error: RelayEnvironmentLinkErrors,
},
).annotate(OpenApi.Summary, "Reconcile a managed endpoint origin"),
)
.annotate(OpenApi.Description, "Environment-authenticated activity publication.")
.annotate(OpenApi.Description, "Environment-authenticated relay operations.")
.middleware(RelayEnvironmentAuth);
export const RelayApi = HttpApi.make("RelayApi")
+16
View File
@@ -314,10 +314,26 @@ describe("tailscale", () => {
// The diagnostic classifies the failure without quoting stderr, so the
// key cannot reach a log through it either.
assert.equal(error.stderrDiagnostic, "permission-denied");
assert.include(error.message, "exited with code 1");
assert.include(error.message, "sudo tailscale set --operator=$USER");
assertCarriesNoSecret(error, "tskey-auth-secret-token-value");
});
});
it("does not suggest a Unix permission command on Windows", () => {
const error = new TailscaleCommandExitError({
executable: "tailscale.exe",
subcommand: "serve",
argumentCount: 4,
exitCode: 1,
stderrLength: 24,
stderrDiagnostic: "permission-denied",
});
assert.include(error.message, "Grant this Windows user permission");
assert.notInclude(error.message, "sudo");
});
it.effect("disables tailscale serve through the process spawner service", () => {
const commands: {
readonly command: string;
+6
View File
@@ -94,6 +94,12 @@ export class TailscaleCommandExitError extends Schema.TaggedErrorClass<Tailscale
},
) {
override get message(): string {
if (this.stderrDiagnostic === "permission-denied" && this.subcommand === "serve") {
if (this.executable === "tailscale.exe") {
return `tailscale serve exited with code ${this.exitCode}: access denied. Grant this Windows user permission to manage Tailscale, then retry.`;
}
return `tailscale serve exited with code ${this.exitCode}: access denied. Run \`sudo tailscale set --operator=$USER\`, then retry.`;
}
return `tailscale ${this.subcommand} exited with code ${this.exitCode}.`;
}
}
+7 -17
View File
@@ -44,27 +44,17 @@ 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 = [
`${SHOWCASE_TERMINAL_PROMPT}vpr dev`,
"\u001b[38;5;75m~/Code/t3code\u001b[0m \u001b[38;5;212mfeat/remote-command-center\u001b[0m",
"$ vp test run --changed",
"",
" \u001b[1;32mVITE\u001b[0m \u001b[32mv7.1.1\u001b[0m \u001b[2mready in\u001b[0m \u001b[1m1.24s\u001b[0m",
" \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[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[32m✨ 612 tests passed\u001b[0m · 3 environments online",
"",
" \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,
"\u001b[38;5;75m~/Code/t3code\u001b[0m \u001b[38;5;212mfeat/remote-command-center\u001b[0m $ ",
].join("\r\n");
const BASE_ENVIRONMENT_PRESENCE = `export function environmentLabel(count: number): string {