Compare commits

..
Author SHA1 Message Date
t3-code[bot] c6d51046f1 fix(mobile): avoid fading liquid glass cards 2026-08-06 03:43:01 +00:00
t3-code[bot] c892ac29d4 fix(mobile): use glass for pending cards 2026-08-06 03:31:02 +00:00
Theo BrowneandClaude Fable 5 990bb0b689 fix: reconnect faster after remote server updates (#5404)
Co-authored-by: Claude Fable 5 <[email protected]>
2026-08-05 19:12:52 -07:00
Julius Marminge 7251f1a1f1 Prevent terminal loading flash (#5432) 2026-08-05 23:09:23 +02:00
t3-code[bot] 30e471530b fix(web): preserve terminal font size when splitting (#5444)
Co-authored-by: t3-code[bot] <269035359+t3-code[bot]@users.noreply.github.com>
2026-08-05 17:02:53 -04:00
Julius Marminge de592a00e8 Enrich terminal font previews (#5428) 2026-08-05 16:03:10 +00:00
Wout Stiens 2a04db134c fix(web): keep terminal font settings reliable (#5397) 2026-08-05 13:42:56 +02:00
Theo Browne 37d3667de4 fix(web): keep model picker shortcuts in sync (#5400) 2026-08-05 04:23:18 -07:00
Theo Browne 9697b765e5 fix(ci): isolate releases from shared API rate limits (#5394) 2026-08-05 02:36:10 -07:00
Wout Stiens 9d9a872bcc fix(web): restore terminal link hover styles (#5382) 2026-08-05 11:20:17 +02:00
Wout Stiens 9235c83eb7 fix(web): keep the composer command menu anchored to the composer (#5336) 2026-08-05 11:19:58 +02:00
shivamandT3 Code Test e0c85a20ef fix(mobile): avoid double dividers between thread sections (#5391)
Co-authored-by: T3 Code Test <[email protected]>
2026-08-05 13:28:10 +05:30
Fllip 3c5bdb84a9 fix(web): truncate long project switcher names (#5348) 2026-08-05 02:03:56 -04:00
shivam 70de6e1786 fix(mobile): prevent Android thread search crash (#5386) 2026-08-05 11:30:10 +05:30
shivamandT3 Code Test 47dfc65265 fix(mobile): preserve grouped project workspaces (#4642)
Co-authored-by: T3 Code Test <[email protected]>
2026-08-05 10:51:35 +05:30
Theo Browne 41ebf22eea fix(web): clear main branch lint warnings (#5384) 2026-08-04 21:31:39 -07:00
Hwanseo Choi 3d429662c9 fix(mcp): unblock Kimi models in OpenCode with preview tools (#5128) 2026-08-04 23:03:15 -04:00
82 changed files with 1850 additions and 2148 deletions

No files matched your search

-22
View File
@@ -1,22 +0,0 @@
.git
.repos
.t3
.vite-plus
node_modules
apps/*/node_modules
packages/*/node_modules
apps/*/dist
packages/*/dist
release
release-mock
artifacts
native/**/target
*.log
.env
.env.*
!.env.example
*.key
*.pem
auth.json
.codex
.claude
+6 -12
View File
@@ -747,15 +747,9 @@ 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:
@@ -823,7 +817,7 @@ jobs:
- name: Publish release
if: needs.preflight.outputs.previous_tag != ''
uses: softprops/action-gh-release@v2
uses: softprops/action-gh-release@v3
with:
tag_name: ${{ needs.preflight.outputs.tag }}
target_commitish: ${{ needs.preflight.outputs.ref }}
@@ -840,11 +834,11 @@ jobs:
release-assets/*.blockmap
release-assets/*.yml
fail_on_unmatched_files: true
token: ${{ steps.app_token.outputs.token }}
token: ${{ github.token }}
- name: Publish first release
if: needs.preflight.outputs.previous_tag == ''
uses: softprops/action-gh-release@v2
uses: softprops/action-gh-release@v3
with:
tag_name: ${{ needs.preflight.outputs.tag }}
target_commitish: ${{ needs.preflight.outputs.ref }}
@@ -860,7 +854,7 @@ jobs:
release-assets/*.blockmap
release-assets/*.yml
fail_on_unmatched_files: true
token: ${{ steps.app_token.outputs.token }}
token: ${{ github.token }}
deploy_web:
name: Deploy hosted web app
-1
View File
@@ -69,7 +69,6 @@ Full docs live in [docs/](./docs). There's no docs site yet.
- [Permission modes](./docs/user/permission-modes.md)
- [Keyboard shortcuts](./docs/user/keybindings.md)
- [Remote access from a phone or another machine](./docs/user/remote-access.md)
- [Deploy a cloud environment on Render](./docs/user/render.md)
- [Keeping app and server in sync](./docs/user/updating.md)
- [Source control integrations](./docs/user/source-control.md)
- Multiple accounts: [Codex](./docs/user/providers-codex.md) · [Claude](./docs/user/providers-claude.md)
+8
View File
@@ -47,6 +47,7 @@ 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 {
@@ -175,6 +176,13 @@ 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="size-11 items-center justify-center"
className="-mr-2 size-11 items-center justify-center"
>
<SymbolView
name="chevron.left"
+8 -1
View File
@@ -694,7 +694,11 @@ export function HomeScreen(props: HomeScreenProps) {
);
const renderV2Item = useCallback(
({ item }: { readonly item: ThreadListV2ListItem }) => {
({ 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);
if (item.type === "v2-pending") {
const pendingScopeKey = scopedProjectKey(
item.pendingTask.message.environmentId,
@@ -712,6 +716,7 @@ export function HomeScreen(props: HomeScreenProps) {
: null
}
showPendingDivider={item.showPendingDivider}
showTrailingDivider={showTrailingDivider}
onSelectPendingTask={props.onSelectPendingTask}
onDeletePendingTask={props.onDeletePendingTask}
/>
@@ -744,6 +749,7 @@ 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
}
@@ -814,6 +820,7 @@ export function HomeScreen(props: HomeScreenProps) {
serverConfigs,
settlementEnvironmentIds,
snoozeEnvironmentIds,
threadListV2Items,
threadSearchMatchByKey,
toggleSettledShelf,
toggleSnoozedShelf,
@@ -31,12 +31,6 @@ 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;
@@ -76,7 +70,9 @@ 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 repository label for a singleton repository scope", () => {
it("uses the physical project title for a singleton 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("codething-mvp");
expect(groups[0]?.title).toBe("codething-mvp");
expect(scopes[0]?.title).toBe("local-worktree-name");
expect(groups[0]?.title).toBe("local-worktree-name");
});
it("sorts the newest thread first regardless of snapshot order", () => {
@@ -565,10 +565,16 @@ describe("buildHomeThreadGroups", () => {
);
expect(buildGroups(projects, threads, { projectGroupingMode: "repository" })).toHaveLength(1);
expect(buildGroups(projects, threads, { projectGroupingMode: "repository_path" })).toHaveLength(
2,
);
expect(buildGroups(projects, threads, { projectGroupingMode: "separate" })).toHaveLength(2);
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"]);
});
it("default view shows only threads from the last 5 days", () => {
+18 -63
View File
@@ -1,5 +1,5 @@
import {
deriveLogicalProjectKey,
buildProjectGroups,
derivePhysicalProjectKey,
deriveProjectGroupLabel,
} from "@t3tools/client-runtime/state/project-grouping";
@@ -37,10 +37,6 @@ 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,
@@ -60,64 +56,19 @@ export function buildHomeProjectScopes(input: {
const projects = input.projects.filter(
(project) => input.environmentId === null || project.environmentId === input.environmentId,
);
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 buildProjectGroups({
projects,
settings: {
sidebarProjectGroupingMode: input.projectGroupingMode,
sidebarProjectGroupingOverrides: {},
},
}).map((group) => {
return {
key,
title: deriveProjectGroupLabel({ representative, members: projects }),
representative,
projects,
projectRefs: projectRefsByGroup.get(key) ?? [],
key: group.key,
title: group.label,
representative: group.representative,
projects: group.members.map((member) => member.project),
projectRefs: group.memberProjectRefs,
};
});
}
@@ -264,9 +215,11 @@ 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],
@@ -345,7 +298,9 @@ export function buildHomeThreadGroups(input: {
continue;
}
const title = deriveProjectGroupLabel({ representative, members: group.projects });
const title =
groupTitleByKey.get(group.key) ??
deriveProjectGroupLabel({ representative, members: group.projects });
const groupMatches =
query.length === 0 ||
title.toLocaleLowerCase().includes(query) ||
@@ -37,11 +37,15 @@ 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, resolveProjectGroupingMode } from "../home/home-list-options";
import { HomeListOptionsProvider } from "../home/home-list-options";
import { ThreadNavigationSidebar } from "../threads/ThreadNavigationSidebar";
import { WORKSPACE_PANE_TIMING } from "./workspace-pane-animation";
import { WorkspaceInspectorPane } from "./workspace-inspector-pane";
@@ -190,15 +194,17 @@ export function AdaptiveWorkspaceLayout(props: {
const preferencesResult = useAtomValue(mobilePreferencesAtom);
if (!AsyncResult.isSuccess(preferencesResult)) {
return AsyncResult.isFailure(preferencesResult) ? (
<AdaptiveWorkspaceLayoutContent {...props} projectGroupingMode="repository" />
<AdaptiveWorkspaceLayoutContent
{...props}
projectGroupingMode={DEFAULT_MOBILE_PROJECT_GROUPING_SETTINGS.sidebarProjectGroupingMode}
/>
) : null;
}
const groupingSettings = resolveMobileProjectGroupingSettings(preferencesResult.value);
return (
<AdaptiveWorkspaceLayoutContent
{...props}
projectGroupingMode={resolveProjectGroupingMode(
preferencesResult.value.projectGroupingEnabled,
)}
projectGroupingMode={groupingSettings.sidebarProjectGroupingMode}
/>
);
}
@@ -1,15 +1,25 @@
import { ScrollView, View } from "react-native";
import { useNavigation } from "@react-navigation/native";
import { Platform, 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}
@@ -0,0 +1,106 @@
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,20 +530,9 @@ 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">
<SettingsSwitchRow
icon="folder"
label="Project Grouping"
value={projectGroupingEnabled}
onValueChange={(value) => savePreferences({ projectGroupingEnabled: value })}
/>
<SettingsRow icon="folder" label="Project Grouping" target="SettingsProjectGrouping" />
</SettingsSection>
);
}
@@ -1,4 +1,11 @@
import { Platform, ScrollView, View, useColorScheme } from "react-native";
import {
Platform,
ScrollView,
type StyleProp,
type TextStyle,
View,
useColorScheme,
} from "react-native";
import { AppText as Text } from "../../../../components/AppText";
import {
@@ -54,14 +61,48 @@ export function TerminalAppearancePreview(props: { readonly fontSize: number })
fontSize: props.fontSize,
lineHeight,
} as const;
// AppText stamps the sans font on every node, so nested spans must
// re-apply the terminal font instead of relying on inheritance, exactly
// like the code preview's tokens below.
const span = (color: string, extra?: TextStyle): StyleProp<TextStyle> => [
lineStyle,
{ color, ...extra },
];
return (
<View className="p-4">
<Text style={[lineStyle, { color: theme.foreground }]}>$ npm run dev</Text>
<Text style={[lineStyle, { color: theme.palette[2] }]}>✓ Ready in 430ms</Text>
<Text style={[lineStyle, { color: theme.foreground }]}>
Local: http://localhost:3000{" "}
<Text style={[lineStyle, { color: theme.cursorForeground }]}>▏</Text>
<Text style={span(theme.foreground)}>
<Text style={span(theme.palette[2])}>→ </Text>
<Text style={span(theme.palette[6])}>t3code </Text>
<Text style={span(theme.palette[4])}>git:(</Text>
<Text style={span(theme.palette[1])}>main</Text>
<Text style={span(theme.palette[4])}>)</Text>
<Text style={span(theme.palette[3])}> ✗</Text>
<Text style={span(theme.foreground)}> vpr dev</Text>
</Text>
<Text style={span(theme.foreground)}>
<Text style={span(theme.palette[2])}>VITE v7.1.1</Text>
<Text style={span(theme.mutedForeground)}> ready in</Text>
<Text style={span(theme.foreground)}> 1.24s</Text>
</Text>
<Text style={span(theme.foreground)}>
<Text style={span(theme.palette[2])}>→ </Text>
<Text style={span(theme.mutedForeground)}>Local: </Text>
<Text style={span(theme.palette[6], { textDecorationLine: "underline" })}>
http://127.0.0.1:5173/
</Text>
</Text>
<Text style={span(theme.foreground)}>
<Text style={span(theme.palette[2])}>✓ 85 passed</Text>
<Text style={span(theme.palette[3])}> △ 2 warnings</Text>
<Text style={span(theme.palette[1])}> ✗ 0 failed</Text>
</Text>
<Text style={span(theme.foreground)}>
<Text style={span(theme.background, { backgroundColor: theme.palette[2] })}>
{" READY "}
</Text>
<Text style={span(theme.mutedForeground)}> watching for changes</Text>{" "}
<Text style={span(theme.cursorForeground)}>▏</Text>
</Text>
</View>
);
@@ -2,6 +2,7 @@ export type SettingsSheetTarget =
| "SettingsEnvironments"
| "SettingsArchive"
| "SettingsAppearance"
| "SettingsProjectGrouping"
| "SettingsClientStorage";
export type SettingsLegalDocumentTarget = "SettingsLegal";
@@ -50,6 +50,7 @@ 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: {
@@ -89,7 +90,7 @@ export function NewTaskDraftScreen(props: {
const colorScheme = useColorScheme();
const isKeyboardVisible = useKeyboardState((state) => state.isVisible);
const controlsBottomPadding = isKeyboardVisible ? 8 : Math.max(insets.bottom, 10);
const { logicalProjects, selectedProject, setProject } = flow;
const { projectScopes, selectedProject, selectedProjectKey, setProject } = flow;
const { connectedEnvironments } = useRemoteConnectionStatus();
const selectedEnvironmentServerConfig = useEnvironmentServerConfig(
selectedProject?.environmentId ?? null,
@@ -277,24 +278,25 @@ export function NewTaskDraftScreen(props: {
return;
}
if (selectedProject) {
const selection = resolveDraftProjectSelection(selectedProjectKey, projects, projectScopes);
if (selection.kind === "preserve") {
return;
}
if (logicalProjects.length === 1) {
setProject(logicalProjects[0]!.project);
if (selection.kind === "select") {
setProject(selection.project);
return;
}
navigation.dispatch(StackActions.replace("NewTask"));
}, [
logicalProjects,
projectScopes,
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 { EnvironmentId, ProjectId } from "@t3tools/contracts";
import { useEffect, useMemo, useRef } from "react";
import type { EnvironmentProject } from "@t3tools/client-runtime/state/shell";
import { useEffect, useRef, useState } 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,12 +11,13 @@ import { cn } from "../../lib/cn";
import { AndroidScreenHeader } from "../../components/AndroidScreenHeader";
import { AppText as Text } from "../../components/AppText";
import { ProjectFavicon } from "../../components/ProjectFavicon";
import { useProjects, useThreadShells } from "../../state/entities";
import { useProjects } from "../../state/entities";
import type { WorkspaceState } from "../../state/workspaceModel";
import { useWorkspaceState } from "../../state/workspace";
import { groupProjectsByRepository } from "../../lib/repositoryGroups";
import { scopedProjectKey } from "../../lib/scopedEntities";
import { useAdaptiveWorkspaceLayout } from "../layout/AdaptiveWorkspaceLayout";
import { useIncomingShare } from "../sharing/IncomingShareProvider";
import { useNewTaskFlow } from "./new-task-flow-provider";
type NewTaskRouteParams = {
readonly incomingShareId?: string | string[];
@@ -79,7 +80,7 @@ function deriveProjectEmptyState(catalogState: WorkspaceState): {
export function NewTaskRouteScreen({ route }: StaticScreenProps<NewTaskRouteParams | undefined>) {
const projects = useProjects();
const threads = useThreadShells();
const { projectScopes } = useNewTaskFlow();
const { state: catalogState } = useWorkspaceState();
const navigation = useNavigation();
const isFocused = useIsFocused();
@@ -87,6 +88,7 @@ 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]
@@ -100,33 +102,6 @@ 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
@@ -137,7 +112,7 @@ export function NewTaskRouteScreen({ route }: StaticScreenProps<NewTaskRoutePara
) ?? null)
: null;
async function selectProject(item: (typeof items)[number]): Promise<void> {
async function selectProject(project: EnvironmentProject): Promise<void> {
if (incomingShare?.destination && !reservedDestinationProject) {
try {
await releaseShareReservation(incomingShare.id, incomingShare.destination);
@@ -154,14 +129,26 @@ export function NewTaskRouteScreen({ route }: StaticScreenProps<NewTaskRoutePara
navigation.navigate("NewTaskSheet", {
screen: "NewTaskDraft",
params: {
environmentId: item.environmentId,
projectId: item.id,
title: item.title,
environmentId: project.environmentId,
projectId: project.id,
title: project.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) {
@@ -251,11 +238,12 @@ export function NewTaskRouteScreen({ route }: StaticScreenProps<NewTaskRoutePara
contentInset={{ bottom: Math.max(insets.bottom, 18) + 18 }}
contentContainerStyle={{
gap: 12,
paddingBottom: 8,
paddingHorizontal: 20,
paddingTop: 8,
}}
>
{items.length === 0 ? (
{projectScopes.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">
@@ -286,42 +274,89 @@ export function NewTaskRouteScreen({ route }: StaticScreenProps<NewTaskRoutePara
</View>
) : (
<View collapsable={false} className="overflow-hidden rounded-[24px] bg-card">
{items.map((item, index) => {
const isFirst = index === 0;
const isLast = index === items.length - 1;
{projectScopes.map((scope, scopeIndex) => {
const hasMultipleProjects = scope.projects.length > 1;
const expanded = expandedGroupKeys.has(scope.key);
const singleProject = hasMultipleProjects ? null : scope.projects[0];
return (
<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]",
)}
<View
key={scope.key}
className={cn(scopeIndex > 0 && "border-t border-border-subtle")}
>
<View className="flex-row items-center justify-between gap-3">
<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="h-7 w-7 items-center justify-center">
<ProjectFavicon
environmentId={item.environmentId}
environmentId={scope.representative.environmentId}
size={20}
projectTitle={item.title}
workspaceRoot={item.workspaceRoot}
projectTitle={scope.title}
workspaceRoot={scope.representative.workspaceRoot}
/>
</View>
<View className="flex-1">
<Text className="text-base leading-snug font-t3-bold">{item.title}</Text>
<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>
<SymbolView
name="chevron.right"
name={hasMultipleProjects && expanded ? "chevron.down" : "chevron.right"}
size={14}
tintColor={chevronColor}
type="monochrome"
/>
</View>
</Pressable>
</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>
@@ -3,6 +3,7 @@ import { Pressable, View } from "react-native";
import { AppText as Text } from "../../components/AppText";
import type { PendingApproval } from "../../lib/threadActivity";
import { PendingCardSurface } from "./PendingCardSurface";
export interface PendingApprovalCardProps {
readonly approval: PendingApproval;
@@ -15,7 +16,7 @@ export interface PendingApprovalCardProps {
export function PendingApprovalCard(props: PendingApprovalCardProps) {
return (
<View className="gap-2.5 rounded-[20px] border border-neutral-200 bg-neutral-100/80 p-4 dark:border-white/6 dark:bg-neutral-900/80">
<PendingCardSurface>
<Text className="font-t3-bold text-2xs uppercase tracking-[1.1px] text-sky-700 dark:text-sky-300">
Approval needed
</Text>
@@ -52,6 +53,6 @@ export function PendingApprovalCard(props: PendingApprovalCardProps) {
<Text className="font-t3-bold text-sm text-rose-700 dark:text-rose-300">Decline</Text>
</Pressable>
</View>
</View>
</PendingCardSurface>
);
}
@@ -0,0 +1,35 @@
import { isLiquidGlassSupported, LiquidGlassView } from "@callstack/liquid-glass";
import type { ReactNode } from "react";
import { useColorScheme, View, type ViewStyle } from "react-native";
const SURFACE_STYLE: ViewStyle = {
borderRadius: 20,
overflow: "hidden",
};
export function PendingCardSurface(props: { readonly children: ReactNode }) {
const isDarkMode = useColorScheme() === "dark";
const content = <View className="gap-2.5 p-4">{props.children}</View>;
if (isLiquidGlassSupported) {
return (
<LiquidGlassView
effect="regular"
interactive
colorScheme={isDarkMode ? "dark" : "light"}
style={SURFACE_STYLE}
>
{content}
</LiquidGlassView>
);
}
return (
<View
className="rounded-[20px] border border-neutral-200 bg-neutral-100 dark:border-white/6 dark:bg-neutral-900"
style={SURFACE_STYLE}
>
{content}
</View>
);
}
@@ -4,6 +4,7 @@ import { Pressable, View } from "react-native";
import { AppText as Text, AppTextInput as TextInput } from "../../components/AppText";
import { cn } from "../../lib/cn";
import type { PendingUserInput, PendingUserInputDraftAnswer } from "../../lib/threadActivity";
import { PendingCardSurface } from "./PendingCardSurface";
export interface PendingUserInputCardProps {
readonly pendingUserInput: PendingUserInput;
@@ -25,7 +26,7 @@ export interface PendingUserInputCardProps {
export function PendingUserInputCard(props: PendingUserInputCardProps) {
return (
<View className="gap-2.5 rounded-[20px] border border-neutral-200 bg-neutral-100/80 p-4 dark:border-white/6 dark:bg-neutral-900/80">
<PendingCardSurface>
<Text className="font-t3-bold text-2xs uppercase tracking-[1.1px] text-sky-700 dark:text-sky-300">
User input needed
</Text>
@@ -100,6 +101,6 @@ export function PendingUserInputCard(props: PendingUserInputCardProps) {
>
<Text className="font-t3-extrabold text-sm text-white">Submit answers</Text>
</Pressable>
</View>
</PendingCardSurface>
);
}
@@ -1,3 +1,4 @@
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";
@@ -391,7 +392,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={FadeInDown.duration(220)}
entering={isLiquidGlassSupported ? undefined : FadeInDown.duration(220)}
exiting={FadeOut.duration(140)}
>
{props.activePendingApproval ? (
@@ -27,7 +27,6 @@ import {
groupByProvider,
resolveSelectableModelSelection,
} from "../../lib/modelOptions";
import { groupProjectsByRepository } from "../../lib/repositoryGroups";
import { scopedProjectKey } from "../../lib/scopedEntities";
import { appAtomRegistry } from "../../state/atom-registry";
import {
@@ -59,6 +58,12 @@ 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";
@@ -109,10 +114,7 @@ export function branchBadgeLabel(input: {
}
type NewTaskFlowContextValue = {
readonly logicalProjects: ReadonlyArray<{
readonly key: string;
readonly project: EnvironmentProject;
}>;
readonly projectScopes: ReadonlyArray<HomeProjectScope>;
readonly selectedEnvironmentId: EnvironmentId | null;
readonly selectedProjectKey: string | null;
readonly selectedModelKey: string | null;
@@ -175,32 +177,20 @@ export function NewTaskFlowProvider(props: React.PropsWithChildren) {
const projects = useProjects();
const threads = useThreadShells();
const { savedConnectionsById } = useSavedRemoteConnections();
const repositoryGroups = useMemo(
() => groupProjectsByRepository({ projects, threads }),
[projects, threads],
);
const logicalProjects = useMemo(
const groupingSettings = useMobileProjectGroupingSettings();
const projectScopes = useMemo(
() =>
pipe(
repositoryGroups,
Arr.map((group) => {
const primaryProject = group.projects[0]?.project;
if (!primaryProject) {
return null;
}
return { key: group.key, project: primaryProject };
sortHomeProjectScopes({
scopes: buildHomeProjectScopes({
projects,
environmentId: null,
projectGroupingMode: groupingSettings.sidebarProjectGroupingMode,
}),
Arr.filter(
(
entry,
): entry is {
readonly key: string;
readonly project: EnvironmentProject;
} => entry !== null,
),
),
[repositoryGroups],
threads,
pendingTasks: [],
projectSortOrder: "updated_at",
}),
[groupingSettings.sidebarProjectGroupingMode, projects, threads],
);
const [selectedEnvironmentIdOverride, setSelectedEnvironmentId] = useState<EnvironmentId | null>(
@@ -846,7 +836,7 @@ export function NewTaskFlowProvider(props: React.PropsWithChildren) {
const value = useMemo<NewTaskFlowContextValue>(
() => ({
logicalProjects,
projectScopes,
selectedEnvironmentId,
selectedProjectKey,
selectedModelKey,
@@ -912,7 +902,7 @@ export function NewTaskFlowProvider(props: React.PropsWithChildren) {
finishEditingPendingTask,
interactionMode,
loadBranches,
logicalProjects,
projectScopes,
modelOptions,
prompt,
providerGroups,
@@ -0,0 +1,82 @@
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,
});
});
});
@@ -0,0 +1,34 @@
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,6 +204,8 @@ 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;
}) {
@@ -291,7 +293,9 @@ export const ThreadListV2PendingRow = memo(function ThreadListV2PendingRow(props
) : (
<View className="bg-screen">
<View className="px-5 py-2.5">{rowContent}</View>
<View className="ml-5 h-px bg-border-subtle" />
{props.showTrailingDivider !== false ? (
<View className="ml-5 h-px bg-border-subtle" />
) : null}
</View>
)}
</Pressable>
@@ -327,6 +331,8 @@ 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;
@@ -728,7 +734,9 @@ 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>
<View className="ml-5 h-px bg-border-subtle" />
{props.showTrailingDivider !== false ? (
<View className="ml-5 h-px bg-border-subtle" />
) : null}
</View>
)}
</Pressable>
@@ -1,192 +0,0 @@
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
@@ -1,131 +0,0 @@
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,6 +5,7 @@ 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";
@@ -22,7 +23,9 @@ 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
@@ -80,6 +83,7 @@ function sanitizePreferences(parsed: Preferences): Preferences {
connectOnboardingOptOutAccounts?: ReadonlyArray<string>;
collapsedProjectGroups?: readonly string[];
projectGroupingEnabled?: boolean;
projectGroupingMode?: SidebarProjectGroupingMode;
threadListV2Enabled?: boolean;
} = {};
@@ -110,6 +114,13 @@ 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;
}
@@ -0,0 +1,33 @@
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",
};
}
@@ -0,0 +1,33 @@
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
@@ -0,0 +1,17 @@
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;
}
@@ -5,7 +5,6 @@ import * as FileSystem from "effect/FileSystem";
import * as Layer from "effect/Layer";
import * as PlatformError from "effect/PlatformError";
import * as Schema from "effect/Schema";
import { HostProcessEnvironment } from "@t3tools/shared/hostProcess";
import * as ServerConfig from "../config.ts";
import * as ServerEnvironment from "./ServerEnvironment.ts";
@@ -74,33 +73,6 @@ it.layer(NodeServices.layer)("ServerEnvironmentLive", (it) => {
}),
);
it.effect("advertises a Render cloud workspace from the host environment", () =>
Effect.gen(function* () {
const fileSystem = yield* FileSystem.FileSystem;
const baseDir = yield* fileSystem.makeTempDirectoryScoped({
prefix: "t3-server-render-environment-test-",
});
const descriptor = yield* Effect.gen(function* () {
const serverEnvironment = yield* ServerEnvironment.ServerEnvironment;
return yield* serverEnvironment.getDescriptor;
}).pipe(
Effect.provide(makeServerEnvironmentLayer(baseDir)),
Effect.provideService(HostProcessEnvironment, {
T3CODE_CLOUD_PROVIDER: "render",
T3CODE_ENVIRONMENT_LABEL: "Render cloud environment",
T3CODE_WORKSPACE_DIR: "/data/workspace",
}),
);
expect(descriptor.label).toBe("Render cloud environment");
expect(descriptor.cloud).toEqual({
provider: "render",
workspaceRoot: "/data/workspace",
});
}),
);
it.effect("structures persisted environment id filesystem failures", () =>
Effect.gen(function* () {
const fileSystem = yield* FileSystem.FileSystem;
@@ -1,9 +1,5 @@
import { EnvironmentId, type ExecutionEnvironmentDescriptor } from "@t3tools/contracts";
import {
HostProcessArchitecture,
HostProcessEnvironment,
HostProcessPlatform,
} from "@t3tools/shared/hostProcess";
import { HostProcessArchitecture, HostProcessPlatform } from "@t3tools/shared/hostProcess";
import * as Context from "effect/Context";
import * as Crypto from "effect/Crypto";
import * as Effect from "effect/Effect";
@@ -73,7 +69,6 @@ export const make = Effect.gen(function* () {
const crypto = yield* Crypto.Crypto;
const hostPlatform = yield* HostProcessPlatform;
const hostArchitecture = yield* HostProcessArchitecture;
const hostEnvironment = yield* HostProcessEnvironment;
const readPersistedEnvironmentId = Effect.gen(function* () {
const exists = yield* fileSystem.exists(serverConfig.environmentIdPath).pipe(
@@ -130,16 +125,7 @@ export const make = Effect.gen(function* () {
const environmentId = EnvironmentId.make(environmentIdRaw);
const cwdBaseName = path.basename(serverConfig.cwd).trim();
const configuredLabel = hostEnvironment.T3CODE_ENVIRONMENT_LABEL?.trim();
const label = configuredLabel || (yield* resolveServerEnvironmentLabel({ cwdBaseName }));
const cloudProvider = hostEnvironment.T3CODE_CLOUD_PROVIDER?.trim().toLowerCase();
const cloud =
cloudProvider === "render"
? {
provider: "render" as const,
workspaceRoot: hostEnvironment.T3CODE_WORKSPACE_DIR?.trim() || serverConfig.cwd,
}
: undefined;
const label = yield* resolveServerEnvironmentLabel({ cwdBaseName });
const launcher = yield* resolveServiceLauncherMode();
const serverSelfUpdate = resolveServerSelfUpdateCapability({
desktopManaged: serverConfig.mode === "desktop",
@@ -153,7 +139,6 @@ export const make = Effect.gen(function* () {
os: platformOs(hostPlatform),
arch: platformArch(hostArchitecture),
},
...(cloud ? { cloud } : {}),
serverVersion: packageJson.version,
capabilities: {
repositoryIdentity: true,
@@ -12,6 +12,19 @@ const schemaHasDescription = (schema: unknown): boolean => {
.some((members) => members.some(schemaHasDescription));
};
const schemaHasMultipleAllOfDescriptions = (schema: unknown): boolean => {
if (!schema || typeof schema !== "object") return false;
const record = schema as Record<string, unknown>;
const allOf = Array.isArray(record.allOf) ? record.allOf : [];
const descriptionCount = allOf.filter(
(member) =>
member !== null &&
typeof member === "object" &&
typeof (member as Record<string, unknown>).description === "string",
).length;
return descriptionCount > 1 || Object.values(record).some(schemaHasMultipleAllOfDescriptions);
};
it("exports provider-compatible object schemas with described parameters", () => {
for (const tool of Object.values(PreviewToolkit.tools)) {
const schema = Tool.getJsonSchema(tool) as {
@@ -27,6 +40,9 @@ it("exports provider-compatible object schemas with described parameters", () =>
expect(schema.type, `${tool.name} must export a top-level object schema`).toBe("object");
expect(schema.anyOf, `${tool.name} must not export a root anyOf`).toBeUndefined();
expect(schema.oneOf, `${tool.name} must not export a root oneOf`).toBeUndefined();
if (tool.name === "preview_navigate") {
expect(schemaHasMultipleAllOfDescriptions(schema)).toBe(false);
}
expect(
schema.properties?.tabId,
`${tool.name} must allow an explicit collaborative browser tab target`,
-61
View File
@@ -1,61 +0,0 @@
import {
EnvironmentHttpApi,
EnvironmentHttpForbiddenError,
EnvironmentHttpInternalServerError,
} from "@t3tools/contracts";
import { HostProcessEnvironment } from "@t3tools/shared/hostProcess";
import * as Effect from "effect/Effect";
import * as HttpEffect from "effect/unstable/http/HttpEffect";
import { HttpServerResponse } from "effect/unstable/http";
import * as HttpApiBuilder from "effect/unstable/httpapi/HttpApiBuilder";
import * as EnvironmentAuth from "../auth/EnvironmentAuth.ts";
const RENDER_BOOTSTRAP_RESPONSE_HEADERS = {
"cache-control": "no-store",
pragma: "no-cache",
"referrer-policy": "no-referrer",
"x-content-type-options": "nosniff",
} as const;
const appendRenderBootstrapResponseHeaders = HttpEffect.appendPreResponseHandler(
(_request, response) =>
Effect.succeed(HttpServerResponse.setHeaders(response, RENDER_BOOTSTRAP_RESPONSE_HEADERS)),
);
export const renderBootstrapHttpApiLayer = HttpApiBuilder.group(
EnvironmentHttpApi,
"renderBootstrap",
Effect.fnUntraced(function* (handlers) {
const hostEnvironment = yield* HostProcessEnvironment;
const serverAuth = yield* EnvironmentAuth.EnvironmentAuth;
const configuredProvider = hostEnvironment.T3CODE_CLOUD_PROVIDER?.trim().toLowerCase();
const environmentLabel =
hostEnvironment.T3CODE_ENVIRONMENT_LABEL?.trim() || "Render cloud environment";
return handlers.handle(
"pair",
Effect.fn("environment.renderBootstrap.pair")(function* () {
yield* appendRenderBootstrapResponseHeaders;
if (configuredProvider !== "render") {
return yield* new EnvironmentHttpForbiddenError({
message: "This environment is not configured for Render setup.",
});
}
const issued = yield* serverAuth.issuePairingCredential({ label: "Render setup" }).pipe(
Effect.mapError(
() =>
new EnvironmentHttpInternalServerError({
message: "Could not create a Render pairing credential.",
}),
),
);
return {
pairingCode: issued.credential,
label: environmentLabel,
};
}),
);
}),
);
+1 -33
View File
@@ -2,7 +2,7 @@ import * as NodeHttpServer from "@effect/platform-node/NodeHttpServer";
import * as NodeSocket from "@effect/platform-node/NodeSocket";
import * as NodeServices from "@effect/platform-node/NodeServices";
import * as NodeCrypto from "node:crypto";
import { HostProcessEnvironment, HostProcessPlatform } from "@t3tools/shared/hostProcess";
import { HostProcessPlatform } from "@t3tools/shared/hostProcess";
import {
AuthAccessTokenType,
@@ -327,7 +327,6 @@ const makeBrowserOtlpPayload = (spanName: string) =>
const buildAppUnderTest = (options?: {
config?: Partial<ServerConfig.ServerConfig["Service"]>;
hostEnvironment?: NodeJS.ProcessEnv;
layers?: {
keybindings?: Partial<Keybindings.Keybindings["Service"]>;
providerRegistry?: Partial<ProviderRegistry.ProviderRegistry["Service"]>;
@@ -892,7 +891,6 @@ const buildAppUnderTest = (options?: {
Layer.provideMerge(ServerSecretStore.layer),
Layer.provide(workspaceAndProjectServicesLayer),
Layer.provideMerge(FetchHttpClient.layer),
Layer.provide(Layer.succeed(HostProcessEnvironment, options?.hostEnvironment ?? process.env)),
Layer.provide(layerConfig),
);
@@ -1398,36 +1396,6 @@ it.layer(NodeServices.layer)("server router seam", (it) => {
}).pipe(Effect.provide(NodeHttpServer.layerTest)),
);
it.effect("pairs a Render environment from its service URL without reading logs", () =>
Effect.gen(function* () {
yield* buildAppUnderTest({
hostEnvironment: {
T3CODE_CLOUD_PROVIDER: "render",
T3CODE_ENVIRONMENT_LABEL: "Render cloud environment",
},
});
const url = yield* getHttpServerUrl("/.well-known/t3/render/pair");
const response = yield* fetchEffect(url, {
method: "POST",
});
const body = yield* responseJsonEffect<{
readonly pairingCode: string;
readonly label: string;
}>(response);
const exchanged = yield* exchangeAccessToken(body.pairingCode, {
scope: "orchestration:read orchestration:operate terminal:operate review:write relay:read",
});
assert.equal(response.status, 200);
assert.equal(response.headers["cache-control"], "no-store");
assert.equal(response.headers["referrer-policy"], "no-referrer");
assert.equal(body.label, "Render cloud environment");
assert.isAbove(body.pairingCode.length, 0);
assert.equal(exchanged.response.status, 200);
}).pipe(Effect.provide(NodeHttpServer.layerTest)),
);
it.effect("compresses large JSON responses through the composed routes", () =>
Effect.gen(function* () {
const descriptor = {
+7 -4
View File
@@ -79,7 +79,6 @@ import * as ProjectSetupScriptRunner from "./project/ProjectSetupScriptRunner.ts
import { ObservabilityLive } from "./observability/Layers/Observability.ts";
import * as ServerEnvironment from "./environment/ServerEnvironment.ts";
import { authHttpApiLayer, environmentAuthenticatedAuthLayer } from "./auth/http.ts";
import { renderBootstrapHttpApiLayer } from "./render/http.ts";
import * as ServerSecretStore from "./auth/ServerSecretStore.ts";
import * as EnvironmentAuth from "./auth/EnvironmentAuth.ts";
import {
@@ -429,7 +428,6 @@ export const makeRoutesLayer = Layer.mergeAll(
Layer.mergeAll(
HttpApiBuilder.layer(EnvironmentHttpApi).pipe(
Layer.provide(authHttpApiLayer),
Layer.provide(renderBootstrapHttpApiLayer),
Layer.provide(connectHttpApiLayer),
Layer.provide(orchestrationHttpApiLayer),
Layer.provide(serverEnvironmentHttpApiLayer),
@@ -585,8 +583,13 @@ export const makeServerLayer = Layer.unwrap(
const server = yield* HttpServer.HttpServer;
const address = server.address;
if (typeof address === "string" || !("port" in address)) return;
yield* Effect.sleep("250 millis").pipe(
Effect.andThen(reconcileDesiredCloudLink(`http://127.0.0.1:${address.port}`)),
// No settling delay before the first attempt: routes are already
// serving by the time activation opens this gate (the startup
// sequence awaits routesReady), and the retry schedule below
// covers anything this sleep used to hedge against. Every
// millisecond here is dead time on the path to remote
// reachability after a restart.
yield* reconcileDesiredCloudLink(`http://127.0.0.1:${address.port}`).pipe(
Effect.retry({
while: (error) =>
error._tag !== "EnvironmentHttpBadRequestError" &&
+43
View File
@@ -1,6 +1,7 @@
import { describe, expect, it } from "vite-plus/test";
import {
areFontAdvancesMonospace,
clampCodeFontSize,
clampInterfaceFontSize,
clampPromptFontSize,
@@ -9,8 +10,22 @@ import {
appearanceFontStack,
cssFontFamilies,
resolveDefaultFamilyLabel,
resolveTerminalFontPreference,
} from "./appearanceFonts";
describe("areFontAdvancesMonospace", () => {
it("accepts a fixed advance and rejects any proportional glyph", () => {
expect(areFontAdvancesMonospace([10, 10, 10, 10])).toBe(true);
expect(areFontAdvancesMonospace([10, 10, 7, 10])).toBe(false);
expect(areFontAdvancesMonospace([10, 10.02])).toBe(false);
});
it("fails open when canvas metrics are unavailable", () => {
expect(areFontAdvancesMonospace([])).toBe(true);
expect(areFontAdvancesMonospace([Number.NaN, Number.NaN])).toBe(true);
});
});
describe("cssFontFamilies", () => {
it("returns null for effectively empty input", () => {
expect(cssFontFamilies("")).toBeNull();
@@ -54,6 +69,34 @@ describe("appearanceFontStack", () => {
});
});
describe("resolveTerminalFontPreference", () => {
it("inherits the code font in simple mode", () => {
expect(
resolveTerminalFontPreference({ advanced: false, code: "Fira Code", terminal: "" }),
).toBe("Fira Code");
expect(
resolveTerminalFontPreference({
advanced: false,
code: "Fira Code",
terminal: "Berkeley Mono",
}),
).toBe("Fira Code");
});
it("keeps code and terminal fonts independent in advanced mode", () => {
expect(resolveTerminalFontPreference({ advanced: true, code: "Fira Code", terminal: "" })).toBe(
"",
);
expect(
resolveTerminalFontPreference({
advanced: true,
code: "Fira Code",
terminal: "Berkeley Mono",
}),
).toBe("Berkeley Mono");
});
});
describe("font size clamping", () => {
it("keeps sizes inside the ranges the UI can absorb", () => {
expect(clampInterfaceFontSize(16)).toBe(16);
+39 -5
View File
@@ -25,6 +25,22 @@ export const DEFAULT_SANS_FONT_STACK =
export const DEFAULT_CODE_FONT_STACK =
'"SF Mono", "SFMono-Regular", Menlo, Consolas, "Liberation Mono", monospace';
export const TYPOGRAPHY_ADVANCED_STORAGE_KEY = "t3code:typography-advanced";
/**
* Simple typography treats the terminal as another monospace surface. In
* Advanced mode an empty terminal preference means the terminal default,
* keeping later code-font changes isolated to code surfaces.
*/
export function resolveTerminalFontPreference(input: {
readonly advanced: boolean;
readonly code: string;
readonly terminal: string;
}): string {
if (input.advanced) return input.terminal;
return input.code;
}
function quoteFontFamilyName(name: string): string {
const bare = name.trim();
if (bare.length === 0) return "";
@@ -165,6 +181,22 @@ export function isFontFamilyAvailable(family: string): boolean {
}
}
const MONOSPACE_PROBE_VARIANTS = ["normal 400", "normal 700", "italic 400", "italic 700"] as const;
const MONOSPACE_PROBE_GLYPHS = ["i", "M", "W", "0", "@", "#", ".", " "] as const;
const MONOSPACE_ADVANCE_TOLERANCE = 0.01;
export function areFontAdvancesMonospace(advances: readonly number[]): boolean {
const reference = advances[0];
if (
reference === undefined ||
reference <= 0 ||
advances.some((advance) => !Number.isFinite(advance) || advance <= 0)
) {
return true;
}
return advances.every((advance) => Math.abs(advance - reference) < MONOSPACE_ADVANCE_TOLERANCE);
}
/**
* Whether a family renders every character on the same advance. Cell-grid
* surfaces (the terminal) require this: a proportional face draws its text
@@ -182,13 +214,15 @@ export function isMonospaceFamily(family: string): boolean {
fontProbeContext = document.createElement("canvas").getContext("2d");
}
if (fontProbeContext === null) return true;
const context = fontProbeContext;
// Fall back to a generic mono so an absent face measures as monospace and
// is left for the normal fallback chain to resolve.
fontProbeContext.font = `32px ${families}, monospace`;
const narrow = fontProbeContext.measureText("i").width;
const wide = fontProbeContext.measureText("M").width;
if (!Number.isFinite(narrow) || !Number.isFinite(wide) || wide === 0) return true;
return Math.abs(wide - narrow) < 0.5;
for (const variant of MONOSPACE_PROBE_VARIANTS) {
context.font = `${variant} 32px ${families}, monospace`;
const advances = MONOSPACE_PROBE_GLYPHS.map((glyph) => context.measureText(glyph).width);
if (!areFontAdvancesMonospace(advances)) return false;
}
return true;
} catch {
return true;
}
@@ -1,59 +0,0 @@
import { describe, expect, it } from "vite-plus/test";
import { cloudCloneDestination, cloudEnvironmentProvider } from "./cloudEnvironment";
describe("cloudEnvironmentProvider", () => {
it("uses advertised Render metadata", () => {
expect(
cloudEnvironmentProvider({
displayUrl: null,
serverConfig: {
environment: {
environmentId: "environment-1",
label: "Render cloud environment",
platform: { os: "linux", arch: "x64" },
cloud: { provider: "render", workspaceRoot: "/data/workspace" },
serverVersion: "1.0.0",
capabilities: { repositoryIdentity: true },
},
} as never,
}),
).toBe("render");
});
it("recognizes disconnected onrender.com environments", () => {
expect(
cloudEnvironmentProvider({
displayUrl: "https://t3code-cloud-demo.onrender.com",
serverConfig: null,
}),
).toBe("render");
});
});
describe("cloudCloneDestination", () => {
it("clones provider repositories under the cloud workspace root", () => {
expect(
cloudCloneDestination({
workspaceRoot: "/data/workspace/",
repository: {
provider: "github",
nameWithOwner: "shivamhwp/render-ad",
url: "https://github.com/shivamhwp/render-ad",
sshUrl: "[email protected]:shivamhwp/render-ad.git",
},
remoteUrl: "[email protected]:shivamhwp/render-ad.git",
}),
).toBe("/data/workspace/render-ad");
});
it("derives a directory from arbitrary Git URLs", () => {
expect(
cloudCloneDestination({
workspaceRoot: "/data/workspace",
repository: null,
remoteUrl: "https://example.com/team/project.git?ref=main",
}),
).toBe("/data/workspace/project");
});
});
-65
View File
@@ -1,65 +0,0 @@
import type { ServerConfig, SourceControlRepositoryInfo } from "@t3tools/contracts";
export type CloudEnvironmentProvider = "render";
interface CloudEnvironmentLike {
readonly displayUrl: string | null;
readonly serverConfig: ServerConfig | null;
}
function isRenderHostname(value: string): boolean {
try {
return new URL(value).hostname.toLowerCase().endsWith(".onrender.com");
} catch {
return false;
}
}
export function cloudEnvironmentProvider(
environment: CloudEnvironmentLike,
): CloudEnvironmentProvider | null {
const advertisedProvider = environment.serverConfig?.environment.cloud?.provider;
if (advertisedProvider === "render") {
return advertisedProvider;
}
return environment.displayUrl && isRenderHostname(environment.displayUrl) ? "render" : null;
}
export function cloudEnvironmentWorkspaceRoot(environment: CloudEnvironmentLike): string | null {
return environment.serverConfig?.environment.cloud?.workspaceRoot ?? null;
}
export function cloudEnvironmentProviderLabel(provider: CloudEnvironmentProvider): string {
switch (provider) {
case "render":
return "Render";
}
}
export function inferRepositoryDirectoryName(input: {
readonly repository: SourceControlRepositoryInfo | null;
readonly remoteUrl: string;
}): string | null {
const candidate = input.repository?.nameWithOwner ?? input.remoteUrl;
const withoutQuery = candidate.split(/[?#]/, 1)[0]?.replace(/[\\/]+$/, "") ?? "";
const segment =
withoutQuery
.split(/[\\/:]/)
.at(-1)
?.replace(/\.git$/i, "")
.trim() ?? "";
return segment.length > 0 && segment !== "." && segment !== ".." ? segment : null;
}
export function cloudCloneDestination(input: {
readonly workspaceRoot: string;
readonly repository: SourceControlRepositoryInfo | null;
readonly remoteUrl: string;
}): string | null {
const directoryName = inferRepositoryDirectoryName(input);
if (!directoryName) {
return null;
}
const workspaceRoot = input.workspaceRoot.trim().replace(/[\\/]+$/, "");
return workspaceRoot.length > 0 ? `${workspaceRoot}/${directoryName}` : null;
}
@@ -1,63 +0,0 @@
import { describe, expect, it, vi } from "vite-plus/test";
import {
maskedRenderServiceUrl,
normalizeRenderServiceUrl,
RenderBootstrapRequestError,
requestRenderPairing,
} from "./renderBootstrap";
describe("normalizeRenderServiceUrl", () => {
it("accepts a bare Render hostname and keeps only its origin", () => {
expect(normalizeRenderServiceUrl("demo.onrender.com/path")).toBe("https://demo.onrender.com");
});
it("rejects Render dashboard URLs", () => {
expect(() => normalizeRenderServiceUrl("https://dashboard.render.com/web/srv-123")).toThrow(
"not the Render dashboard URL",
);
});
it("masks long service hostnames", () => {
expect(maskedRenderServiceUrl("https://t3code-cloud-demo-eg5i.onrender.com")).toBe(
"t3code-cloud-…i.onrender.com",
);
});
});
describe("requestRenderPairing", () => {
it("claims a one-time pairing credential from the service URL", async () => {
const fetcher = vi.fn(async (_input: RequestInfo | URL, _init?: RequestInit) =>
Response.json({ pairingCode: "pairing-code", label: "Render cloud environment" }),
);
await expect(
requestRenderPairing({
serviceUrl: "demo.onrender.com",
fetcher,
}),
).resolves.toEqual({
host: "https://demo.onrender.com",
pairingCode: "pairing-code",
label: "Render cloud environment",
});
expect(fetcher).toHaveBeenCalledOnce();
expect(fetcher.mock.calls[0]?.[0].toString()).toBe(
"https://demo.onrender.com/.well-known/t3/render/pair",
);
});
it("explains when the service is still running an older deployment", async () => {
const fetcher = vi.fn(async (_input: RequestInfo | URL, _init?: RequestInit) =>
Response.json({ message: "missing" }, { status: 404 }),
);
const failure = await requestRenderPairing({
serviceUrl: "https://demo.onrender.com",
fetcher,
}).catch((error: unknown) => error);
expect(failure).toBeInstanceOf(RenderBootstrapRequestError);
expect((failure as Error).message).toContain("Deploy the latest version");
});
});
-91
View File
@@ -1,91 +0,0 @@
import { EnvironmentRenderBootstrapPairingResult } from "@t3tools/contracts";
import * as Option from "effect/Option";
import * as Schema from "effect/Schema";
const RenderBootstrapErrorBody = Schema.Struct({ message: Schema.String });
const decodeRenderBootstrapErrorBody = Schema.decodeUnknownOption(RenderBootstrapErrorBody);
const decodeRenderBootstrapPairingResult = Schema.decodeUnknownSync(
EnvironmentRenderBootstrapPairingResult,
);
export class RenderBootstrapRequestError extends Error {
readonly status: number | null;
constructor(message: string, status: number | null = null) {
super(message);
this.name = "RenderBootstrapRequestError";
this.status = status;
}
}
export function normalizeRenderServiceUrl(value: string): string {
const candidate = value.trim();
if (candidate.length === 0) {
throw new RenderBootstrapRequestError("Enter the Render service URL.");
}
let url: URL;
try {
url = new URL(/^https?:\/\//iu.test(candidate) ? candidate : `https://${candidate}`);
} catch {
throw new RenderBootstrapRequestError("Enter a valid Render service URL.");
}
if (url.protocol !== "https:") {
throw new RenderBootstrapRequestError("Render service URLs must use HTTPS.");
}
if (url.hostname.toLowerCase() === "dashboard.render.com") {
throw new RenderBootstrapRequestError(
"Paste the service's .onrender.com URL, not the Render dashboard URL.",
);
}
return url.origin;
}
export function maskedRenderServiceUrl(value: string): string {
try {
const hostname = new URL(value).hostname;
if (hostname.length <= 28) return hostname;
return `${hostname.slice(0, 13)}…${hostname.slice(-14)}`;
} catch {
return "Render service";
}
}
export async function requestRenderPairing(input: {
readonly serviceUrl: string;
readonly fetcher?: typeof globalThis.fetch;
}): Promise<{ readonly host: string; readonly pairingCode: string; readonly label: string }> {
const host = normalizeRenderServiceUrl(input.serviceUrl);
const endpoint = new URL("/.well-known/t3/render/pair", host);
let response: Response;
try {
response = await (input.fetcher ?? globalThis.fetch)(endpoint, {
method: "POST",
cache: "no-store",
referrerPolicy: "no-referrer",
});
} catch {
throw new RenderBootstrapRequestError(
"Could not reach the Render service. A free instance can take about a minute to wake up.",
);
}
const responseBody: unknown = await response.json().catch(() => null);
if (!response.ok) {
const decodedError = decodeRenderBootstrapErrorBody(responseBody);
const serverMessage = Option.isSome(decodedError) ? decodedError.value.message : null;
const message =
response.status === 403 || response.status === 404
? "This service does not have in-app Render pairing yet. Deploy the latest version."
: serverMessage || `Render pairing failed with HTTP ${response.status}.`;
throw new RenderBootstrapRequestError(message, response.status);
}
try {
const pairing = decodeRenderBootstrapPairingResult(responseBody);
return { host, pairingCode: pairing.pairingCode, label: pairing.label };
} catch {
throw new RenderBootstrapRequestError("The Render service returned an invalid pairing reply.");
}
}
+4
View File
@@ -1363,6 +1363,9 @@ function ChatMarkdown({
},
[createAssetUrl, openPreview, preparedConnection, threadRef],
);
/* eslint-disable react/no-unstable-nested-components -- ReactMarkdown requires component
* renderers that close over this message's metadata. useMemo keeps them stable until that
* metadata changes. */
const markdownComponents = useMemo<Components>(() => {
const fileLinkChip = (
fileLinkMeta: MarkdownFileLinkMeta,
@@ -1593,6 +1596,7 @@ function ChatMarkdown({
text,
threadRef,
]);
/* eslint-enable react/no-unstable-nested-components */
return (
<div
+101 -236
View File
@@ -119,7 +119,6 @@ import { CommandPaletteContent } from "./CommandPaletteContent";
import { CommandPaletteResults } from "./CommandPaletteResults";
import { AzureDevOpsIcon, BitbucketIcon, GitHubIcon, GitLabIcon } from "./Icons";
import { ProjectFavicon } from "./ProjectFavicon";
import { RenderLogo } from "./RenderLogo";
import { ProjectFilePicker } from "./files/ProjectFilePicker";
import { ProjectContentSearchDialog } from "./search/ProjectContentSearchDialog";
import { ThreadRowLeadingStatus, ThreadRowTrailingStatus } from "./ThreadStatusIndicators";
@@ -135,20 +134,24 @@ import { ComposerHandleContext, useComposerHandleContext } from "../composerHand
import type { ChatComposerHandle } from "./chat/ChatComposer";
import { getProjectOrderKey, selectProjectGroupingSettings } from "../logicalProject";
import { legacyProjectCwdPreferenceKey, useUiStateStore } from "../uiStateStore";
import {
cloudCloneDestination,
cloudEnvironmentProvider,
cloudEnvironmentProviderLabel,
cloudEnvironmentWorkspaceRoot,
type CloudEnvironmentProvider,
} from "../cloud/cloudEnvironment";
import {
buildSidebarProjectPickerEntries,
buildSidebarProjectSnapshots,
} from "../sidebarProjectGrouping";
import type { Project } from "../types";
const EMPTY_BROWSE_ENTRIES: FilesystemBrowseResult["entries"] = [];
function projectFavicon(project: Project) {
return (
<ProjectFavicon
environmentId={project.environmentId}
cwd={project.workspaceRoot}
className={ITEM_ICON_CLASS}
/>
);
}
function getLocalFileManagerName(platform: string): string {
if (isMacPlatform(platform)) {
return "Finder";
@@ -178,7 +181,6 @@ interface AddProjectEnvironmentOption {
readonly isPrimary: boolean;
readonly isConnected: boolean;
readonly status: string;
readonly cloudProvider: CloudEnvironmentProvider | null;
}
type AddProjectRemoteProviderKind = Extract<
@@ -201,7 +203,6 @@ type AddProjectCloneFlow =
readonly repository: SourceControlRepositoryInfo | null;
readonly remoteUrl: string;
};
type AddProjectCloneConfirmation = Extract<AddProjectCloneFlow, { readonly step: "confirm" }>;
const REMOTE_PROJECT_SOURCES: ReadonlyArray<AddProjectRemoteSource> = [
"url",
@@ -550,10 +551,6 @@ function OpenCommandPaletteDialog(props: {
const lookupRepository = useAtomQueryRunner(sourceControlEnvironment.repository, {
reportFailure: false,
});
const loadSourceControlDiscovery = useAtomQueryRunner(sourceControlEnvironment.discovery, {
reportFailure: false,
reportDefect: false,
});
const loadBrowsePath = useAtomQueryRunner(filesystemEnvironment.browse, {
reportFailure: false,
reportDefect: false,
@@ -709,7 +706,6 @@ function OpenCommandPaletteDialog(props: {
isPrimary,
isConnected: canCreateProjectInEnvironment(environment.connection.phase),
status: connectionStatusText(environment.connection),
cloudProvider: cloudEnvironmentProvider(environment),
};
});
@@ -939,13 +935,7 @@ function OpenCommandPaletteDialog(props: {
group?.memberProjects.flatMap((member) => [member.title, member.workspaceRoot]) ?? []
);
},
icon: (project) => (
<ProjectFavicon
environmentId={project.environmentId}
cwd={project.workspaceRoot}
className={ITEM_ICON_CLASS}
/>
),
icon: projectFavicon,
runProject: openProjectFromSearch,
}),
[openProjectFromSearch, pickerProjects, projectGroupByTargetKey],
@@ -963,13 +953,7 @@ function OpenCommandPaletteDialog(props: {
group?.memberProjects.flatMap((member) => [member.title, member.workspaceRoot]) ?? []
);
},
icon: (project) => (
<ProjectFavicon
environmentId={project.environmentId}
cwd={project.workspaceRoot}
className={ITEM_ICON_CLASS}
/>
),
icon: projectFavicon,
runProject: async (project) => {
const group = projectGroupByTargetKey.get(`${project.environmentId}:${project.id}`);
const contextualRefBelongsToGroup =
@@ -1224,7 +1208,7 @@ function OpenCommandPaletteDialog(props: {
);
const startAddProjectSourceSelection = useCallback(
async (environmentId: EnvironmentId): Promise<void> => {
(environmentId: EnvironmentId): void => {
const environment = environments.find(
(candidate) => candidate.environmentId === environmentId,
);
@@ -1240,21 +1224,13 @@ function OpenCommandPaletteDialog(props: {
}
setAddProjectEnvironmentId(environmentId);
setAddProjectCloneFlow(null);
let discovery = browseEnvironmentId === environmentId ? sourceControlDiscovery.data : null;
if (discovery === null) {
const discoveryResult = await loadSourceControlDiscovery({
environmentId,
input: {},
});
if (discoveryResult._tag === "Success") {
discovery = discoveryResult.value;
}
}
pushPaletteView({
addonIcon: <FolderPlusIcon className={ADDON_ICON_CLASS} />,
groups: buildAddProjectSourceGroups(
environmentId,
buildAddProjectRemoteSourceReadiness(discovery),
buildAddProjectRemoteSourceReadiness(
browseEnvironmentId === environmentId ? sourceControlDiscovery.data : null,
),
),
});
},
@@ -1262,83 +1238,44 @@ function OpenCommandPaletteDialog(props: {
browseEnvironmentId,
buildAddProjectSourceGroups,
environments,
loadSourceControlDiscovery,
pushPaletteView,
sourceControlDiscovery.data,
],
);
const addProjectEnvironmentGroups = useMemo<CommandPaletteView["groups"]>(() => {
const toItem = (option: AddProjectEnvironmentOption): CommandPaletteActionItem => ({
const addProjectEnvironmentItems: CommandPaletteActionItem[] = addProjectEnvironmentOptions.map(
(option) => ({
kind: "action",
value: `action:add-project:environment:${option.environmentId}`,
searchTerms: [
option.label,
option.environmentId,
option.isPrimary ? "this device" : "",
option.cloudProvider ? "cloud render" : "",
],
searchTerms: [option.label, option.environmentId, option.isPrimary ? "this device" : ""],
title: option.label,
description: option.isConnected
? option.cloudProvider
? `Cloud workspace · Powered by ${cloudEnvironmentProviderLabel(option.cloudProvider)}`
: option.isPrimary
? "This device"
: option.environmentId
? option.isPrimary
? "This device"
: option.environmentId
: option.status,
disabled: !option.isConnected,
icon: option.cloudProvider ? (
<RenderLogo className={ITEM_ICON_CLASS} />
) : (
<FolderPlusIcon className={ITEM_ICON_CLASS} />
),
icon: <FolderPlusIcon className={ITEM_ICON_CLASS} />,
keepOpen: true,
run: async () => {
if (option.cloudProvider) {
startAddProjectClone(option.environmentId, "url");
return;
}
await startAddProjectSourceSelection(option.environmentId);
startAddProjectSourceSelection(option.environmentId);
},
});
const cloudItems = addProjectEnvironmentOptions
.filter((option) => option.cloudProvider !== null)
.map(toItem);
const deviceItems = addProjectEnvironmentOptions
.filter((option) => option.cloudProvider === null)
.map(toItem);
}),
);
return [
...(cloudItems.length > 0
? [
{
value: "cloud-environments",
label: "Cloud environments · Powered by Render",
items: cloudItems,
},
]
: []),
...(deviceItems.length > 0
? [
{
value: "device-environments",
label: "Devices",
items: deviceItems,
},
]
: []),
];
}, [addProjectEnvironmentOptions, startAddProjectClone, startAddProjectSourceSelection]);
const hasCloudAddProjectEnvironment = addProjectEnvironmentOptions.some(
(option) => option.cloudProvider !== null,
const addProjectEnvironmentGroups = useMemo<CommandPaletteView["groups"]>(
() => [
{
value: "environments",
label: "Environments",
items: addProjectEnvironmentItems,
},
],
[addProjectEnvironmentItems],
);
const openAddProjectFlow = useCallback(() => {
if (
hasCloudAddProjectEnvironment ||
addProjectEnvironmentOptions.length > 1 ||
defaultAddProjectEnvironmentId === null
) {
if (addProjectEnvironmentOptions.length > 1 || defaultAddProjectEnvironmentId === null) {
pushPaletteView({
addonIcon: <FolderPlusIcon className={ADDON_ICON_CLASS} />,
groups: addProjectEnvironmentGroups,
@@ -1363,7 +1300,6 @@ function OpenCommandPaletteDialog(props: {
addProjectEnvironmentGroups,
addProjectEnvironmentOptions.length,
defaultAddProjectEnvironmentId,
hasCloudAddProjectEnvironment,
pushPaletteView,
startAddProjectSourceSelection,
]);
@@ -1727,119 +1663,6 @@ function OpenCommandPaletteDialog(props: {
return getAddProjectInitialQueryForEnvironment(environmentId);
}
function getCloudCloneDestination(flow: AddProjectCloneConfirmation): string | null | undefined {
const environment = environments.find(
(candidate) => candidate.environmentId === flow.environmentId,
);
if (!environment) {
return undefined;
}
const workspaceRoot = cloudEnvironmentWorkspaceRoot(environment);
if (!workspaceRoot) {
return undefined;
}
return cloudCloneDestination({
workspaceRoot,
repository: flow.repository,
remoteUrl: flow.remoteUrl,
});
}
async function cloneIntoCloudEnvironmentIfConfigured(
flow: AddProjectCloneConfirmation,
): Promise<boolean> {
const destination = getCloudCloneDestination(flow);
if (destination === undefined) {
return false;
}
if (destination === null) {
toastManager.add(
stackedThreadToast({
type: "error",
title: "Unable to name cloud workspace",
description: "Use a repository URL whose final path contains the repository name.",
}),
);
return true;
}
await cloneAndAddRemoteProject(flow, destination);
return true;
}
async function cloneAndAddRemoteProject(
flow: AddProjectCloneConfirmation,
destinationPathInput: string,
): Promise<void> {
const rawDestination = destinationPathInput.trim();
if (rawDestination.length === 0 || isRemoteProjectCloning) {
return;
}
const targetEnvironment = environments.find(
(candidate) => candidate.environmentId === flow.environmentId,
);
const targetPlatform = getEnvironmentBrowsePlatform(
targetEnvironment?.serverConfig?.environment.platform.os,
);
const targetCurrentProjectCwd =
currentProjectEnvironmentId === flow.environmentId ? currentProjectCwd : null;
if (isUnsupportedWindowsProjectPath(rawDestination, targetPlatform)) {
toastManager.add(
stackedThreadToast({
type: "error",
title: "Clone failed",
description: "Windows-style paths are only supported on Windows.",
}),
);
return;
}
if (isExplicitRelativeProjectPath(rawDestination) && !targetCurrentProjectCwd) {
toastManager.add(
stackedThreadToast({
type: "error",
title: "Clone failed",
description: "Relative paths require an active project.",
}),
);
return;
}
const destinationPath = resolveProjectPathForDispatch(rawDestination, targetCurrentProjectCwd);
if (destinationPath.length === 0) {
return;
}
setIsRemoteProjectCloning(true);
const cloneResult = await cloneRepository({
environmentId: flow.environmentId,
input: {
remoteUrl: flow.remoteUrl,
destinationPath,
},
});
setIsRemoteProjectCloning(false);
if (cloneResult._tag === "Failure") {
if (!isAtomCommandInterrupted(cloneResult)) {
toastManager.add(
stackedThreadToast({
type: "error",
title: "Clone failed",
description: errorMessage(squashAtomCommandFailure(cloneResult)),
}),
);
}
return;
}
await handleAddProjectForEnvironment({
environmentId: flow.environmentId,
rawCwd: cloneResult.value.cwd,
platform: targetPlatform,
currentProjectCwd: targetCurrentProjectCwd,
});
}
async function submitAddProjectCloneFlow(destinationPathInput?: string): Promise<void> {
if (!addProjectCloneFlow) {
return;
@@ -1863,19 +1686,15 @@ function OpenCommandPaletteDialog(props: {
const provider = remoteProjectSourceProvider(addProjectCloneFlow.source);
if (!provider) {
const confirmation: AddProjectCloneConfirmation = {
const destinationPath = getDefaultCloneParentPath(addProjectCloneFlow.environmentId);
setAddProjectCloneFlow({
step: "confirm",
environmentId: addProjectCloneFlow.environmentId,
source: addProjectCloneFlow.source,
repositoryInput: rawRepository,
repository: null,
remoteUrl: rawRepository,
};
if (await cloneIntoCloudEnvironmentIfConfigured(confirmation)) {
return;
}
const destinationPath = getDefaultCloneParentPath(addProjectCloneFlow.environmentId);
setAddProjectCloneFlow(confirmation);
});
setHighlightedItemValue(null);
setQuery(destinationPath);
setBrowseGeneration((generation) => generation + 1);
@@ -1904,32 +1723,78 @@ function OpenCommandPaletteDialog(props: {
return;
}
const repository = lookupResult.value;
const cloneEnvironment = environments.find(
(environment) => environment.environmentId === addProjectCloneFlow.environmentId,
);
const confirmation: AddProjectCloneConfirmation = {
const destinationPath = getDefaultCloneParentPath(addProjectCloneFlow.environmentId);
setAddProjectCloneFlow({
step: "confirm",
environmentId: addProjectCloneFlow.environmentId,
source: addProjectCloneFlow.source,
repositoryInput: rawRepository,
repository,
remoteUrl:
cloneEnvironment && cloudEnvironmentWorkspaceRoot(cloneEnvironment)
? repository.url
: repository.sshUrl,
};
if (await cloneIntoCloudEnvironmentIfConfigured(confirmation)) {
return;
}
const destinationPath = getDefaultCloneParentPath(addProjectCloneFlow.environmentId);
setAddProjectCloneFlow(confirmation);
remoteUrl: repository.sshUrl,
});
setHighlightedItemValue(null);
setQuery(destinationPath);
setBrowseGeneration((generation) => generation + 1);
return;
}
await cloneAndAddRemoteProject(addProjectCloneFlow, destinationPathInput ?? query);
const rawDestination = (destinationPathInput ?? query).trim();
if (rawDestination.length === 0 || isRemoteProjectCloning) {
return;
}
if (isUnsupportedWindowsProjectPath(rawDestination, browseEnvironmentPlatform)) {
toastManager.add(
stackedThreadToast({
type: "error",
title: "Clone failed",
description: "Windows-style paths are only supported on Windows.",
}),
);
return;
}
if (isExplicitRelativeProjectPath(rawDestination) && !currentProjectCwdForBrowse) {
toastManager.add(
stackedThreadToast({
type: "error",
title: "Clone failed",
description: "Relative paths require an active project.",
}),
);
return;
}
const destinationPath = resolveProjectPathForDispatch(
rawDestination,
currentProjectCwdForBrowse,
);
if (destinationPath.length === 0) {
return;
}
setIsRemoteProjectCloning(true);
const cloneResult = await cloneRepository({
environmentId: addProjectCloneFlow.environmentId,
input: {
remoteUrl: addProjectCloneFlow.remoteUrl,
destinationPath,
},
});
setIsRemoteProjectCloning(false);
if (cloneResult._tag === "Failure") {
if (!isAtomCommandInterrupted(cloneResult)) {
toastManager.add(
stackedThreadToast({
type: "error",
title: "Clone failed",
description: errorMessage(squashAtomCommandFailure(cloneResult)),
}),
);
}
return;
}
await handleAddProject(cloneResult.value.cwd);
}
const browseTo = useCallback(
-13
View File
@@ -1,13 +0,0 @@
import type { ComponentPropsWithoutRef } from "react";
/** Monochrome Render logomark from Render's official brand kit. */
export function RenderLogo(props: ComponentPropsWithoutRef<"svg">) {
return (
<svg viewBox="206 194 400 400" fill="none" aria-hidden="true" {...props}>
<path
fill="currentColor"
d="M605.28 288.733C605.221 287.368 605.102 286.033 604.984 284.668C604.954 284.342 604.954 283.986 604.894 283.659C604.805 282.829 604.687 282.027 604.568 281.197C604.449 280.336 604.36 279.506 604.241 278.675C604.152 278.082 604.034 277.488 603.915 276.924C603.737 275.886 603.559 274.818 603.351 273.78C603.173 272.949 602.965 272.148 602.787 271.317C602.609 270.516 602.431 269.745 602.253 268.944C602.045 268.113 601.778 267.312 601.54 266.481C601.333 265.71 601.125 264.968 600.887 264.197C600.62 263.366 600.323 262.535 600.027 261.704C599.789 260.992 599.552 260.28 599.314 259.568C598.928 258.53 598.513 257.521 598.127 256.512C597.919 256.008 597.741 255.533 597.533 255.029C597.058 253.931 596.584 252.863 596.079 251.795C595.901 251.409 595.723 250.994 595.545 250.608C595.07 249.599 594.535 248.62 594.031 247.641C593.793 247.196 593.586 246.751 593.348 246.306C592.755 245.208 592.102 244.111 591.478 243.043C591.3 242.746 591.152 242.449 590.974 242.153C590.291 241.025 589.579 239.927 588.837 238.83C588.688 238.592 588.54 238.355 588.391 238.118C587.501 236.812 586.581 235.507 585.631 234.231C584.741 233.044 583.82 231.857 582.871 230.7C582.811 230.611 582.752 230.522 582.663 230.433C564.319 208.211 536.626 194.089 505.609 194.059V194L505.52 194.059H505.549C496.942 194.059 488.571 195.157 480.587 197.204C475.808 198.421 471.148 200.023 466.666 201.892C465.182 202.515 463.698 203.197 462.243 203.88C432.769 218.061 411.398 246.306 406.679 279.891H406.62C404.542 294.281 400.119 307.899 393.827 320.419H394.035C372.129 363.854 327.132 393.671 275.129 393.671C251.918 393.671 230.131 387.738 211.135 377.324C208.909 376.107 206.208 377.71 206.208 380.231V393.671H206V593.254H405.7V493.448H405.907V443.545C405.907 415.982 428.258 393.642 455.832 393.642H505.757C514.305 393.642 522.587 392.544 530.512 390.497C535.291 389.251 539.951 387.678 544.433 385.809C545.917 385.186 547.401 384.504 548.855 383.821C579.398 369.106 601.303 339.288 604.894 304.071C605.221 300.719 605.399 297.307 605.399 293.865C605.399 292.145 605.369 290.424 605.28 288.733Z"
/>
</svg>
);
}
@@ -18,6 +18,7 @@ import {
type ThreadId,
} from "@t3tools/contracts";
import { getTerminalLabel } from "@t3tools/shared/terminalLabels";
import * as Schema from "effect/Schema";
import {
type PointerEvent as ReactPointerEvent,
type ReactNode,
@@ -57,6 +58,7 @@ import {
} from "../types";
import { readLocalApi } from "~/localApi";
import { useClientSettings } from "../hooks/useSettings";
import { useLocalStorage } from "../hooks/useLocalStorage";
import { useAttachedTerminalSession } from "../state/terminalSessions";
import { serverEnvironment } from "../state/server";
import { previewEnvironment } from "../state/preview";
@@ -64,6 +66,7 @@ import { terminalEnvironment } from "../state/terminal";
import { openTerminalLinkInPreview } from "./preview/openTerminalLinkInPreview";
import { useAtomCommand } from "../state/use-atom-command";
import { preventTerminalCloseShortcut } from "../lib/terminalCloseShortcut";
import { resolveTerminalFontPreference, TYPOGRAPHY_ADVANCED_STORAGE_KEY } from "../appearanceFonts";
const MIN_DRAWER_HEIGHT = 180;
const MAX_DRAWER_HEIGHT_RATIO = 0.75;
@@ -241,6 +244,7 @@ export function shouldHandleTerminalExit(
}
interface TerminalViewportProps {
advancedTypography: boolean;
threadRef: ScopedThreadRef;
threadId: ThreadId;
terminalId: string;
@@ -264,6 +268,7 @@ interface TerminalLaunchLocation {
}
export function TerminalViewport({
advancedTypography,
threadRef,
threadId,
terminalId,
@@ -312,10 +317,12 @@ export function TerminalViewport({
onAddTerminalContext(selection);
});
const readTerminalLabel = useEffectEvent(() => terminalLabel);
// The terminal inherits the monospace (code) preference unless it has an
// override of its own, so one font choice drives every mono surface.
const terminalFontFamily = useClientSettings(
(settings) => settings.fontFamilyTerminal.trim() || settings.fontFamilyCode,
const terminalFontFamily = useClientSettings((settings) =>
resolveTerminalFontPreference({
advanced: advancedTypography,
code: settings.fontFamilyCode,
terminal: settings.fontFamilyTerminal,
}),
);
const terminalFontSize = useClientSettings((settings) => settings.fontSizeTerminal);
const terminalFontRef = useRef({ family: terminalFontFamily, size: terminalFontSize });
@@ -921,6 +928,11 @@ export default function ThreadTerminalDrawer({
terminalLaunchLocationsById,
}: ThreadTerminalDrawerProps) {
const isPanel = mode === "panel";
const [advancedTypography] = useLocalStorage(
TYPOGRAPHY_ADVANCED_STORAGE_KEY,
false,
Schema.Boolean,
);
const controlledDrawerHeight = clampDrawerHeight(height);
const [drawerHeightState, setDrawerHeightState] = useState(() => ({
threadId,
@@ -1357,6 +1369,7 @@ export default function ThreadTerminalDrawer({
>
<div className="h-full p-1">
<TerminalViewport
advancedTypography={advancedTypography}
threadRef={threadRef}
threadId={threadId}
terminalId={terminalId}
@@ -1384,6 +1397,7 @@ export default function ThreadTerminalDrawer({
) : (
<div className="h-full p-1">
<TerminalViewport
advancedTypography={advancedTypography}
key={resolvedActiveTerminalId}
threadRef={threadRef}
threadId={threadId}
+32 -9
View File
@@ -108,13 +108,24 @@ 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<{
bottom: number;
left: number;
maxHeight: number;
width: number;
} | null>(null);
const [position, setPosition] = useState<ComposerCommandMenuPosition | null>(null);
useLayoutEffect(() => {
const anchor = props.anchor;
@@ -125,12 +136,15 @@ function ComposerCommandMenuLayer(props: { anchor: HTMLElement | null; children:
const updatePosition = () => {
const rect = anchor.getBoundingClientRect();
setPosition({
const next = {
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();
@@ -139,7 +153,16 @@ function ComposerCommandMenuLayer(props: { anchor: HTMLElement | null; children:
const observer =
typeof ResizeObserver === "undefined" ? null : new ResizeObserver(updatePosition);
observer?.observe(anchor);
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);
}
}
return () => {
observer?.disconnect();
@@ -101,7 +101,8 @@ export function DraftHeroHeadline({
<Menu>
<MenuTrigger
aria-label={hasResolvedProject ? "Change project" : "Choose a project"}
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"
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}
>
{activeProjectDisplayName ?? "Choose a project"}
</MenuTrigger>
@@ -122,7 +123,9 @@ export function DraftHeroHeadline({
{projectPickerEntries.map(({ group }) => {
return (
<MenuRadioItem key={group.projectKey} value={group.projectKey} closeOnClick>
<span className="min-w-0 truncate">{group.displayName}</span>
<span className="block min-w-0 truncate" title={group.displayName}>
{group.displayName}
</span>
</MenuRadioItem>
);
})}
@@ -541,6 +541,10 @@ export const ModelPickerContent = memo(function ModelPickerContent(props: {
}
return mapping.size > 0 ? mapping : EMPTY_MODEL_JUMP_LABELS;
}, [keybindings, modelJumpCommandByKey, modelJumpShortcutContext]);
const modelListExtraData = useMemo(
() => ({ favoritesSet, modelJumpLabelByKey }),
[favoritesSet, modelJumpLabelByKey],
);
useEffect(() => {
const onWindowKeyDown = (event: globalThis.KeyboardEvent) => {
@@ -710,7 +714,7 @@ export const ModelPickerContent = memo(function ModelPickerContent(props: {
<LegendList<string>
ref={modelListRef}
data={filteredItemKeys}
extraData={favoritesSet}
extraData={modelListExtraData}
keyExtractor={(modelKey) => modelKey}
renderItem={({ item: modelKey, index }) => {
if (legacySection?.key === modelKey) {
@@ -1,347 +0,0 @@
import { connectionStatusText } from "@t3tools/client-runtime/connection";
import {
isAtomCommandInterrupted,
squashAtomCommandFailure,
} from "@t3tools/client-runtime/state/runtime";
import type { EnvironmentId } from "@t3tools/contracts";
import { CheckIcon, CopyIcon, ExternalLinkIcon, LoaderCircleIcon } from "lucide-react";
import { useCallback, useMemo, useState } from "react";
import { cloudEnvironmentProvider } from "~/cloud/cloudEnvironment";
import { maskedRenderServiceUrl, requestRenderPairing } from "~/cloud/renderBootstrap";
import { openCommandPalette } from "~/commandPaletteBus";
import { environmentCatalog } from "~/connection/catalog";
import { connectPairing as connectPairingAtom } from "~/connection/onboarding";
import { useCopyToClipboard } from "~/hooks/useCopyToClipboard";
import { useAtomCommand } from "~/state/use-atom-command";
import { type EnvironmentPresentation, useEnvironments } from "~/state/environments";
import { RenderLogo } from "../RenderLogo";
import { Button } from "../ui/button";
import { Input } from "../ui/input";
import { stackedThreadToast, toastManager } from "../ui/toast";
import { SettingsPageContainer, SettingsRow, SettingsSection } from "./settingsLayout";
import { searchableSetting } from "./settingsSearch";
const RENDER_DEPLOY_URL =
"https://render.com/deploy?repo=https%3A%2F%2Fgithub.com%2Fpingdotgg%2Ft3code%2Ftree%2Ffeat%2Frender-cloud-environment";
const CODEX_LOGIN_COMMAND = "codex login --device-auth";
type RenderAuthenticationMode = "api-key" | "subscription";
function CopyValueButton({ value, label }: { readonly value: string; readonly label: string }) {
const { copyToClipboard, isCopied } = useCopyToClipboard({ target: label });
return (
<Button
size="icon-sm"
variant="outline"
aria-label={`Copy ${label}`}
onClick={() => copyToClipboard(value, undefined)}
>
{isCopied ? <CheckIcon className="size-3.5" /> : <CopyIcon className="size-3.5" />}
</Button>
);
}
function CopyCommand({ command }: { readonly command: string }) {
return (
<div className="mt-2 flex min-w-0 items-start gap-2 rounded-lg border border-border/70 bg-muted/20 p-2">
<code className="min-w-0 flex-1 overflow-x-auto py-1 text-xs text-foreground">{command}</code>
<CopyValueButton value={command} label="command" />
</div>
);
}
function RenderEnvironmentRow({
environment,
busyEnvironmentIds,
onConnect,
onDisconnect,
}: {
readonly environment: EnvironmentPresentation;
readonly busyEnvironmentIds: ReadonlySet<EnvironmentId>;
readonly onConnect: (environmentId: EnvironmentId) => void;
readonly onDisconnect: (environmentId: EnvironmentId) => void;
}) {
const isConnected = environment.connection.phase === "connected";
const isBusy = busyEnvironmentIds.has(environment.environmentId);
const serviceLabel = environment.displayUrl
? maskedRenderServiceUrl(environment.displayUrl)
: null;
return (
<SettingsRow
title={
<span className="inline-flex items-center gap-2">
<RenderLogo className="size-4" />
{environment.label}
</span>
}
description="Powered by Render"
status={[connectionStatusText(environment.connection), serviceLabel]
.filter(Boolean)
.join(" · ")}
control={
<>
{environment.displayUrl ? (
<Button
size="icon-xs"
variant="ghost"
aria-label="Open Render service"
render={<a href={environment.displayUrl} target="_blank" rel="noreferrer" />}
>
<ExternalLinkIcon className="size-3.5" />
</Button>
) : null}
{isConnected ? (
<Button
size="xs"
variant="outline"
onClick={() => openCommandPalette({ open: "add-project" })}
>
Add project
</Button>
) : null}
<Button
size="xs"
variant="outline"
disabled={isBusy}
onClick={() =>
isConnected
? onDisconnect(environment.environmentId)
: onConnect(environment.environmentId)
}
>
{isBusy ? <LoaderCircleIcon className="size-3 animate-spin" /> : null}
{isConnected ? "Disconnect" : "Connect"}
</Button>
</>
}
/>
);
}
export function CloudEnvironmentsSettings() {
const { environments } = useEnvironments();
const connectPairing = useAtomCommand(connectPairingAtom, { reportFailure: false });
const retryEnvironment = useAtomCommand(environmentCatalog.retryNow, { reportFailure: false });
const removeEnvironment = useAtomCommand(environmentCatalog.remove, { reportFailure: false });
const [serviceUrl, setServiceUrl] = useState("");
const [pairing, setPairing] = useState(false);
const [pairingStatus, setPairingStatus] = useState<string | null>(null);
const [pairError, setPairError] = useState<string | null>(null);
const [busyEnvironmentIds, setBusyEnvironmentIds] = useState<ReadonlySet<EnvironmentId>>(
() => new Set(),
);
const [authenticationMode, setAuthenticationMode] = useState<RenderAuthenticationMode>("api-key");
const renderEnvironments = useMemo(
() => environments.filter((environment) => cloudEnvironmentProvider(environment) === "render"),
[environments],
);
const hasConnectedRenderEnvironment = renderEnvironments.some(
(environment) => environment.connection.phase === "connected",
);
const reportFailure = useCallback((title: string, description: string) => {
toastManager.add(stackedThreadToast({ type: "error", title, description }));
}, []);
const setEnvironmentBusy = useCallback((environmentId: EnvironmentId, busy: boolean) => {
setBusyEnvironmentIds((current) => {
const next = new Set(current);
if (busy) next.add(environmentId);
else next.delete(environmentId);
return next;
});
}, []);
const handlePair = useCallback(async () => {
if (pairing) return;
setPairError(null);
setPairing(true);
setPairingStatus("Waking the Render service…");
try {
const pairingInput = await requestRenderPairing({ serviceUrl });
setServiceUrl(pairingInput.host);
setPairingStatus("Connecting T3 Code…");
const result = await connectPairing({
host: pairingInput.host,
pairingCode: pairingInput.pairingCode,
});
if (result._tag === "Failure") {
if (!isAtomCommandInterrupted(result)) {
const failure = squashAtomCommandFailure(result);
setPairError(failure instanceof Error ? failure.message : "Could not pair environment.");
}
return;
}
toastManager.add({ type: "success", title: "Render environment connected" });
} catch (error) {
setPairError(error instanceof Error ? error.message : "Could not connect Render.");
} finally {
setPairing(false);
setPairingStatus(null);
}
}, [connectPairing, pairing, serviceUrl]);
const handleConnect = useCallback(
async (environmentId: EnvironmentId) => {
setEnvironmentBusy(environmentId, true);
const result = await retryEnvironment(environmentId);
setEnvironmentBusy(environmentId, false);
if (result._tag === "Failure" && !isAtomCommandInterrupted(result)) {
const failure = squashAtomCommandFailure(result);
reportFailure(
"Could not connect Render environment",
failure instanceof Error ? failure.message : "Could not connect Render environment.",
);
}
},
[reportFailure, retryEnvironment, setEnvironmentBusy],
);
const handleDisconnect = useCallback(
async (environmentId: EnvironmentId) => {
setEnvironmentBusy(environmentId, true);
const result = await removeEnvironment(environmentId);
setEnvironmentBusy(environmentId, false);
if (result._tag === "Failure" && !isAtomCommandInterrupted(result)) {
const failure = squashAtomCommandFailure(result);
reportFailure(
"Could not disconnect Render environment",
failure instanceof Error ? failure.message : "Could not disconnect Render environment.",
);
}
},
[removeEnvironment, reportFailure, setEnvironmentBusy],
);
return (
<SettingsPageContainer>
<SettingsSection
{...searchableSetting("cloud-environments")}
icon={<RenderLogo className="size-5" />}
/>
<SettingsSection title="1. Deploy to Render">
<div className="px-3 sm:px-4">
<div
role="tablist"
aria-label="Codex authentication method"
className="inline-flex rounded-lg border border-border/70 bg-muted/20 p-1"
>
<button
type="button"
role="tab"
aria-selected={authenticationMode === "api-key"}
className="rounded-md px-3 py-1.5 text-xs font-medium text-muted-foreground aria-selected:bg-background aria-selected:text-foreground aria-selected:shadow-xs"
onClick={() => setAuthenticationMode("api-key")}
>
OpenAI API key
</button>
<button
type="button"
role="tab"
aria-selected={authenticationMode === "subscription"}
className="rounded-md px-3 py-1.5 text-xs font-medium text-muted-foreground aria-selected:bg-background aria-selected:text-foreground aria-selected:shadow-xs"
onClick={() => setAuthenticationMode("subscription")}
>
ChatGPT subscription
</button>
</div>
</div>
{authenticationMode === "api-key" ? (
<div role="tabpanel">
<SettingsRow
title="OpenAI API key"
description="Render asks for OPENAI_API_KEY. Codex is authenticated automatically when the service starts."
status="OpenAI API usage is billed separately from Render."
control={
<Button
size="sm"
render={<a href={RENDER_DEPLOY_URL} target="_blank" rel="noreferrer" />}
>
Deploy on Render
<ExternalLinkIcon className="size-3.5" />
</Button>
}
/>
</div>
) : (
<div role="tabpanel">
<SettingsRow
title="ChatGPT subscription"
description="Leave OPENAI_API_KEY empty. After connecting and adding a project, run the command below in its T3 terminal."
status="A free instance forgets this login whenever it restarts or spins down."
control={
<Button
size="sm"
variant="outline"
render={<a href={RENDER_DEPLOY_URL} target="_blank" rel="noreferrer" />}
>
Deploy on Render
<ExternalLinkIcon className="size-3.5" />
</Button>
}
>
<CopyCommand command={CODEX_LOGIN_COMMAND} />
</SettingsRow>
</div>
)}
</SettingsSection>
<SettingsSection title="2. Connect in T3 Code">
<SettingsRow
title="Render service URL"
description="Paste the .onrender.com URL shown at the top of the Render service. T3 Code pairs it here automatically."
status={pairingStatus}
>
<div className="mt-3 flex flex-col gap-2 sm:flex-row">
<Input
value={serviceUrl}
onChange={(event) => setServiceUrl(event.target.value)}
placeholder="https://your-service.onrender.com"
autoComplete="url"
spellCheck={false}
onKeyDown={(event) => {
if (event.key === "Enter" && !pairing) void handlePair();
}}
/>
<Button
disabled={pairing || serviceUrl.trim().length === 0}
onClick={() => void handlePair()}
>
{pairing ? <LoaderCircleIcon className="size-4 animate-spin" /> : null}
Connect environment
</Button>
</div>
{pairError ? <p className="mt-2 text-xs text-destructive">{pairError}</p> : null}
</SettingsRow>
{renderEnvironments.map((environment) => (
<RenderEnvironmentRow
key={environment.environmentId}
environment={environment}
busyEnvironmentIds={busyEnvironmentIds}
onConnect={(environmentId) => void handleConnect(environmentId)}
onDisconnect={(environmentId) => void handleDisconnect(environmentId)}
/>
))}
</SettingsSection>
<SettingsSection title="3. Add a project">
<SettingsRow
title="Clone a public GitHub repository"
description="Paste a GitHub URL and T3 Code clones it into the Render workspace, ready for an agent."
status={hasConnectedRenderEnvironment ? "Render is ready" : "Connect Render first"}
control={
<Button
size="sm"
disabled={!hasConnectedRenderEnvironment}
onClick={() => openCommandPalette({ open: "add-project" })}
>
Add project
</Button>
}
/>
</SettingsSection>
</SettingsPageContainer>
);
}
@@ -131,7 +131,6 @@ import { ConnectionStatusDot } from "../ConnectionStatusDot";
import { ServerUpdateAction, ServerUpdateProgress } from "../ServerUpdateAction";
import { CloudEnvironmentConnectRows } from "../cloud/CloudEnvironmentConnectList";
import { ITEM_ROW_CLASSNAME, ITEM_ROW_INNER_CLASSNAME } from "./itemRows";
import { cloudEnvironmentProvider, cloudEnvironmentProviderLabel } from "~/cloud/cloudEnvironment";
const DEFAULT_TAILSCALE_SERVE_PORT = 443;
const EMPTY_ADVERTISED_ENDPOINTS: ReadonlyArray<AdvertisedEndpoint> = [];
@@ -1395,9 +1394,7 @@ function SavedBackendListRow({
environment.entry.profile.value._tag === "SshConnectionProfile"
? environment.entry.profile.value.target
: null;
const cloudProvider = cloudEnvironmentProvider(environment);
const metadataBits = [
cloudProvider ? `Powered by ${cloudEnvironmentProviderLabel(cloudProvider)}` : null,
sshTarget ? `SSH ${formatDesktopSshTarget(sshTarget)}` : null,
environment.relayManaged ? "T3 Connect" : null,
].filter((value): value is string => value !== null);
@@ -1745,10 +1742,6 @@ export function ConnectionsSettings() {
.toSorted((left, right) => left.label.localeCompare(right.label)),
[environments],
);
const savedNonCloudEnvironments = useMemo(
() => savedEnvironments.filter((environment) => cloudEnvironmentProvider(environment) === null),
[savedEnvironments],
);
const savedDesktopSshEnvironmentsByAlias = useMemo(
() =>
savedEnvironments.reduce<Record<string, EnvironmentPresentation>>(
@@ -3415,7 +3408,7 @@ export function ConnectionsSettings() {
</Dialog>
}
>
{savedNonCloudEnvironments.map((environment) => (
{savedEnvironments.map((environment) => (
<SavedBackendListRow
key={environment.environmentId}
environment={environment}
@@ -129,7 +129,6 @@ export function FontFamilyPicker({
if (initialOpen) setOpen(true);
// The prop is only meaningful at mount - the control just swapped in
// under an active focus - so later changes are deliberately ignored.
// eslint-disable-next-line react-hooks/exhaustive-deps
}, []);
const listRef = useRef<LegendListRef | null>(null);
const enumeration = useFontEnumeration();
@@ -113,18 +113,33 @@ export function CodeFontPreview() {
if (htmlByFile === null) return null;
return (
<div className="mt-1 mb-2 space-y-2">
{htmlByFile.map((html, index) => (
<StaticDiffHtml key={index} html={html} />
{htmlByFile.map((html) => (
<StaticDiffHtml key={html} html={html} />
))}
</div>
);
}
const TERMINAL_PROMPT = "\x1b[2m$\x1b[0m ";
// A zsh-style prompt: green arrow, cyan project, blue/red git segment,
// yellow dirty marker. It doubles as the echo loop's fresh-line prompt.
const TERMINAL_PROMPT =
"\x1b[1;32m→\x1b[0m \x1b[1;36mt3code\x1b[0m \x1b[1;34mgit:(\x1b[1;31mmain\x1b[1;34m)\x1b[0m \x1b[1;33m✗\x1b[0m ";
// A dev-server startup: brand line, addresses, a test summary, and a READY
// badge. Together the lines cover bold, dim, underline, the six accent
// colors, and a background cell, so a font choice shows every SGR the
// terminal actually renders.
const TERMINAL_PREVIEW_TRANSCRIPT =
`${TERMINAL_PROMPT}npm run dev\r\n` +
"\x1b[32m✓\x1b[0m Ready in 430ms\r\n" +
"\x1b[2mLocal:\x1b[0m \x1b[36mhttp://localhost:3000\x1b[0m\r\n" +
`${TERMINAL_PROMPT}vpr dev\r\n` +
"\r\n" +
" \x1b[1;32mVITE\x1b[0m \x1b[32mv7.1.1\x1b[0m \x1b[2mready in\x1b[0m \x1b[1m1.24s\x1b[0m\r\n" +
"\r\n" +
" \x1b[32m→\x1b[0m \x1b[2mLocal:\x1b[0m \x1b[4;36mhttp://127.0.0.1:5173/\x1b[0m\r\n" +
" \x1b[32m→\x1b[0m \x1b[2mNetwork:\x1b[0m \x1b[4;36mhttp://192.168.1.24:5173/\x1b[0m\r\n" +
"\r\n" +
" \x1b[32m✓ 85 passed\x1b[0m \x1b[33m△ 2 warnings\x1b[0m \x1b[31m✗ 0 failed\x1b[0m\r\n" +
"\r\n" +
" \x1b[42;30m READY \x1b[0m \x1b[2mwatching for changes — press\x1b[0m \x1b[1mq\x1b[0m \x1b[2mto quit\x1b[0m\r\n" +
"\r\n" +
TERMINAL_PROMPT;
/** The surface treats an omitted family or size as "use the built-in default". */
@@ -225,7 +240,7 @@ export function TerminalFontPreview({ family, size }: { family: string; size: nu
return (
<div
ref={mountRef}
className="relative mt-1 mb-2 h-36 overflow-hidden rounded-lg border border-border"
className="relative mt-1 mb-2 h-52 overflow-hidden rounded-lg border border-border"
aria-label="Terminal font preview"
/>
);
@@ -115,8 +115,9 @@ import {
isFontFamilyAvailable,
isMonospaceFamily,
resolveDefaultFamilyLabel,
resolveTerminalFontPreference,
TYPOGRAPHY_ADVANCED_STORAGE_KEY,
} from "../../appearanceFonts";
import { DEFAULT_TERMINAL_FONT_FAMILY } from "~/terminal/ghostty/surface";
import { CodeFontPreview, PromptFontPreview, TerminalFontPreview } from "./SettingsFontPreviews";
import { discoverInstalledFonts, FontFamilyPicker, useFontEnumeration } from "./FontFamilyPicker";
import {
@@ -1152,10 +1153,8 @@ function useFontDefaultFamilies() {
return {
sans: defaults.sans,
code: defaults.code,
// The composer inherits whatever the interface preference resolves to;
// the terminal inherits the monospace preference the same way.
// The composer inherits whatever the interface preference resolves to.
interfaceFamily: settings.fontFamilySans.trim() || defaults.sans,
monoFamily: settings.fontFamilyCode.trim() || defaults.code,
};
}
@@ -1245,8 +1244,8 @@ function TerminalFontRow() {
return (
<FontFamilySettingsRow
{...searchableSetting("terminal-font")}
description="Terminal output. Follows the monospace font unless set."
defaultFamily={defaults.monoFamily}
description="Terminal output, independent from code blocks and diffs."
defaultFamily={defaults.code}
value={settings.fontFamilyTerminal}
onValueChange={(fontFamilyTerminal) => updateSettings({ fontFamilyTerminal })}
requireMonospace
@@ -1259,7 +1258,11 @@ function TerminalFontRow() {
}}
preview={
<TerminalFontPreview
family={settings.fontFamilyTerminal.trim() || settings.fontFamilyCode}
family={resolveTerminalFontPreference({
advanced: true,
code: settings.fontFamilyCode,
terminal: settings.fontFamilyTerminal,
})}
size={settings.fontSizeTerminal}
/>
}
@@ -1351,7 +1354,11 @@ function SimpleFontRows() {
<>
<CodeFontPreview />
<TerminalFontPreview
family={settings.fontFamilyTerminal.trim() || settings.fontFamilyCode}
family={resolveTerminalFontPreference({
advanced: false,
code: settings.fontFamilyCode,
terminal: settings.fontFamilyTerminal,
})}
size={settings.fontSizeTerminal}
/>
</>
@@ -1371,8 +1378,6 @@ const ADVANCED_TYPOGRAPHY_TARGET_IDS: ReadonlySet<string> = new Set([
: []),
]);
const TYPOGRAPHY_ADVANCED_KEY = "t3code:typography-advanced";
/**
* The two-font view by default - one sans, one monospace, each cascading to
* every surface it reaches - with an Advanced switch in the section header
@@ -1381,7 +1386,11 @@ const TYPOGRAPHY_ADVANCED_KEY = "t3code:typography-advanced";
* target exists to scroll to.
*/
function TypographySection() {
const [advanced, setAdvanced] = useLocalStorage(TYPOGRAPHY_ADVANCED_KEY, false, Schema.Boolean);
const [advanced, setAdvanced] = useLocalStorage(
TYPOGRAPHY_ADVANCED_STORAGE_KEY,
false,
Schema.Boolean,
);
const searchTargetId = useSettingsSearchTargetId();
// Flip Advanced on once per search jump so the hidden target can mount and
// scroll; tracking the handled id lets the user turn it back off without
@@ -35,7 +35,6 @@ import {
useSidebar,
} from "../ui/sidebar";
import { T3ConnectSidebarAvatar, T3ConnectSidebarSignIn } from "../clerk/T3ConnectSidebarSignIn";
import { RenderLogo } from "../RenderLogo";
import { scrollToSettingsTarget } from "./settingsLayout";
import {
searchSettings,
@@ -53,7 +52,6 @@ const SETTINGS_SECTION_ICONS: Readonly<
"/settings/providers": BotIcon,
"/settings/source-control": GitBranchIcon,
"/settings/connections": Link2Icon,
"/settings/cloud-environments": RenderLogo,
"/settings/beta": FlaskConicalIcon,
"/settings/archived": ArchiveIcon,
};
@@ -104,7 +104,7 @@ export function SettingsSection({
title: string;
icon?: ReactNode;
headerAction?: ReactNode;
children?: ReactNode;
children: ReactNode;
}) {
const targetRef = useSettingsSearchTarget<HTMLElement>(sectionProps.id);
@@ -122,9 +122,7 @@ export function SettingsSection({
</h2>
<div className="flex min-h-7 min-w-7 items-center justify-end">{headerAction}</div>
</div>
{children !== undefined && children !== null ? (
<div className="relative space-y-1 overflow-visible text-foreground">{children}</div>
) : null}
<div className="relative space-y-1 overflow-visible text-foreground">{children}</div>
</section>
);
}
@@ -5,7 +5,6 @@ export type SettingsPath =
| "/settings/providers"
| "/settings/source-control"
| "/settings/connections"
| "/settings/cloud-environments"
| "/settings/beta"
| "/settings/archived";
@@ -27,7 +26,6 @@ export const SETTINGS_SECTION_LABELS: Readonly<Record<SettingsPath, string>> = {
"/settings/providers": "Providers",
"/settings/source-control": "Source Control",
"/settings/connections": "Connections",
"/settings/cloud-environments": "Cloud environments",
"/settings/beta": "Beta",
"/settings/archived": "Archive",
};
@@ -168,11 +166,6 @@ export const SETTINGS_SEARCH_ITEMS = [
title: "Source control",
to: "/settings/source-control",
},
{
id: "cloud-environments",
title: "Cloud environments",
to: "/settings/cloud-environments",
},
{
id: "remote-environments",
title: "Remote environments",
@@ -19,6 +19,15 @@ import { Alert, AlertDescription, AlertTitle } from "../ui/alert";
import { Separator } from "../ui/separator";
import { Tooltip, TooltipPopup, TooltipTrigger } from "../ui/tooltip";
function keyReleaseNoteItems(items: ReadonlyArray<string>) {
const occurrences = new Map<string, number>();
return items.map((item) => {
const occurrence = occurrences.get(item) ?? 0;
occurrences.set(item, occurrence + 1);
return { item, key: JSON.stringify([item, occurrence]) };
});
}
function SidebarUpdateReleaseNotesTooltip({
state,
tooltip,
@@ -44,8 +53,8 @@ function SidebarUpdateReleaseNotesTooltip({
{index === 0 ? "What's changed" : `Changes in ${releaseNote.version}`}
</h3>
<ul className="mt-2 space-y-1.5 pl-4 text-xs leading-5 text-popover-foreground/90">
{releaseNote.items.map((item, itemIndex) => (
<li className="list-disc break-words" key={`${releaseNote.version}-${itemIndex}`}>
{keyReleaseNoteItems(releaseNote.items).map(({ item, key }) => (
<li className="list-disc break-words" key={key}>
{item}
</li>
))}
+3
View File
@@ -1,4 +1,5 @@
export {
buildProjectGroups,
deriveLogicalProjectKey,
deriveLogicalProjectKeyFromRef,
deriveLogicalProjectKeyFromSettings,
@@ -11,4 +12,6 @@ export {
selectProjectGroupingSettings,
type ProjectGroupingMode,
type ProjectGroupingSettings,
type ProjectGroup,
type ProjectGroupMember,
} from "@t3tools/client-runtime/state/project-grouping";
-22
View File
@@ -20,7 +20,6 @@ import { Route as SettingsKeybindingsRouteImport } from './routes/settings.keybi
import { Route as SettingsGeneralRouteImport } from './routes/settings.general'
import { Route as SettingsDiagnosticsRouteImport } from './routes/settings.diagnostics'
import { Route as SettingsConnectionsRouteImport } from './routes/settings.connections'
import { Route as SettingsCloudEnvironmentsRouteImport } from './routes/settings.cloud-environments'
import { Route as SettingsBetaRouteImport } from './routes/settings.beta'
import { Route as SettingsArchivedRouteImport } from './routes/settings.archived'
import { Route as SettingsAppearanceRouteImport } from './routes/settings.appearance'
@@ -82,12 +81,6 @@ const SettingsConnectionsRoute = SettingsConnectionsRouteImport.update({
path: '/connections',
getParentRoute: () => SettingsRoute,
} as any)
const SettingsCloudEnvironmentsRoute =
SettingsCloudEnvironmentsRouteImport.update({
id: '/cloud-environments',
path: '/cloud-environments',
getParentRoute: () => SettingsRoute,
} as any)
const SettingsBetaRoute = SettingsBetaRouteImport.update({
id: '/beta',
path: '/beta',
@@ -129,7 +122,6 @@ export interface FileRoutesByFullPath {
'/settings/appearance': typeof SettingsAppearanceRoute
'/settings/archived': typeof SettingsArchivedRoute
'/settings/beta': typeof SettingsBetaRoute
'/settings/cloud-environments': typeof SettingsCloudEnvironmentsRoute
'/settings/connections': typeof SettingsConnectionsRoute
'/settings/diagnostics': typeof SettingsDiagnosticsRoute
'/settings/general': typeof SettingsGeneralRoute
@@ -147,7 +139,6 @@ export interface FileRoutesByTo {
'/settings/appearance': typeof SettingsAppearanceRoute
'/settings/archived': typeof SettingsArchivedRoute
'/settings/beta': typeof SettingsBetaRoute
'/settings/cloud-environments': typeof SettingsCloudEnvironmentsRoute
'/settings/connections': typeof SettingsConnectionsRoute
'/settings/diagnostics': typeof SettingsDiagnosticsRoute
'/settings/general': typeof SettingsGeneralRoute
@@ -168,7 +159,6 @@ export interface FileRoutesById {
'/settings/appearance': typeof SettingsAppearanceRoute
'/settings/archived': typeof SettingsArchivedRoute
'/settings/beta': typeof SettingsBetaRoute
'/settings/cloud-environments': typeof SettingsCloudEnvironmentsRoute
'/settings/connections': typeof SettingsConnectionsRoute
'/settings/diagnostics': typeof SettingsDiagnosticsRoute
'/settings/general': typeof SettingsGeneralRoute
@@ -190,7 +180,6 @@ export interface FileRouteTypes {
| '/settings/appearance'
| '/settings/archived'
| '/settings/beta'
| '/settings/cloud-environments'
| '/settings/connections'
| '/settings/diagnostics'
| '/settings/general'
@@ -208,7 +197,6 @@ export interface FileRouteTypes {
| '/settings/appearance'
| '/settings/archived'
| '/settings/beta'
| '/settings/cloud-environments'
| '/settings/connections'
| '/settings/diagnostics'
| '/settings/general'
@@ -228,7 +216,6 @@ export interface FileRouteTypes {
| '/settings/appearance'
| '/settings/archived'
| '/settings/beta'
| '/settings/cloud-environments'
| '/settings/connections'
| '/settings/diagnostics'
| '/settings/general'
@@ -327,13 +314,6 @@ declare module '@tanstack/react-router' {
preLoaderRoute: typeof SettingsConnectionsRouteImport
parentRoute: typeof SettingsRoute
}
'/settings/cloud-environments': {
id: '/settings/cloud-environments'
path: '/cloud-environments'
fullPath: '/settings/cloud-environments'
preLoaderRoute: typeof SettingsCloudEnvironmentsRouteImport
parentRoute: typeof SettingsRoute
}
'/settings/beta': {
id: '/settings/beta'
path: '/beta'
@@ -397,7 +377,6 @@ interface SettingsRouteChildren {
SettingsAppearanceRoute: typeof SettingsAppearanceRoute
SettingsArchivedRoute: typeof SettingsArchivedRoute
SettingsBetaRoute: typeof SettingsBetaRoute
SettingsCloudEnvironmentsRoute: typeof SettingsCloudEnvironmentsRoute
SettingsConnectionsRoute: typeof SettingsConnectionsRoute
SettingsDiagnosticsRoute: typeof SettingsDiagnosticsRoute
SettingsGeneralRoute: typeof SettingsGeneralRoute
@@ -410,7 +389,6 @@ const SettingsRouteChildren: SettingsRouteChildren = {
SettingsAppearanceRoute: SettingsAppearanceRoute,
SettingsArchivedRoute: SettingsArchivedRoute,
SettingsBetaRoute: SettingsBetaRoute,
SettingsCloudEnvironmentsRoute: SettingsCloudEnvironmentsRoute,
SettingsConnectionsRoute: SettingsConnectionsRoute,
SettingsDiagnosticsRoute: SettingsDiagnosticsRoute,
SettingsGeneralRoute: SettingsGeneralRoute,
@@ -1,7 +0,0 @@
import { createFileRoute } from "@tanstack/react-router";
import { CloudEnvironmentsSettings } from "../components/settings/CloudEnvironmentsSettings";
export const Route = createFileRoute("/settings/cloud-environments")({
component: CloudEnvironmentsSettings,
});
+33 -138
View File
@@ -1,11 +1,5 @@
import { scopeProjectRef } from "@t3tools/client-runtime/environment";
import type { EnvironmentId, ScopedProjectRef } from "@t3tools/contracts";
import {
deriveLogicalProjectKeyFromSettings,
derivePhysicalProjectKey,
deriveProjectGroupLabel,
type ProjectGroupingSettings,
} from "./logicalProject";
import { buildProjectGroups, type ProjectGroupingSettings } from "./logicalProject";
import type { Project } from "./types";
export type EnvironmentPresence = "local-only" | "remote-only" | "mixed";
@@ -37,77 +31,21 @@ 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>();
for (const [physicalProjectKey, winner] of collectProjectWinnersByPhysicalKey(input)) {
mapping.set(physicalProjectKey, winner.logicalKey);
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);
}
}
return mapping;
}
@@ -123,59 +61,24 @@ export function buildSidebarProjectSnapshots(input: {
// legacy behavior.
isDesktopLocalEnvironment?: (environmentId: EnvironmentId) => boolean;
}): SidebarProjectSnapshot[] {
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) ?? [];
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 representative =
(input.primaryEnvironmentId
? members.find((member) => member.environmentId === input.primaryEnvironmentId)
: null) ?? members[0];
if (!representative) {
continue;
}
members.find(
(member) =>
member.environmentId === group.representative.environmentId &&
member.id === group.representative.id,
) ?? members[0]!;
const hasLocal =
input.primaryEnvironmentId !== null &&
@@ -196,27 +99,19 @@ export function buildSidebarProjectSnapshots(input: {
remoteMembers.length > 0 &&
remoteMembers.every((member) => isDesktopLocal(member.environmentId));
result.push({
return {
...representative,
projectKey: logicalKey,
displayName:
members.length > 1
? deriveProjectGroupLabel({
representative,
members,
})
: representative.title,
projectKey: group.key,
displayName: group.label,
groupedProjectCount: members.length,
environmentPresence:
hasLocal && hasRemote ? "mixed" : hasRemote ? "remote-only" : "local-only",
allRemoteMembersAreDesktopLocal,
memberProjects: members,
memberProjectRefs: projectRefsByLogicalKey.get(logicalKey) ?? [],
memberProjectRefs: group.memberProjectRefs,
remoteEnvironmentLabels,
});
}
return result;
};
});
}
export function buildSidebarProjectPickerEntries(input: {
@@ -71,6 +71,62 @@ 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 = {
+19 -2
View File
@@ -12,6 +12,11 @@ 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 {
@@ -98,6 +103,7 @@ 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 {
@@ -114,6 +120,7 @@ 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)
@@ -216,10 +223,20 @@ export function renderGhosttySnapshot(options: {
for (let column = 0; column < row.cells.length; column += 1) {
const cell = row.cells[column];
if (!cell || (!cell.underline && !cell.strikethrough && !cell.overline)) continue;
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;
}
context.fillStyle = cssColor(cell.foreground);
const left = padding + column * metrics.width;
if (cell.underline) context.fillRect(left, top + metrics.height - 2, metrics.width, 1);
if (cell.underline || hoveredLink) {
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);
}
+70 -20
View File
@@ -1,4 +1,4 @@
import { describe, expect, it } from "vite-plus/test";
import { describe, expect, it, vi } from "vite-plus/test";
import type { GhosttyCell, GhosttyRow } from "./core";
import {
@@ -11,15 +11,18 @@ import {
isTerminalCopyShortcut,
isTerminalLinkPointerGesture,
isTerminalPasteShortcut,
loadTerminalFontFamily,
shouldBlinkTerminalCursor,
shouldReportTerminalMouse,
shouldShowTerminalLinkHover,
terminalGridCellAt,
terminalScrollbarGeometry,
terminalScrollbarOffsetAtPointer,
terminalLinkAtColumn,
terminalLinkAtPosition,
terminalLinkAtPositionWithRange,
terminalContentOriginY,
terminalFontFamily,
fittedTerminalFontSize,
terminalFontSize,
terminalWheelArrowData,
terminalWheelDeltaRows,
@@ -56,6 +59,32 @@ 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,
@@ -99,6 +128,10 @@ 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", () => {
@@ -119,6 +152,13 @@ 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", () => {
@@ -245,9 +285,37 @@ 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);
@@ -274,24 +342,6 @@ describe("terminal font resolution", () => {
expect(terminalFontFamily(" , ")).toBe(DEFAULT_TERMINAL_FONT_FAMILY);
});
it("slides the rendered size down until a full-width grid fits the canvas", () => {
// SF Mono-like advance: 0.6em per cell.
const cellWidthAt = (size: number) => size * 0.6;
// A wide drawer keeps the preference untouched.
expect(fittedTerminalFontSize(cellWidthAt, 20, 1140)).toBe(20);
// A split pane at the same preference shrinks until 80 columns fit.
const fitted = fittedTerminalFontSize(cellWidthAt, 20, 570);
expect(fitted).toBeLessThan(20);
expect(Math.floor((570 - 8) / cellWidthAt(fitted))).toBeGreaterThanOrEqual(80);
// A tiny pane stops at the legibility floor instead of vanishing.
expect(fittedTerminalFontSize(cellWidthAt, 20, 220)).toBe(8);
// A preference below the floor is honored as-is.
expect(fittedTerminalFontSize(cellWidthAt, 6, 220)).toBe(6);
// Unmeasured layouts leave the preference alone.
expect(fittedTerminalFontSize(cellWidthAt, 14, 0)).toBe(14);
expect(fittedTerminalFontSize(() => 0, 14, 600)).toBe(14);
});
it("clamps requested font sizes to the supported range", () => {
expect(terminalFontSize()).toBe(DEFAULT_TERMINAL_FONT_SIZE);
expect(terminalFontSize(Number.NaN)).toBe(DEFAULT_TERMINAL_FONT_SIZE);
+250 -72
View File
@@ -10,6 +10,7 @@ import {
measureGhosttyCell,
renderGhosttySnapshot,
terminalGridSize,
type GhosttyCellRange,
type GhosttyCellMetrics,
} from "./renderer";
import symbolsFontUrl from "./fonts/SymbolsNerdFontMono-Regular.woff2?url";
@@ -35,6 +36,13 @@ const CONTENT_PADDING = 4;
const MIN_SCROLLBAR_THUMB_HEIGHT = 18;
/** Half a blink cycle: the visible and hidden phases are equally long. */
const CURSOR_BLINK_INTERVAL_MS = 500;
const TERMINAL_FONT_LOAD_TEXT = "iMW0@# .";
const TERMINAL_FONT_LOAD_VARIANTS = [
"normal 400",
"normal 700",
"italic 400",
"italic 700",
] as const;
/** Requested terminal font; omitted fields fall back to the defaults. */
export interface GhosttyTerminalFont {
@@ -77,6 +85,13 @@ function quoteTerminalFontFamilies(list: string): string {
.join(", ");
}
function uncheckedTerminalFontFamily(family?: string): string {
const custom = family === undefined ? "" : quoteTerminalFontFamilies(family);
return custom.length === 0
? DEFAULT_TERMINAL_FONT_FAMILY
: `${custom}, ${TERMINAL_GLYPH_FALLBACKS}`;
}
export function terminalFontFamily(family?: string): string {
// Quote non-ident names ("3270 Nerd Font", "M+ 1m"): an unquoted one makes
// the whole canvas font string invalid and the assignment silently no-ops.
@@ -87,43 +102,31 @@ export function terminalFontFamily(family?: string): string {
// it here rather than render a ragged grid with a stranded cursor.
if (!isMonospaceFamily(custom)) return DEFAULT_TERMINAL_FONT_FAMILY;
// A custom face keeps the glyph fallbacks so prompt symbols stay covered.
return `${custom}, ${TERMINAL_GLYPH_FALLBACKS}`;
return uncheckedTerminalFontFamily(custom);
}
/**
* Grids narrower than a classic 80-column terminal wrap command output hard,
* so the rendered font size follows the canvas width: the preference is the
* ceiling, and the size slides down (to a legibility floor) until a full-width
* grid fits. A widening pane slides it back up toward the preference.
*/
const MIN_TERMINAL_FIT_COLUMNS = 80;
const MIN_TERMINAL_FIT_FONT_SIZE = 8;
export function fittedTerminalFontSize(
cellWidthAt: (size: number) => number,
requested: number,
mountWidth: number,
): number {
const available = mountWidth - CONTENT_PADDING * 2;
if (available <= 0) return requested;
const floor = Math.min(requested, MIN_TERMINAL_FIT_FONT_SIZE);
const fits = (cellWidth: number) =>
cellWidth > 0 && Math.floor(available / cellWidth) >= MIN_TERMINAL_FIT_COLUMNS;
let cellWidth = cellWidthAt(requested);
if (cellWidth <= 0 || fits(cellWidth)) return requested;
// The advance scales linearly with size for monospace faces: jump close to
// the fitting size, then settle the remaining rounding one step at a time.
const targetCellWidth = available / MIN_TERMINAL_FIT_COLUMNS;
let size = Math.max(
floor,
Math.min(requested, Math.floor((requested * targetCellWidth) / cellWidth)),
);
while (size > floor) {
cellWidth = cellWidthAt(size);
if (cellWidth <= 0 || fits(cellWidth)) break;
size -= 1;
/** Load every style the renderer can request, then validate the actual face. */
export async function loadTerminalFontFamily(
family: string | undefined,
size: number,
environment?: {
readonly load: (font: string, text: string) => Promise<unknown>;
readonly resolve: (family: string | undefined) => string;
},
): Promise<string> {
const candidate = uncheckedTerminalFontFamily(family);
const load =
environment?.load ?? ((font: string, text: string) => document.fonts.load(font, text));
try {
await Promise.all(
TERMINAL_FONT_LOAD_VARIANTS.map((variant) =>
load(`${variant} ${size}px ${candidate}`, TERMINAL_FONT_LOAD_TEXT),
),
);
} catch {
// The fixed-width fallback stack remains available if a face cannot load.
}
return size;
return (environment?.resolve ?? terminalFontFamily)(family);
}
export function terminalFontSize(size?: number): number {
@@ -205,6 +208,28 @@ 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;
@@ -223,6 +248,27 @@ 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;
@@ -251,7 +297,28 @@ export function terminalLinkAtPosition(
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;
return match.text;
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 null;
@@ -338,6 +405,13 @@ 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:
@@ -407,9 +481,10 @@ export class GhosttyTerminalSurface {
private readonly options: GhosttyTerminalSurfaceOptions;
private metrics: GhosttyCellMetrics;
private fontFamily: string;
private requestedFontFamily: string | undefined;
private fontSize: number;
private requestedFontSize: number;
private fontEpoch = 0;
private pendingFontEpoch: number | null = null;
private readonly resizeObserver: ResizeObserver;
private readonly scrollbarThumb: HTMLDivElement;
private snapshot: GhosttySnapshot | null = null;
@@ -444,6 +519,9 @@ 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;
@@ -470,6 +548,7 @@ export class GhosttyTerminalSurface {
context: CanvasRenderingContext2D,
core: GhosttyTerminalCore,
metrics: GhosttyCellMetrics,
fontFamily: string,
options: GhosttyTerminalSurfaceOptions,
) {
this.mount = mount;
@@ -482,9 +561,9 @@ export class GhosttyTerminalSurface {
this.metrics = metrics;
this.options = options;
this.theme = options.theme;
this.fontFamily = terminalFontFamily(options.font?.family);
this.fontFamily = fontFamily;
this.requestedFontFamily = options.font?.family;
this.fontSize = terminalFontSize(options.font?.size);
this.requestedFontSize = this.fontSize;
this.resizeObserver = new ResizeObserver(() => this.fit());
this.installEvents();
this.watchDevicePixelRatio();
@@ -525,16 +604,20 @@ export class GhosttyTerminalSurface {
const context = canvas.getContext("2d", { alpha: false });
if (!context) throw new Error("Canvas 2D is unavailable");
const fontFamily = terminalFontFamily(options.font?.family);
// An opaque canvas backing store initializes to solid black, and the font
// and WASM loads below leave it on screen for the whole setup window; paint
// the theme background first so the mount never flashes a black box.
context.fillStyle = `rgb(${options.theme.background.r}, ${options.theme.background.g}, ${options.theme.background.b})`;
context.fillRect(0, 0, canvas.width, canvas.height);
const fontSize = terminalFontSize(options.font?.size);
try {
// Cell metrics must come from the faces that will render; measuring before
// the bundled webfonts load would size the grid from a fallback font.
await ensureTerminalSymbolsFont();
await document.fonts.load(`${fontSize}px ${fontFamily}`);
} catch {
// Metrics fall back to whichever faces are already available.
}
const fontFamily = await loadTerminalFontFamily(options.font?.family, fontSize);
const metrics = measureGhosttyCell(context, fontSize, fontFamily);
const grid = terminalGridSize(mount.clientWidth, mount.clientHeight, metrics, CONTENT_PADDING);
const core = await GhosttyTerminalCore.create(
@@ -554,6 +637,7 @@ export class GhosttyTerminalSurface {
context,
core,
metrics,
fontFamily,
options,
);
surface.fit();
@@ -592,19 +676,16 @@ export class GhosttyTerminalSurface {
async setFont(font: GhosttyTerminalFont): Promise<void> {
if (this.disposed) return;
const fontFamily = terminalFontFamily(font.family);
const fontSize = terminalFontSize(font.size);
// The fields only change together with their metrics after the load, and
// the epoch lets the newest overlapping call win regardless of load order.
const epoch = ++this.fontEpoch;
try {
await document.fonts.load(`${fontSize}px ${fontFamily}`);
} catch {
// Metrics fall back to whichever faces are already available.
}
this.pendingFontEpoch = epoch;
const fontFamily = await loadTerminalFontFamily(font.family, fontSize);
if (this.disposed || epoch !== this.fontEpoch) return;
this.pendingFontEpoch = null;
this.fontFamily = fontFamily;
this.requestedFontSize = fontSize;
this.requestedFontFamily = font.family;
this.fontSize = fontSize;
this.applyFontMetrics();
}
@@ -631,6 +712,17 @@ export class GhosttyTerminalSurface {
private readonly onFontsLoaded = () => {
if (this.disposed) return;
// The explicit load validates every style and applies the newest request.
// Its own loading events must not revalidate the previously applied face.
if (this.pendingFontEpoch !== null) return;
// A face may become available after an earlier fallback measurement. Run
// the fixed-width guard again before using its newly loaded metrics.
const fontFamily = terminalFontFamily(this.requestedFontFamily);
if (fontFamily !== this.fontFamily) {
this.fontFamily = fontFamily;
this.applyFontMetrics();
return;
}
// A face that finished loading after the initial measurement changes glyph
// advances; re-measure and refit so the grid matches what actually renders.
const metrics = measureGhosttyCell(this.context, this.fontSize, this.fontFamily);
@@ -649,22 +741,6 @@ export class GhosttyTerminalSurface {
const width = this.mount.clientWidth;
const height = this.mount.clientHeight;
if (width <= 0 || height <= 0) return false;
const fitted = fittedTerminalFontSize(
(size) => measureGhosttyCell(this.context, size, this.fontFamily).width,
this.requestedFontSize,
width,
);
if (fitted !== this.fontSize) {
this.fontSize = fitted;
this.metrics = measureGhosttyCell(this.context, this.fontSize, this.fontFamily);
// The grid-change branch below resizes the core, but only when the
// column count moved; the cell geometry always did, so sync it here.
this.core.resize(this.cols, this.rows, this.metrics.width, this.metrics.height);
this.inputLeft = -1;
this.inputTop = -1;
this.forceFullRender = true;
this.scrollbarDirty = true;
}
const ratio = window.devicePixelRatio || 1;
const pixelWidth = Math.max(1, Math.round(width * ratio));
const pixelHeight = Math.max(1, Math.round(height * ratio));
@@ -815,6 +891,7 @@ 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
@@ -866,6 +943,7 @@ 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;
@@ -887,6 +965,8 @@ 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
@@ -968,6 +1048,7 @@ 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);
@@ -982,6 +1063,7 @@ 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(
@@ -1029,6 +1111,11 @@ 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;
@@ -1037,6 +1124,7 @@ export class GhosttyTerminalSurface {
this.updateHoverCursor(event);
return;
}
this.clearHoveredLink();
this.selectionPointer = { x: event.clientX, y: event.clientY };
const bounds = this.canvas.getBoundingClientRect();
this.setSelectionAutoscroll(
@@ -1097,10 +1185,50 @@ export class GhosttyTerminalSurface {
}
private updateHoverCursor(event: PointerEvent): void {
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;
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();
}
private readonly onPointerUp = (event: PointerEvent) => {
@@ -1114,7 +1242,7 @@ export class GhosttyTerminalSurface {
}
if (event.type !== "pointercancel") {
const link = this.linkAt(event.clientX, event.clientY);
if (link) this.options.onLinkActivate(link, event);
if (link) this.options.onLinkActivate(link.text, event);
}
return;
}
@@ -1127,6 +1255,13 @@ 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)) {
@@ -1253,6 +1388,7 @@ 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 });
@@ -1276,6 +1412,7 @@ 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);
@@ -1378,6 +1515,7 @@ export class GhosttyTerminalSurface {
this.originY = nextOriginY;
this.forceFullRender = true;
}
this.refreshHoveredLink();
renderGhosttySnapshot({
context: this.context,
snapshot: this.snapshot,
@@ -1390,6 +1528,7 @@ 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 }
: {}),
@@ -1466,12 +1605,51 @@ export class GhosttyTerminalSurface {
};
}
private linkAt(clientX: number, clientY: number): string | null {
private linkAt(clientX: number, clientY: number): TerminalLinkWithRange | null {
if (!this.snapshot) return null;
const cell = this.cellAt(clientX, clientY);
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 explicitHyperlink = this.core.hyperlinkAt(cell.x, cell.y);
if (explicitHyperlink) return explicitHyperlink;
return terminalLinkAtPosition(this.snapshot.rowData, cell.y, cell.x);
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);
}
private sendMouse(
+4 -3
View File
@@ -34,14 +34,15 @@ This document covers the unified release workflow for stable and nightly desktop
## Required release credentials
The release workflow requires these GitHub Actions secrets in addition to the platform and deployment
Stable releases require these GitHub Actions secrets in addition to the platform and deployment
credentials documented below:
- `RELEASE_APP_ID`
- `RELEASE_APP_PRIVATE_KEY`
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`.
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.
## T3 Connect relay deployment
-79
View File
@@ -1,79 +0,0 @@
# Deploy a Cloud Environment on Render
This experimental setup runs one T3 Code environment as a Render web service. The environment owns
the provider processes, repositories, worktrees, terminals, and T3 Code state. The web, desktop, and
mobile clients connect to it over Render's public HTTPS and WebSocket endpoint.
This is an ephemeral, one-session demo environment, not a multi-tenant hosted service. The Free
instance can run multiple agent threads, but loses its files and authentication when it restarts or
spins down.
## What the Blueprint Creates
The root [`render.yaml`](../../render.yaml) creates:
- a Docker web service containing T3 Code, Codex, Claude Code, Git, and the GitHub CLI;
- an ephemeral `/data` workspace for T3 Code state, provider credentials, and repositories;
- an optional `OPENAI_API_KEY` secret prompt for automatic Codex authentication;
- in-app pairing directly from the service URL;
- a health check against T3 Code's public environment descriptor.
## Deploy
1. Open **Settings → Cloud environments** in T3 Code.
2. Choose an authentication method, then select **Deploy on Render**:
- **OpenAI API key:** enter `OPENAI_API_KEY` in Render's secret prompt. Startup authenticates
Codex automatically.
- **ChatGPT subscription:** skip the optional API key, then use device login after cloning.
3. Deploy the Blueprint and wait for the service health check to pass.
4. Copy the service's `.onrender.com` URL, return to T3 Code, paste it under **Connect in T3
Code**, and select **Connect environment**. T3 Code wakes the service and requests a one-time
pairing credential; there is no log-copying step.
5. Select **Add project** and choose **Cloud environments → Render cloud
environment**. Paste a public GitHub URL. T3 Code clones it directly into the Render workspace;
there is no local destination picker.
6. API-key deployments are ready immediately. For subscription authentication, open the project
terminal, run `codex login --device-auth`, complete the device login, and start an agent.
Repositories are selected after pairing rather than baked into the Blueprint. Each clone is stored
under `/data/workspace` for the current Free-instance session.
The Render service advertises cloud metadata in its normal T3 environment descriptor. That is what
lets clients present it as a cloud device and automatically route project cloning to its cloud
workspace while leaving the existing local-device folder flow unchanged.
The demo Blueprint is pinned to `feat/render-cloud-environment` so it can deploy before the draft
pull request is merged. Update the `branch` field in `render.yaml` if you rename or reuse the branch.
## Provider Authentication
For API-key authentication, the Blueprint declares `OPENAI_API_KEY` with `sync: false`. Render asks
for it during the initial deployment and stores it as a secret; the value is never committed to the
repository. The startup script pipes it to `codex login --with-api-key` and removes it from the
server process environment afterward.
For ChatGPT subscription authentication, clone a public project, open its T3 Code terminal, and run:
```sh
codex login --device-auth
```
Follow the printed link and enter the device code. The login lasts for the current Free-instance
session and is lost if Render restarts or spins down the service.
## T3 Connect
T3 Connect is not required for this deployment. Render already gives the environment a public HTTPS
and WebSocket endpoint, so the in-app setup registers it as a direct remote environment. Use its
existing Connect and Disconnect controls under **Settings → Cloud environments**. T3 Connect remains
useful for machines that need its managed tunnel or account-level environment discovery.
## Operations
- Anyone with the service URL can request a standard T3 Code pairing credential. Use this setup only
for a private demo and remove the Render service afterward. Existing paired browser sessions remain
authenticated until the ephemeral service restarts.
- Render spins a Free web service down after 15 minutes without inbound HTTP or WebSocket traffic.
A later request starts a fresh instance, so pair, clone, and authenticate again.
- Do not use this Blueprint for untrusted users or repositories. Coding agents can execute commands
and access every secret available to the service.
-40
View File
@@ -1,40 +0,0 @@
FROM node:24.19.0-bookworm-slim
ARG VP_VERSION=0.2.2
ARG CODEX_VERSION=0.146.0
ARG CLAUDE_CODE_VERSION=2.1.220
ENV CI=1 \
VP_NODE_MANAGER=no \
PATH="/root/.vite-plus/bin:${PATH}"
RUN apt-get update \
&& apt-get install --yes --no-install-recommends \
build-essential \
ca-certificates \
curl \
gh \
git \
openssh-client \
python3 \
&& rm -rf /var/lib/apt/lists/*
WORKDIR /app
COPY . .
RUN curl -fsSL https://vite.plus | bash \
&& vp install --frozen-lockfile \
&& vp run --filter t3 build \
&& npm install --global \
"@anthropic-ai/claude-code@${CLAUDE_CODE_VERSION}" \
"@openai/codex@${CODEX_VERSION}"
ENV T3CODE_HOME=/data/t3 \
T3CODE_WORKSPACE_DIR=/data/workspace \
CODEX_HOME=/data/codex \
CLAUDE_CONFIG_DIR=/data/claude
EXPOSE 10000
ENTRYPOINT ["/app/infra/render/start.sh"]
-37
View File
@@ -1,37 +0,0 @@
#!/bin/sh
set -eu
script_dir="$(CDPATH= cd -- "$(dirname -- "$0")" && pwd)"
app_root="$(CDPATH= cd -- "$script_dir/../.." && pwd)"
t3_entry="$app_root/apps/server/dist/bin.mjs"
port="${PORT:-10000}"
t3_home="${T3CODE_HOME:-/data/t3}"
workspace_dir="${T3CODE_WORKSPACE_DIR:-/data/workspace}"
codex_home="${CODEX_HOME:-/data/codex}"
claude_config_dir="${CLAUDE_CONFIG_DIR:-/data/claude}"
export CODEX_HOME="$codex_home"
export CLAUDE_CONFIG_DIR="$claude_config_dir"
export T3CODE_CLOUD_PROVIDER="${T3CODE_CLOUD_PROVIDER:-render}"
export T3CODE_ENVIRONMENT_LABEL="${T3CODE_ENVIRONMENT_LABEL:-Render cloud environment}"
export T3CODE_WORKSPACE_DIR="$workspace_dir"
mkdir -p "$t3_home" "$workspace_dir" "$codex_home" "$claude_config_dir"
if [ -n "${OPENAI_API_KEY:-}" ]; then
printf '%s\n' "$OPENAI_API_KEY" | codex login --with-api-key
unset OPENAI_API_KEY
fi
if [ -n "${GH_TOKEN:-}" ]; then
gh auth setup-git
fi
cd "$workspace_dir"
exec node "$t3_entry" start \
--host 0.0.0.0 \
--port "$port" \
--base-dir "$t3_home" \
--no-browser
@@ -0,0 +1,194 @@
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,5 +1,9 @@
import { scopedProjectKey, scopeProjectRef } from "../environment/scoped.ts";
import type { ScopedProjectRef, SidebarProjectGroupingMode } from "@t3tools/contracts";
import type {
EnvironmentId,
ScopedProjectRef,
SidebarProjectGroupingMode,
} from "@t3tools/contracts";
import type { ClientSettings } from "@t3tools/contracts/settings";
import type { EnvironmentProject } from "./models.ts";
@@ -181,3 +185,141 @@ 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,12 +7,16 @@ import {
} from "@t3tools/contracts";
import { describe, expect, it } from "@effect/vitest";
import * as Cause from "effect/Cause";
import * as Duration from "effect/Duration";
import * as Effect from "effect/Effect";
import * as Exit from "effect/Exit";
import * as Fiber from "effect/Fiber";
import * as Option from "effect/Option";
import * as Queue from "effect/Queue";
import * as Ref from "effect/Ref";
import * as Stream from "effect/Stream";
import * as SubscriptionRef from "effect/SubscriptionRef";
import * as TestClock from "effect/testing/TestClock";
import { RpcClientError } from "effect/unstable/rpc";
import * as Socket from "effect/unstable/socket/Socket";
@@ -30,6 +34,7 @@ import {
makeEnvironmentServerConfigState,
isLegacyUpdateHandoffLoss,
matchesServerUpdateReadyEvent,
nudgeReconnectDuringUpdateRestart,
projectServerWelcome,
resolveServerConfigValue,
resolveServerUpdateProgressResult,
@@ -71,6 +76,56 @@ function session(client: WsRpcProtocolClient): RpcSession {
};
}
describe("update restart reconnect nudges", () => {
it.effect("retries once per backoff entry instead of only the first", () =>
Effect.gen(function* () {
const retries = yield* Ref.make(0);
const states = [
{ phase: "backoff" },
{ phase: "connecting" },
{ phase: "backoff" },
{ phase: "backoff" },
];
yield* nudgeReconnectDuringUpdateRestart({
stateChanges: Stream.fromIterable(states),
retryNow: Ref.update(retries, (count) => count + 1),
interval: Duration.zero,
});
// Three backoff entries, three nudges. The old one-shot behavior fired
// once and then let the supervisor's ladder stretch to 16-second gaps.
expect(yield* Ref.get(retries)).toBe(3);
}),
);
it.effect("paces nudges so a fast-failing connection cannot spin", () =>
Effect.gen(function* () {
const retries = yield* Ref.make(0);
const fiber = yield* Effect.forkChild(
nudgeReconnectDuringUpdateRestart({
stateChanges: Stream.fromIterable([{ phase: "backoff" }, { phase: "backoff" }]),
retryNow: Ref.update(retries, (count) => count + 1),
}),
{ startImmediately: true },
);
// Each nudge waits out the interval first, so nothing fires immediately.
yield* TestClock.adjust(Duration.millis(999));
expect(yield* Ref.get(retries)).toBe(0);
yield* TestClock.adjust(Duration.millis(1));
expect(yield* Ref.get(retries)).toBe(1);
yield* TestClock.adjust(Duration.seconds(1));
expect(yield* Ref.get(retries)).toBe(2);
yield* Fiber.join(fiber);
}).pipe(Effect.provide(TestClock.layer())),
);
});
describe("server state projection", () => {
it("only treats a legacy transport interruption as an unacknowledged handoff", () => {
expect(isLegacyUpdateHandoffLoss(Cause.interrupt(1))).toBe(true);
+36 -12
View File
@@ -149,6 +149,35 @@ export function validateServerUpdateReadyEvent(
);
}
/**
* Keeps reconnect attempts ~1s apart for the whole update restart.
*
* A restart takes the server down for ~15 seconds, but the supervisor's normal
* backoff ladder (1/2/4/8/16s) assumes an unexpected failure and lands attempts
* at ~3, 5, 9, 17 and 33 seconds — so a 15-second restart is observed as a
* 33-second "Resuming". Nudging on every backoff entry (not just the first)
* holds the retry cadence flat until the server answers again. The sleep before
* each nudge is the pacer: a connection that fails instantly re-enters backoff
* immediately and would otherwise spin a tight retry loop.
*
* Callers fork this as a child of the update command so it is interrupted as
* soon as the update settles, whether it succeeds, fails, or times out.
*/
export function nudgeReconnectDuringUpdateRestart(input: {
readonly stateChanges: Stream.Stream<{ readonly phase: string }, unknown>;
readonly retryNow: Effect.Effect<void>;
readonly interval?: Duration.Duration;
}): Effect.Effect<void> {
return input.stateChanges.pipe(
Stream.filter((state) => state.phase === "backoff"),
Stream.runForEach(() =>
Effect.sleep(input.interval ?? Duration.seconds(1)).pipe(Effect.andThen(input.retryNow)),
),
Effect.timeoutOption(SERVER_UPDATE_RESUME_TIMEOUT),
Effect.ignore,
);
}
export function serverUpdateStateForProgressEvent(
fromVersion: string,
targetVersion: string,
@@ -589,18 +618,13 @@ export function createServerEnvironmentAtoms<R, E>(
}),
);
// The update restart is intentional. As soon as the supervisor sees
// that first failed connection, discard any prior backoff debt and
// retry immediately instead of carrying an old 16-second delay.
yield* environmentRegistry.stateChanges(target.environmentId).pipe(
Stream.filter((state) => state.phase === "backoff"),
Stream.take(1),
Stream.runDrain,
Effect.andThen(environmentRegistry.retryNow(target.environmentId)),
Effect.timeoutOption(Duration.seconds(30)),
Effect.ignore,
Effect.forkChild,
);
// The update restart is intentional and the server stays unreachable
// for the whole restart, so hold the retry cadence flat instead of
// letting the supervisor climb its backoff ladder.
yield* nudgeReconnectDuringUpdateRestart({
stateChanges: environmentRegistry.stateChanges(target.environmentId),
retryNow: environmentRegistry.retryNow(target.environmentId),
}).pipe(Effect.forkChild);
const resumed = yield* environmentRegistry
.followStream(target.environmentId, subscribe(WS_METHODS.subscribeServerLifecycle, {}))
@@ -23,6 +23,19 @@ 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].toSorted((left, right) => left.localeCompare(right)),
[...environmentIds].sort((left, right) => left.localeCompare(right)),
query,
]);
}
-11
View File
@@ -20,16 +20,6 @@ export const ExecutionEnvironmentPlatform = Schema.Struct({
});
export type ExecutionEnvironmentPlatform = typeof ExecutionEnvironmentPlatform.Type;
export const ExecutionEnvironmentCloudProvider = Schema.Literals(["render"]);
export type ExecutionEnvironmentCloudProvider = typeof ExecutionEnvironmentCloudProvider.Type;
/** Metadata advertised by a backend whose workspace is hosted by a cloud provider. */
export const ExecutionEnvironmentCloud = Schema.Struct({
provider: ExecutionEnvironmentCloudProvider,
workspaceRoot: TrimmedNonEmptyString,
});
export type ExecutionEnvironmentCloud = typeof ExecutionEnvironmentCloud.Type;
/** How a server can replace itself with another version when asked over RPC.
New servers only advertise the stable launcher-backed "boot-service" path;
"respawn" remains decodable for compatibility with older servers. */
@@ -77,7 +67,6 @@ export const ExecutionEnvironmentDescriptor = Schema.Struct({
environmentId: EnvironmentId,
label: TrimmedNonEmptyString,
platform: ExecutionEnvironmentPlatform,
cloud: Schema.optionalKey(ExecutionEnvironmentCloud),
serverVersion: TrimmedNonEmptyString,
capabilities: ExecutionEnvironmentCapabilities,
});
-20
View File
@@ -371,25 +371,6 @@ export const AuthOtherClientSessionsRevokeResult = Schema.Struct({
});
export type AuthOtherClientSessionsRevokeResult = typeof AuthOtherClientSessionsRevokeResult.Type;
export const EnvironmentRenderBootstrapPairingResult = Schema.Struct({
pairingCode: TrimmedNonEmptyString,
label: TrimmedNonEmptyString,
});
export type EnvironmentRenderBootstrapPairingResult =
typeof EnvironmentRenderBootstrapPairingResult.Type;
const EnvironmentRenderBootstrapErrors = [
EnvironmentHttpForbiddenError,
EnvironmentHttpInternalServerError,
] as const;
export class EnvironmentRenderBootstrapHttpApi extends HttpApiGroup.make("renderBootstrap").add(
HttpApiEndpoint.post("pair", "/.well-known/t3/render/pair", {
success: EnvironmentRenderBootstrapPairingResult,
error: EnvironmentRenderBootstrapErrors,
}),
) {}
export class EnvironmentMetadataHttpApi extends HttpApiGroup.make("metadata").add(
HttpApiEndpoint.get("descriptor", "/.well-known/t3/environment", {
success: ExecutionEnvironmentDescriptor,
@@ -570,7 +551,6 @@ export class EnvironmentConnectHttpApi extends HttpApiGroup.make("connect")
) {}
export class EnvironmentHttpApi extends HttpApi.make("environment")
.add(EnvironmentRenderBootstrapHttpApi)
.add(EnvironmentMetadataHttpApi)
.add(EnvironmentAuthHttpApi)
.add(EnvironmentOrchestrationHttpApi)
+6 -11
View File
@@ -12,13 +12,10 @@ import {
import { ProviderInstanceId } from "./providerInstance.ts";
const BoundedUrl = Schema.String.check(Schema.isTrimmed())
.check(
Schema.isNonEmpty({
description:
"Absolute http(s) URL or a schemeless host such as t3.chat or localhost:5173. Schemeless public hosts use https; loopback hosts use http.",
}),
)
.check(Schema.isNonEmpty())
.check(Schema.isMaxLength(2048));
const URL_GUIDANCE =
"Absolute http(s) URL or a schemeless host such as t3.chat or localhost:5173. Schemeless public hosts use https; loopback hosts use http.";
const OptionalTimeoutMs = Schema.optional(
Schema.Int.check(Schema.isGreaterThan(0))
.check(Schema.isLessThanOrEqualTo(60_000))
@@ -83,8 +80,7 @@ export type PreviewAutomationStatus = typeof PreviewAutomationStatus.Type;
export const PreviewAutomationOpenInput = Schema.Struct({
...PreviewAutomationTabTargetFields,
url: Schema.optional(BoundedUrl).annotate({
description:
"Optional initial page URL, for example https://t3.chat or localhost:5173. Omit to open a blank tab.",
description: `Optional initial page URL. ${URL_GUIDANCE} Omit to open a blank tab.`,
}),
open: Schema.optional(
Schema.Boolean.annotate({
@@ -124,7 +120,7 @@ export const BrowserNavigationTarget = Schema.Union([
description: "Selects direct URL navigation.",
}),
url: BoundedUrl.annotate({
description: "Direct website URL.",
description: `Direct website URL. ${URL_GUIDANCE}`,
}),
}),
Schema.Struct({
@@ -151,8 +147,7 @@ export type BrowserNavigationTarget = typeof BrowserNavigationTarget.Type;
export const PreviewAutomationNavigateInput = Schema.Struct({
...PreviewAutomationTabTargetFields,
url: Schema.optional(BoundedUrl).annotate({
description:
"Website URL, for example https://t3.chat. Use this for public pages and directly reachable URLs.",
description: `Website URL. ${URL_GUIDANCE} Use this for public pages and directly reachable URLs.`,
}),
target: Schema.optional(
BrowserNavigationTarget.annotate({
-20
View File
@@ -1,20 +0,0 @@
services:
- type: web
name: t3code-cloud-demo
runtime: docker
plan: free
repo: https://github.com/pingdotgg/t3code.git
branch: feat/render-cloud-environment
autoDeployTrigger: off
dockerfilePath: ./infra/render/Dockerfile
dockerContext: .
healthCheckPath: /.well-known/t3/environment
envVars:
- key: T3CODE_CLOUD_PROVIDER
value: render
- key: T3CODE_ENVIRONMENT_LABEL
value: Render cloud environment
- key: T3CODE_WORKSPACE_DIR
value: /data/workspace
- key: OPENAI_API_KEY
sync: false
+17 -7
View File
@@ -44,17 +44,27 @@ const PROJECT_SCRIPTS = JSON.stringify([
},
]);
const SHOWCASE_TERMINAL_PROMPT =
"\u001b[1;32m→\u001b[0m \u001b[1;36mt3code\u001b[0m \u001b[1;34mgit:(\u001b[1;31mfeat/remote-command-center\u001b[1;34m)\u001b[0m \u001b[1;33m✗\u001b[0m ";
// A dev-server startup mirroring the web settings' terminal font preview:
// zsh-style prompt, brand line, addresses, the thread's 612-test summary,
// and a READY badge, so the scene exercises bold, dim, underline, the six
// accent colors, and a background cell.
export const SHOWCASE_TERMINAL_BUFFER = [
"\u001b[38;5;75m~/Code/t3code\u001b[0m \u001b[38;5;212mfeat/remote-command-center\u001b[0m",
"$ vp test run --changed",
`${SHOWCASE_TERMINAL_PROMPT}vpr dev`,
"",
" \u001b[38;5;117mt3code-mobile\u001b[0m 184 passed",
" \u001b[38;5;213mclient-runtime\u001b[0m 263 passed",
" \u001b[38;5;221mserver\u001b[0m 165 passed",
" \u001b[1;32mVITE\u001b[0m \u001b[32mv7.1.1\u001b[0m \u001b[2mready in\u001b[0m \u001b[1m1.24s\u001b[0m",
"",
"\u001b[32m✨ 612 tests passed\u001b[0m · 3 environments online",
" \u001b[32m→\u001b[0m \u001b[2mLocal:\u001b[0m \u001b[4;36mhttp://127.0.0.1:5173/\u001b[0m",
" \u001b[32m→\u001b[0m \u001b[2mNetwork:\u001b[0m \u001b[4;36mhttp://192.168.1.24:5173/\u001b[0m",
" \u001b[32m→\u001b[0m \u001b[2mProject:\u001b[0m \u001b[1mt3code\u001b[0m \u001b[2m— ~/Code/t3code\u001b[0m",
"",
"\u001b[38;5;75m~/Code/t3code\u001b[0m \u001b[38;5;212mfeat/remote-command-center\u001b[0m $ ",
" \u001b[32m✓ 612 passed\u001b[0m \u001b[33m△ 2 warnings\u001b[0m \u001b[31m✗ 0 failed\u001b[0m",
"",
" \u001b[42;30m READY \u001b[0m \u001b[2mwatching for changes — press\u001b[0m \u001b[1mq\u001b[0m \u001b[2mto quit\u001b[0m",
"",
SHOWCASE_TERMINAL_PROMPT,
].join("\r\n");
const BASE_ENVIRONMENT_PRESENCE = `export function environmentLabel(count: number): string {