Compare commits

..
Author SHA1 Message Date
Julius Marminge 4a42ee1ad0 fix(vcs): preserve branch PR state across checkout changes
- Reconcile VCS refreshes after mid-refresh checkouts
- Use branch-keyed PR lookups for thread indicators
- Keep git actions tied to the active checkout
2026-08-05 16:17:58 +02:00
Julius Marminge c7b1e2e6c4 feat(vcs): preserve branch PR status across checkouts
- Add branch-keyed PR lookup RPC and client query
- Serialize VCS refreshes to prevent stale status races
2026-08-05 15:18:06 +02: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
89 changed files with 1992 additions and 2156 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>
);
}
@@ -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>
@@ -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;
}
+21 -5
View File
@@ -15,6 +15,10 @@ export {
* (environmentId, cwd) by the atom family, so many rows on the same worktree
* or project root share one stream — and virtualization means only visible
* rows subscribe at all.
*
* Keyed by the thread's recorded branch, not the current checkout: the
* streamed status is the fast path while the checkout matches, and a
* branch-keyed lookup keeps the badge alive once the checkout moves away.
*/
export function useThreadPr(
thread: EnvironmentThreadShell,
@@ -29,13 +33,25 @@ export function useThreadPr(
})
: null,
);
const branchPr = useEnvironmentQuery(
thread.branch !== null && cwd !== null
? vcsEnvironment.branchPr({
environmentId: thread.environmentId,
input: { cwd, branch: thread.branch },
})
: null,
);
const status = gitStatus.data;
if (status === null || thread.branch === null || status.refName !== thread.branch) {
// When the status describes the thread's own branch it is authoritative
// about that branch's PR — including when it reports none, so this must not
// fall through to a warm branch lookup that would resurrect a stale badge.
if (status !== null && thread.branch !== null && status.refName === thread.branch) {
return status.pr ? presentThreadPr(status.pr, status.sourceControlProvider) : null;
}
const pr = branchPr.data?.pr;
if (!pr) {
return null;
}
if (!status.pr) {
return null;
}
return presentThreadPr(status.pr, status.sourceControlProvider);
return presentThreadPr(pr, status?.sourceControlProvider);
}
+1
View File
@@ -64,6 +64,7 @@ export const RPC_REQUIRED_SCOPES = {
[WS_METHODS.subscribeVcsStatus]: AuthOrchestrationReadScope,
[WS_METHODS.subscribeResourceTelemetry]: AuthOrchestrationReadScope,
[WS_METHODS.vcsRefreshStatus]: AuthOrchestrationReadScope,
[WS_METHODS.vcsBranchPr]: AuthOrchestrationReadScope,
[WS_METHODS.vcsPull]: AuthOrchestrationOperateScope,
[WS_METHODS.gitRunStackedAction]: AuthOrchestrationOperateScope,
[WS_METHODS.gitResolvePullRequest]: AuthOrchestrationOperateScope,
@@ -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,
+43
View File
@@ -23,6 +23,8 @@ import {
GitRunStackedActionInput,
GitRunStackedActionResult,
GitStackedAction,
type VcsBranchPrInput,
type VcsBranchPrResult,
VcsStatusInput,
type VcsStatusLocalResult,
type VcsStatusRemoteResult,
@@ -87,6 +89,9 @@ export class GitManager extends Context.Service<
input: VcsStatusInput,
options?: GitVcsDriver.GitRemoteStatusOptions,
) => Effect.Effect<VcsStatusRemoteResult | null, GitManagerServiceError>;
readonly branchPr: (
input: VcsBranchPrInput,
) => Effect.Effect<VcsBranchPrResult, GitManagerServiceError>;
readonly invalidateLocalStatus: (cwd: string) => Effect.Effect<void, never>;
readonly invalidateRemoteStatus: (cwd: string) => Effect.Effect<void, never>;
readonly invalidateStatus: (cwd: string) => Effect.Effect<void, never>;
@@ -1684,6 +1689,43 @@ export const make = Effect.gen(function* () {
});
return mergeGitStatusParts(local, remote);
});
// PR lookup for a branch that is not necessarily checked out. Threads keep
// a recorded branch, and their PR badge must survive the checkout moving
// elsewhere — so this derives the branch's upstream from git config instead
// of HEAD and funnels into the same cached lookup as status.
const branchPr: GitManager["Service"]["branchPr"] = Effect.fn("branchPr")(function* (input) {
const cwd = yield* normalizeStatusCacheKey(input.cwd);
const branch = input.branch;
const [remoteName, mergeRef, originHead] = yield* Effect.all(
[
readConfigValueNullable(cwd, `branch.${branch}.remote`),
readConfigValueNullable(cwd, `branch.${branch}.merge`),
gitCore
.execute({
operation: "GitManager.branchPr.defaultBranch",
cwd,
args: ["symbolic-ref", "--short", "refs/remotes/origin/HEAD"],
allowNonZeroExit: true,
})
.pipe(Effect.orElseSucceed(() => null)),
],
{ concurrency: "unbounded" },
);
const upstreamRef =
remoteName !== null && mergeRef !== null && mergeRef.startsWith("refs/heads/")
? `${remoteName}/${mergeRef.slice("refs/heads/".length)}`
: null;
const originHeadBranch =
originHead !== null && originHead.exitCode === 0
? (originHead.stdout.trim().split("/").slice(1).join("/") ?? "")
: "";
const isDefaultBranch =
originHeadBranch.length > 0
? branch === originHeadBranch
: branch === "main" || branch === "master";
const pr = yield* lookupStatusPr(cwd, { branch, upstreamRef, isDefaultBranch });
return { branch, pr } satisfies VcsBranchPrResult;
});
const invalidateLocalStatus: GitManager["Service"]["invalidateLocalStatus"] = Effect.fn(
"invalidateLocalStatus",
)(function* (cwd) {
@@ -2136,6 +2178,7 @@ export const make = Effect.gen(function* () {
return GitManager.of({
localStatus,
remoteStatus,
branchPr,
status,
invalidateLocalStatus,
invalidateRemoteStatus,
+13
View File
@@ -22,6 +22,8 @@ import {
type GitResolvePullRequestResult,
type GitRunStackedActionInput,
type GitRunStackedActionResult,
type VcsBranchPrInput,
type VcsBranchPrResult,
type VcsStatusInput,
type VcsStatusLocalResult,
type VcsStatusRemoteResult,
@@ -45,6 +47,9 @@ export class GitWorkflowService extends Context.Service<
input: VcsStatusInput,
options?: GitVcsDriver.GitRemoteStatusOptions,
) => Effect.Effect<VcsStatusRemoteResult | null, GitManagerServiceError>;
readonly branchPr: (
input: VcsBranchPrInput,
) => Effect.Effect<VcsBranchPrResult, GitManagerServiceError>;
readonly invalidateLocalStatus: (cwd: string) => Effect.Effect<void, never>;
readonly invalidateRemoteStatus: (cwd: string) => Effect.Effect<void, never>;
readonly invalidateStatus: (cwd: string) => Effect.Effect<void, never>;
@@ -270,6 +275,14 @@ export const make = Effect.gen(function* () {
isGitRepository ? gitManager.remoteStatus(input, options) : Effect.succeed(null),
),
),
branchPr: (input) =>
detectGitRepositoryForStatus("GitWorkflowService.branchPr", input.cwd).pipe(
Effect.flatMap((isGitRepository) =>
isGitRepository
? gitManager.branchPr(input)
: Effect.succeed({ branch: input.branch, pr: null }),
),
),
invalidateLocalStatus: gitManager.invalidateLocalStatus,
invalidateRemoteStatus: gitManager.invalidateRemoteStatus,
invalidateStatus: gitManager.invalidateStatus,
@@ -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 = {
-2
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),
@@ -6,6 +6,7 @@ import * as DateTime from "effect/DateTime";
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 FileSystem from "effect/FileSystem";
import * as Layer from "effect/Layer";
import * as Logger from "effect/Logger";
@@ -208,7 +209,7 @@ describe("VcsStatusBroadcaster", () => {
}).pipe(Effect.provide(makeTestLayer(state)));
});
it.effect("keeps the cached snapshot unchanged when a refresh branch fails", () => {
it.effect("keeps local progress and recovers the remote half after a failed refresh", () => {
const state = {
currentLocalStatus: baseLocalStatus,
currentRemoteStatus: baseRemoteStatus,
@@ -273,14 +274,139 @@ describe("VcsStatusBroadcaster", () => {
state.failRemoteStatus = true;
const refreshExit = yield* broadcaster.refreshStatus("/repo").pipe(Effect.exit);
const cached = yield* broadcaster.getStatus({ cwd: "/repo" });
assert.isTrue(Exit.isFailure(refreshExit));
assert.deepStrictEqual(cached, baseStatus);
// The local half landed even though the refresh failed. The remote half
// was computed for the previous checkout, so the refName change dropped
// it rather than pairing the old branch's data with the new branch; it
// repopulates on the next successful read.
state.failRemoteStatus = false;
const cached = yield* broadcaster.getStatus({ cwd: "/repo" });
assert.deepStrictEqual(cached, {
...state.currentLocalStatus,
...state.currentRemoteStatus,
});
}).pipe(Effect.provide(testLayer));
});
it.effect("refreshes only the cached local snapshot when requested", () => {
it.effect("returns the new checkout when one lands mid-refresh", () => {
const state = {
currentLocalStatus: baseLocalStatus,
currentRemoteStatus: baseRemoteStatus,
localStatusCalls: 0,
remoteStatusCalls: 0,
localInvalidationCalls: 0,
remoteInvalidationCalls: 0,
};
return Effect.gen(function* () {
const remoteEntered = yield* Deferred.make<void>();
const releaseRemote = yield* Deferred.make<void>();
// Armed only around the refresh under test, so neither the priming read
// nor the follow-up refresh that the checkout change kicks off blocks.
const gate = { armed: false };
const testLayer = VcsStatusBroadcaster.layer.pipe(
Layer.provideMerge(NodeServices.layer),
Layer.provide(makeBackgroundPolicyLayer(() => true)),
Layer.provide(
Layer.mock(GitWorkflowService.GitWorkflowService)({
localStatus: () =>
Effect.sync(() => {
state.localStatusCalls += 1;
return state.currentLocalStatus;
}),
remoteStatus: () =>
Effect.suspend(() => {
state.remoteStatusCalls += 1;
if (!gate.armed) {
return Effect.succeed(state.currentRemoteStatus);
}
gate.armed = false;
return Deferred.succeed(remoteEntered, undefined).pipe(
Effect.andThen(Deferred.await(releaseRemote)),
Effect.as(state.currentRemoteStatus),
);
}),
invalidateLocalStatus: () =>
Effect.sync(() => {
state.localInvalidationCalls += 1;
}),
invalidateRemoteStatus: () =>
Effect.sync(() => {
state.remoteInvalidationCalls += 1;
}),
invalidateStatus: () =>
Effect.sync(() => {
state.localInvalidationCalls += 1;
state.remoteInvalidationCalls += 1;
}),
}),
),
);
return yield* Effect.gen(function* () {
const broadcaster = yield* VcsStatusBroadcaster.VcsStatusBroadcaster;
yield* broadcaster.getStatus({ cwd: "/repo" });
gate.armed = true;
const refreshFiber = yield* Effect.forkChild(broadcaster.refreshStatus("/repo"), {
startImmediately: true,
});
yield* Deferred.await(remoteEntered);
// A checkout lands while the slow remote read is still in flight.
state.currentLocalStatus = {
...baseLocalStatus,
refName: "feature/checked-out-mid-refresh",
};
yield* broadcaster.refreshLocalStatus("/repo");
yield* Deferred.succeed(releaseRemote, undefined);
const refreshed = yield* Fiber.join(refreshFiber);
// The refresh must not hand back the branch that was checked out when
// it started; its own remote result was discarded as superseded.
assert.equal(refreshed.refName, "feature/checked-out-mid-refresh");
}).pipe(Effect.provide(testLayer));
});
});
it.effect("refreshes only the cached local snapshot when the checkout is unchanged", () => {
const state = {
currentLocalStatus: baseLocalStatus,
currentRemoteStatus: baseRemoteStatus,
localStatusCalls: 0,
remoteStatusCalls: 0,
localInvalidationCalls: 0,
remoteInvalidationCalls: 0,
};
return Effect.gen(function* () {
const broadcaster = yield* VcsStatusBroadcaster.VcsStatusBroadcaster;
const initial = yield* broadcaster.getStatus({ cwd: "/repo" });
state.currentLocalStatus = {
...baseLocalStatus,
hasWorkingTreeChanges: true,
};
const refreshedLocal = yield* broadcaster.refreshLocalStatus("/repo");
const cached = yield* broadcaster.getStatus({ cwd: "/repo" });
assert.deepStrictEqual(initial, baseStatus);
assert.deepStrictEqual(refreshedLocal, state.currentLocalStatus);
assert.deepStrictEqual(cached, {
...state.currentLocalStatus,
...baseRemoteStatus,
});
assert.equal(state.localStatusCalls, 2);
assert.equal(state.remoteStatusCalls, 1);
assert.equal(state.localInvalidationCalls, 1);
assert.equal(state.remoteInvalidationCalls, 0);
}).pipe(Effect.provide(makeTestLayer(state)));
});
it.effect("repopulates the remote half when a local refresh changes the checkout", () => {
const state = {
currentLocalStatus: baseLocalStatus,
currentRemoteStatus: baseRemoteStatus,
@@ -299,20 +425,31 @@ describe("VcsStatusBroadcaster", () => {
refName: "feature/local-only-refresh",
hasWorkingTreeChanges: true,
};
state.currentRemoteStatus = {
...baseRemoteStatus,
aheadCount: 4,
};
const refreshedLocal = yield* broadcaster.refreshLocalStatus("/repo");
// The refName change drops the stale remote half and forks a remote
// refresh for the new branch; let that fiber settle.
for (let i = 0; i < 100 && state.remoteStatusCalls < 2; i++) {
yield* Effect.yieldNow;
}
const cached = yield* broadcaster.getStatus({ cwd: "/repo" });
assert.deepStrictEqual(initial, baseStatus);
assert.deepStrictEqual(refreshedLocal, state.currentLocalStatus);
assert.deepStrictEqual(cached, {
...state.currentLocalStatus,
...baseRemoteStatus,
...state.currentRemoteStatus,
});
assert.equal(state.localStatusCalls, 2);
assert.equal(state.remoteStatusCalls, 1);
assert.equal(state.remoteStatusCalls, 2);
assert.equal(state.localInvalidationCalls, 1);
assert.equal(state.remoteInvalidationCalls, 0);
assert.equal(state.remoteInvalidationCalls, 1);
}).pipe(Effect.provide(makeTestLayer(state)));
});
+156 -34
View File
@@ -10,6 +10,7 @@ import * as PubSub from "effect/PubSub";
import * as Ref from "effect/Ref";
import * as Schedule from "effect/Schedule";
import * as Scope from "effect/Scope";
import * as Semaphore from "effect/Semaphore";
import * as Stream from "effect/Stream";
import * as SynchronizedRef from "effect/SynchronizedRef";
import type {
@@ -194,6 +195,35 @@ export const make = Effect.gen(function* () {
const cacheRef = yield* Ref.make(new Map<string, CachedVcsStatus>());
const pollersRef = yield* SynchronizedRef.make(new Map<string, ActiveRemotePoller>());
// Serialize refreshes per cwd so a read that started before a mutation (a
// checkout, a pull) cannot finish after the post-mutation refresh and
// publish stale state on top of fresh state. Local and remote halves get
// separate locks: local reads are cheap and must never queue behind an
// in-flight remote read (PR lookups hit the network for seconds). The only
// path that holds both acquires remote before local.
interface CwdLocks {
readonly local: Semaphore.Semaphore;
readonly remote: Semaphore.Semaphore;
}
const locksRef = yield* SynchronizedRef.make(new Map<string, CwdLocks>());
const locksFor = (cwd: string) =>
SynchronizedRef.modifyEffect(locksRef, (locks) => {
const existing = locks.get(cwd);
if (existing) {
return Effect.succeed([existing, locks] as const);
}
return Effect.all([Semaphore.make(1), Semaphore.make(1)]).pipe(
Effect.map(([local, remote]) => {
const created: CwdLocks = { local, remote };
return [created, new Map(locks).set(cwd, created)] as const;
}),
);
});
const withLocalLock = <A, E, R>(cwd: string, effect: Effect.Effect<A, E, R>) =>
locksFor(cwd).pipe(Effect.flatMap((locks) => locks.local.withPermits(1)(effect)));
const withRemoteLock = <A, E, R>(cwd: string, effect: Effect.Effect<A, E, R>) =>
locksFor(cwd).pipe(Effect.flatMap((locks) => locks.remote.withPermits(1)(effect)));
const getCachedStatus = Effect.fn("VcsStatusBroadcaster.getCachedStatus")(function* (
cwd: string,
) {
@@ -206,27 +236,45 @@ export const make = Effect.gen(function* () {
fingerprint: fingerprintStatusPart(local),
value: local,
} satisfies CachedValue<VcsStatusLocalResult>;
const shouldPublish = yield* Ref.modify(cacheRef, (cache) => {
const { shouldPublish, checkoutChanged } = yield* Ref.modify(cacheRef, (cache) => {
const previous = cache.get(cwd) ?? { local: null, remote: null };
const changedRefName =
previous.local !== null && previous.local.value.refName !== local.refName;
const nextCache = new Map(cache);
nextCache.set(cwd, {
...previous,
local: nextLocal,
// The cached remote half (ahead/behind, PR) was computed for the
// previous checkout; carrying it across a refName change would pair
// the new branch with the old branch's PR. Drop it and let the
// remote refresh repopulate it for the new branch.
remote: changedRefName ? null : previous.remote,
});
return [previous.local?.fingerprint !== nextLocal.fingerprint, nextCache] as const;
return [
{
shouldPublish: previous.local?.fingerprint !== nextLocal.fingerprint,
checkoutChanged: changedRefName,
},
nextCache,
] as const;
});
if (options?.publish && shouldPublish) {
yield* PubSub.publish(changesPubSub, {
cwd,
event: {
_tag: "localUpdated",
local,
},
event: checkoutChanged
? {
_tag: "snapshot",
local,
remote: null,
}
: {
_tag: "localUpdated",
local,
},
});
}
return local;
return { local, checkoutChanged };
},
);
@@ -305,8 +353,13 @@ export const make = Effect.gen(function* () {
const loadLocalStatus = Effect.fn("VcsStatusBroadcaster.loadLocalStatus")(function* (
cwd: string,
) {
const local = yield* workflow.localStatus({ cwd });
return yield* updateCachedLocalStatus(cwd, local);
return yield* withLocalLock(
cwd,
Effect.gen(function* () {
const local = yield* workflow.localStatus({ cwd });
return (yield* updateCachedLocalStatus(cwd, local)).local;
}),
);
});
const getOrLoadLocalStatus = Effect.fn("VcsStatusBroadcaster.getOrLoadLocalStatus")(function* (
@@ -329,21 +382,52 @@ export const make = Effect.gen(function* () {
if (cached?.local && cached.remote) {
return mergeGitStatusParts(cached.local.value, cached.remote.value);
}
const [local, remote] = yield* Effect.all(
[
cached?.local ? Effect.succeed(cached.local.value) : workflow.localStatus({ cwd }),
cached?.remote ? Effect.succeed(cached.remote.value) : workflow.remoteStatus({ cwd }),
],
{ concurrency: "unbounded" },
return yield* withRemoteLock(
cwd,
withLocalLock(
cwd,
Effect.gen(function* () {
// Re-check under the locks: a refresh may have populated the cache
// while this call was waiting for them.
const current = yield* getCachedStatus(cwd);
if (current?.local && current.remote) {
return mergeGitStatusParts(current.local.value, current.remote.value);
}
const [local, remote] = yield* Effect.all(
[
current?.local ? Effect.succeed(current.local.value) : workflow.localStatus({ cwd }),
current?.remote
? Effect.succeed(current.remote.value)
: workflow.remoteStatus({ cwd }),
],
{ concurrency: "unbounded" },
);
return yield* updateCachedStatus(cwd, local, remote);
}),
),
);
return yield* updateCachedStatus(cwd, local, remote);
});
const refreshLocalStatusCore = Effect.fn("VcsStatusBroadcaster.refreshLocalStatusCore")(
function* (cwd: string) {
yield* workflow.invalidateLocalStatus(cwd);
const local = yield* workflow.localStatus({ cwd });
return yield* updateCachedLocalStatus(cwd, local, { publish: true });
const result = yield* withLocalLock(
cwd,
Effect.gen(function* () {
yield* workflow.invalidateLocalStatus(cwd);
const local = yield* workflow.localStatus({ cwd });
return yield* updateCachedLocalStatus(cwd, local, { publish: true });
}),
);
if (result.checkoutChanged) {
// The checkout moved (a switch, or a `git checkout` outside T3's
// commands). The remote half was dropped above; repopulate it for the
// new branch without waiting for the next poll tick.
yield* refreshRemoteStatus(cwd).pipe(
Effect.ignoreCause({ log: true }),
Effect.forkIn(broadcasterScope),
);
}
return result.local;
},
);
@@ -356,27 +440,65 @@ export const make = Effect.gen(function* () {
const refreshRemoteStatus = Effect.fn("VcsStatusBroadcaster.refreshRemoteStatus")(function* (
cwd: string,
options?: { readonly refreshUpstream?: boolean },
options?: { readonly refreshUpstream?: boolean; readonly invalidate?: boolean },
) {
if (options?.refreshUpstream !== false) {
yield* workflow.invalidateRemoteStatus(cwd);
}
const remote = yield* workflow.remoteStatus({ cwd }, options);
return yield* updateCachedRemoteStatus(cwd, remote, { publish: true });
return yield* withRemoteLock(
cwd,
Effect.gen(function* () {
const refNameBefore = (yield* getCachedStatus(cwd))?.local?.value.refName;
if (options?.invalidate !== false && options?.refreshUpstream !== false) {
yield* workflow.invalidateRemoteStatus(cwd);
}
const remote = yield* workflow.remoteStatus(
{ cwd },
options?.refreshUpstream === undefined
? undefined
: { refreshUpstream: options.refreshUpstream },
);
// A checkout that lands while the slow remote read is in flight makes
// this result describe the previous branch. Publishing it would
// attach the old branch's PR/divergence to the new refName — discard
// it; the refName change itself already kicked a follow-up refresh.
const refNameAfter = (yield* getCachedStatus(cwd))?.local?.value.refName;
if (refNameBefore !== undefined && refNameAfter !== refNameBefore) {
return (yield* getCachedStatus(cwd))?.remote?.value ?? null;
}
return yield* updateCachedRemoteStatus(cwd, remote, { publish: true });
}),
);
});
const refreshStatusCore = Effect.fn("VcsStatusBroadcaster.refreshStatusCore")(function* (
cwd: string,
) {
// invalidateStatus (not the two partial invalidations) so an explicit
// refresh also bypasses GitManager's slow PR-lookup cache.
yield* workflow.invalidateStatus(cwd);
const local = yield* withLocalLock(
cwd,
Effect.gen(function* () {
const localResult = yield* workflow.localStatus({ cwd });
return (yield* updateCachedLocalStatus(cwd, localResult, { publish: true })).local;
}),
);
const remote = yield* refreshRemoteStatus(cwd, { invalidate: false });
// A checkout can land between the two reads. refreshRemoteStatus discards
// a superseded remote result, which would leave `local` describing the old
// branch — returning that pair would hand the caller a status the cache
// itself no longer agrees with. Prefer the cache's halves, which the
// concurrent refresh has already reconciled for the new branch.
const cached = yield* getCachedStatus(cwd);
return mergeGitStatusParts(
cached?.local?.value ?? local,
cached?.remote ? cached.remote.value : remote,
);
});
const refreshStatus: VcsStatusBroadcaster["Service"]["refreshStatus"] = Effect.fn(
"VcsStatusBroadcaster.refreshStatus",
)(function* (rawCwd) {
const cwd = yield* withFileSystem(normalizeCwd(rawCwd));
// invalidateStatus (not the two partial invalidations) so an explicit
// refresh also bypasses GitManager's slow PR-lookup cache.
yield* workflow.invalidateStatus(cwd);
const [local, remote] = yield* Effect.all(
[workflow.localStatus({ cwd }), workflow.remoteStatus({ cwd })],
{ concurrency: "unbounded" },
);
return yield* updateCachedStatus(cwd, local, remote, { publish: true });
return yield* refreshStatusCore(cwd);
});
const makeRemoteRefreshLoop = (
+16 -1
View File
@@ -1763,6 +1763,10 @@ const makeWsRpcLayer = (
"rpc.aggregate": "vcs",
},
),
[WS_METHODS.vcsBranchPr]: (input) =>
observeRpcEffect(WS_METHODS.vcsBranchPr, gitWorkflow.branchPr(input), {
"rpc.aggregate": "vcs",
}),
[WS_METHODS.vcsPull]: (input) =>
observeRpcEffect(
WS_METHODS.vcsPull,
@@ -1839,7 +1843,18 @@ const makeWsRpcLayer = (
[WS_METHODS.vcsSwitchRef]: (input) =>
observeRpcEffect(
WS_METHODS.vcsSwitchRef,
gitWorkflow.switchRef(input).pipe(Effect.tap(() => refreshGitStatus(input.cwd))),
gitWorkflow.switchRef(input).pipe(
// Publish the new refName before the RPC resolves so a client
// that awaited the switch can never observe the old branch from
// the status stream afterwards. The full refresh (remote half,
// PR lookup) is slow and stays forked.
Effect.tap(() =>
vcsStatusBroadcaster
.refreshLocalStatus(input.cwd)
.pipe(Effect.ignoreCause({ log: true })),
),
Effect.tap(() => refreshGitStatus(input.cwd)),
),
{ "rpc.aggregate": "vcs" },
),
[WS_METHODS.vcsInit]: (input) =>
@@ -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.");
}
}
@@ -10,7 +10,6 @@ import {
resolveEffectiveEnvMode,
resolveEnvModeLabel,
resolveBranchTriggerLabel,
resolveBranchToolbarPrBranch,
resolveBranchToolbarValue,
resolveLockedWorkspaceLabel,
resolveLocalCheckoutBranchMismatch,
@@ -270,35 +269,6 @@ describe("resolveBranchTriggerLabel", () => {
});
});
describe("resolveBranchToolbarPrBranch", () => {
it("uses the explicit thread branch when it matches the displayed branch", () => {
expect(
resolveBranchToolbarPrBranch({
activeThreadBranch: "feature/current",
resolvedActiveBranch: "feature/current",
}),
).toBe("feature/current");
});
it("hides PR state while an optimistic branch switch is in flight", () => {
expect(
resolveBranchToolbarPrBranch({
activeThreadBranch: "feature/current",
resolvedActiveBranch: "feature/next",
}),
).toBeNull();
});
it("does not infer PR state without an explicit thread branch", () => {
expect(
resolveBranchToolbarPrBranch({
activeThreadBranch: null,
resolvedActiveBranch: "feature/current",
}),
).toBeNull();
});
});
describe("resolveLocalCheckoutBranchMismatch", () => {
it("detects when a local thread is associated with a different branch than the checkout", () => {
expect(
@@ -183,13 +183,6 @@ export function resolveBranchTriggerLabel(input: {
return resolvedActiveBranch;
}
export function resolveBranchToolbarPrBranch(input: {
activeThreadBranch: string | null;
resolvedActiveBranch: string | null;
}): string | null {
return input.activeThreadBranch === input.resolvedActiveBranch ? input.activeThreadBranch : null;
}
export function resolveLocalCheckoutBranchMismatch(input: {
effectiveEnvMode: EnvMode;
activeWorktreePath: string | null;
@@ -37,7 +37,6 @@ import { getSourceControlPresentation } from "../sourceControlPresentation";
import {
deriveLocalBranchNameFromRemoteRef,
resolveBranchTriggerLabel,
resolveBranchToolbarPrBranch,
resolveBranchSelectionTarget,
resolveBranchToolbarValue,
resolveDraftEnvModeAfterBranchChange,
@@ -47,7 +46,7 @@ import {
import {
ChangeRequestStatusIcon,
prStatusIndicator,
resolveThreadPr,
selectBranchPr,
} from "./ThreadStatusIndicators";
import { Button } from "./ui/button";
import { Switch } from "./ui/switch";
@@ -601,13 +600,28 @@ export function BranchToolbarBranchSelector({
startFromOrigin,
});
// PR pill shown next to the branch selector when the active branch has one.
const branchPr = resolveThreadPr({
threadBranch: resolveBranchToolbarPrBranch({
activeThreadBranch,
resolvedActiveBranch,
}),
// PR pill shown next to the branch selector when the displayed ref has one.
// The stream-fed status is the fast path while the checkout matches; the
// branch-keyed query keeps the pill correct when the checkout has moved
// elsewhere. Draft "From <base>" selectors intentionally show none — the
// base branch's PR is not this thread's.
const branchPrLookupBranch =
(effectiveEnvMode === "worktree" && !activeWorktreePath) ||
resolvedActiveBranchIsRemote === true
? null
: resolvedActiveBranch;
const branchPrQuery = useEnvironmentQuery(
branchCwd !== null && branchPrLookupBranch !== null
? vcsEnvironment.branchPr({
environmentId,
input: { cwd: branchCwd, branch: branchPrLookupBranch },
})
: null,
);
const branchPr = selectBranchPr({
branch: branchPrLookupBranch,
gitStatus: branchStatusQuery.data ?? null,
branchPr: branchPrQuery.data?.pr,
});
const branchPrStatus = prStatusIndicator(branchPr, branchStatusQuery.data?.sourceControlProvider);
// Action-oriented tooltip (the pill opens the PR), distinct from the sidebar's
+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
+4 -2
View File
@@ -238,7 +238,7 @@ import {
shouldShowProviderStatusBanner,
} from "./chat/ProviderStatusBanner";
import { ThreadErrorBanner } from "./chat/ThreadErrorBanner";
import { resolveThreadPr } from "./ThreadStatusIndicators";
import { useThreadPr } from "./ThreadStatusIndicators";
import { ComposerBannerStack, type ComposerBannerStackItem } from "./chat/ComposerBannerStack";
import { ThreadSyncStatusPill } from "./chat/ThreadSyncStatusPill";
import {
@@ -3964,7 +3964,9 @@ function ChatViewContent(props: ChatViewProps) {
// so the banner and the sidebar row never disagree.
const activeThreadShell = useThreadShell(isServerThread ? activeThreadRef : null);
const autoSettleAfterDays = useClientSettings((settings) => settings.sidebarAutoSettleAfterDays);
const activeThreadPr = resolveThreadPr({
const activeThreadPr = useThreadPr({
environmentId,
cwd: gitStatusCwd,
threadBranch: activeThread?.branch ?? null,
gitStatus: gitStatusQuery.data ?? null,
});
+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(
@@ -1099,6 +1099,12 @@ export default function GitActionsControl({
// Default to true while loading so we don't flash init controls.
const isRepo = gitStatus?.isRepo ?? true;
const hasPrimaryRemote = gitStatus?.hasPrimaryRemote ?? false;
// Deliberately the checkout's status, not the active thread's branch: every
// action here (commit, push, create) runs against whatever is checked out at
// `gitCwd`, so gating them on another branch's PR would offer "Create PR"
// for a branch that already has one — or hide it for one that doesn't.
// Thread-scoped PR state lives on the sidebar badge and the composer pill,
// which are branch-keyed; the branch-mismatch banner explains the split.
const gitStatusForActions = gitStatus;
const allFiles = gitStatusForActions?.workingTree.files ?? [];
-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>
);
}
+4 -2
View File
@@ -16,8 +16,8 @@ import {
ChangeRequestStatusIcon,
prStatusIndicator,
PrStatusTooltipContent,
resolveThreadPr,
terminalStatusFromRunningIds,
useThreadPr,
ThreadStatusLabel,
ThreadWorktreeIndicator,
} from "./ThreadStatusIndicators";
@@ -449,7 +449,9 @@ export const SidebarThreadRow = memo(function SidebarThreadRow(props: SidebarThr
lastVisitedAt,
},
});
const pr = resolveThreadPr({
const pr = useThreadPr({
environmentId: thread.environmentId,
cwd: gitCwd,
threadBranch: thread.branch,
gitStatus: gitStatus.data,
});
+4 -2
View File
@@ -127,8 +127,8 @@ import {
import { resolveLocalCheckoutBranchMismatch } from "./BranchToolbar.logic";
import {
prStatusIndicator,
resolveThreadPr,
settledPrHoverColorClass,
useThreadPr,
terminalStatusFromRunningIds,
type TerminalStatusIndicator,
} from "./ThreadStatusIndicators";
@@ -543,7 +543,9 @@ const SidebarV2Row = memo(function SidebarV2Row(props: {
activeThreadBranch: thread.branch,
currentGitBranch: gitStatus.data?.refName ?? null,
});
const pr = resolveThreadPr({
const pr = useThreadPr({
environmentId: thread.environmentId,
cwd: gitCwd,
threadBranch: thread.branch,
gitStatus: gitStatus.data,
});
@@ -3,7 +3,7 @@ import { describe, expect, it } from "vite-plus/test";
import {
prStatusIndicator,
resolveThreadPr,
selectBranchPr,
settledPrHoverColorClass,
} from "./ThreadStatusIndicators";
@@ -30,43 +30,54 @@ function status(overrides: Partial<VcsStatusResult> = {}): VcsStatusResult {
};
}
describe("resolveThreadPr", () => {
it("keeps local-checkout PR indicators scoped to the stored thread branch", () => {
expect(
resolveThreadPr({
threadBranch: "feature/other",
gitStatus: status(),
}),
).toBeNull();
});
const otherBranchPr = {
number: 7,
title: "Branch-keyed PR",
url: "https://github.com/pingdotgg/t3code/pull/7",
baseRef: "main",
headRef: "feature/other",
state: "open",
} as const;
it("hides PR indicators when a dedicated worktree has switched away from the thread branch", () => {
expect(
resolveThreadPr({
threadBranch: "stack/base",
gitStatus: status(),
}),
).toBeNull();
});
it("hides PR indicators when thread branch metadata is missing", () => {
expect(
resolveThreadPr({
threadBranch: null,
gitStatus: status(),
}),
).toBeNull();
});
it("shows the PR when the live checkout matches the stored thread branch", () => {
describe("selectBranchPr", () => {
it("shows the PR when the live checkout matches the requested branch", () => {
const gitStatus = status();
expect(selectBranchPr({ branch: "feature/current", gitStatus, branchPr: undefined })).toBe(
gitStatus.pr,
);
});
it("falls back to the branch-keyed lookup when the checkout moved elsewhere", () => {
expect(
resolveThreadPr({
threadBranch: "feature/current",
gitStatus,
selectBranchPr({
branch: "feature/other",
gitStatus: status(),
branchPr: otherBranchPr,
}),
).toBe(gitStatus.pr);
).toBe(otherBranchPr);
});
it("treats an empty PR on the matching checkout as authoritative", () => {
// Regression: a warm branch-keyed result must not resurrect a badge the
// status stream just cleared (e.g. immediately after a merge).
expect(
selectBranchPr({
branch: "feature/current",
gitStatus: status({ pr: null }),
branchPr: otherBranchPr,
}),
).toBeNull();
});
it("returns nothing when the branch is unknown and no lookup resolved", () => {
expect(selectBranchPr({ branch: null, gitStatus: status(), branchPr: undefined })).toBeNull();
});
it("returns nothing while the branch-keyed lookup is unresolved", () => {
expect(
selectBranchPr({ branch: "feature/other", gitStatus: status(), branchPr: undefined }),
).toBeNull();
});
});
@@ -3,7 +3,7 @@ import {
scopedThreadKey,
scopeThreadRef,
} from "@t3tools/client-runtime/environment";
import type { VcsStatusResult } from "@t3tools/contracts";
import type { EnvironmentId, VcsStatusResult } from "@t3tools/contracts";
import { CloudIcon, FolderGit2Icon, GitPullRequestIcon, TerminalIcon } from "lucide-react";
import { useMemo } from "react";
import { useEnvironment, usePrimaryEnvironmentId } from "../state/environments";
@@ -110,20 +110,60 @@ export function PrStatusTooltipContent({ status }: { status: PrStatusIndicator }
);
}
export function resolveThreadPr(input: {
/**
* True when the streamed status describes the thread's own branch, and so is
* authoritative about that branch's PR — including when it reports none.
*/
function statusCoversBranch(
gitStatus: VcsStatusResult | null,
threadBranch: string | null,
): gitStatus is VcsStatusResult {
return gitStatus !== null && threadBranch !== null && gitStatus.refName === threadBranch;
}
/**
* Pick the PR for `branch` from the two available sources. The streamed
* status wins whenever it describes that branch — including when it reports
* no PR, which is why this short-circuits instead of falling through with
* `??`: a warm branch-keyed result must never resurrect a badge the
* authoritative status just cleared (e.g. right after a merge).
*/
export function selectBranchPr(input: {
branch: string | null;
gitStatus: VcsStatusResult | null;
branchPr: ThreadPr | null | undefined;
}): ThreadPr | null {
if (statusCoversBranch(input.gitStatus, input.branch)) {
return input.gitStatus.pr ?? null;
}
return input.branchPr ?? null;
}
/**
* PR state for a thread, keyed by the thread's recorded branch rather than
* the current checkout. The stream-fed status is the fast path while the
* checkout matches the thread's branch; the branch-keyed query keeps the
* badge alive when the checkout has moved elsewhere.
*/
export function useThreadPr(input: {
environmentId: EnvironmentId | null;
cwd: string | null;
threadBranch: string | null;
gitStatus: VcsStatusResult | null;
}): ThreadPr | null {
const { threadBranch, gitStatus } = input;
if (gitStatus === null) {
return null;
}
if (threadBranch === null || gitStatus.refName !== threadBranch) {
return null;
}
return gitStatus.pr ?? null;
const branchPr = useEnvironmentQuery(
input.environmentId !== null && input.threadBranch !== null && input.cwd !== null
? vcsEnvironment.branchPr({
environmentId: input.environmentId,
input: { cwd: input.cwd, branch: input.threadBranch },
})
: null,
);
return selectBranchPr({
branch: input.threadBranch,
gitStatus: input.gitStatus,
branchPr: branchPr.data?.pr,
});
}
export function terminalStatusFromRunningIds(
@@ -250,7 +290,9 @@ export function ThreadRowLeadingStatus({ thread }: { thread: SidebarThreadSummar
})
: null,
);
const pr = resolveThreadPr({
const pr = useThreadPr({
environmentId: thread.environmentId,
cwd: gitCwd,
threadBranch: thread.branch,
gitStatus: gitStatus.data,
});
+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>
);
})}
@@ -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,8 +113,8 @@ 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>
);
@@ -116,7 +116,6 @@ import {
isMonospaceFamily,
resolveDefaultFamilyLabel,
} from "../../appearanceFonts";
import { DEFAULT_TERMINAL_FONT_FAMILY } from "~/terminal/ghostty/surface";
import { CodeFontPreview, PromptFontPreview, TerminalFontPreview } from "./SettingsFontPreviews";
import { discoverInstalledFonts, FontFamilyPicker, useFontEnumeration } from "./FontFamilyPicker";
import {
@@ -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);
}
@@ -13,10 +13,13 @@ import {
isTerminalPasteShortcut,
shouldBlinkTerminalCursor,
shouldReportTerminalMouse,
shouldShowTerminalLinkHover,
terminalGridCellAt,
terminalScrollbarGeometry,
terminalScrollbarOffsetAtPointer,
terminalLinkAtColumn,
terminalLinkAtPosition,
terminalLinkAtPositionWithRange,
terminalContentOriginY,
terminalFontFamily,
fittedTerminalFontSize,
@@ -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,6 +285,13 @@ 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", () => {
+187 -10
View File
@@ -10,6 +10,7 @@ import {
measureGhosttyCell,
renderGhosttySnapshot,
terminalGridSize,
type GhosttyCellRange,
type GhosttyCellMetrics,
} from "./renderer";
import symbolsFontUrl from "./fonts/SymbolsNerdFontMono-Regular.woff2?url";
@@ -205,6 +206,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 +246,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 +295,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 +403,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:
@@ -444,6 +516,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;
@@ -815,6 +890,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 +942,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 +964,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 +1047,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 +1062,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 +1110,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 +1123,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 +1184,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 +1241,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 +1254,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 +1387,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 +1411,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 +1514,7 @@ export class GhosttyTerminalSurface {
this.originY = nextOriginY;
this.forceFullRender = true;
}
this.refreshHoveredLink();
renderGhosttySnapshot({
context: this.context,
snapshot: this.snapshot,
@@ -1390,6 +1527,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 +1604,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) ?? [],
};
});
}
@@ -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,
]);
}
+15 -1
View File
@@ -15,7 +15,11 @@ import * as Stream from "effect/Stream";
import * as SubscriptionRef from "effect/SubscriptionRef";
import { Atom, AtomRegistry } from "effect/unstable/reactivity";
import { createEnvironmentRpcCommand, createEnvironmentSubscriptionAtomFamily } from "./runtime.ts";
import {
createEnvironmentRpcCommand,
createEnvironmentRpcQueryAtomFamily,
createEnvironmentSubscriptionAtomFamily,
} from "./runtime.ts";
import type { EnvironmentRegistry } from "../connection/registry.ts";
import { EnvironmentSupervisor } from "../connection/supervisor.ts";
import { safeErrorLogAttributes } from "../errors/safeLog.ts";
@@ -270,6 +274,16 @@ export function createVcsEnvironmentAtoms<R, E>(
return {
listRefs,
// PR state per (cwd, branch), independent of the current checkout. The
// server funnels this into the same cached PR lookup that feeds status,
// so a warm badge costs no extra provider calls.
branchPr: createEnvironmentRpcQueryAtomFamily(runtime, {
label: "environment-data:vcs:branch-pr",
tag: WS_METHODS.vcsBranchPr,
staleTimeMs: 60_000,
idleTtlMs: 5 * 60_000,
refreshIntervalMs: 5 * 60_000,
}),
status: createEnvironmentSubscriptionAtomFamily(runtime, {
label: "environment-data:vcs:status",
subscribe: (input: EnvironmentRpcInput<typeof WS_METHODS.subscribeVcsStatus>) =>
-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)
+19 -1
View File
@@ -188,9 +188,15 @@ export const VcsInitInput = Schema.Struct({
});
export type VcsInitInput = typeof VcsInitInput.Type;
export const VcsBranchPrInput = Schema.Struct({
cwd: TrimmedNonEmptyStringSchema,
branch: TrimmedNonEmptyStringSchema,
});
export type VcsBranchPrInput = typeof VcsBranchPrInput.Type;
// RPC Results
const VcsStatusChangeRequest = Schema.Struct({
export const VcsStatusChangeRequest = Schema.Struct({
number: PositiveInt,
title: TrimmedNonEmptyStringSchema,
url: Schema.String,
@@ -198,6 +204,7 @@ const VcsStatusChangeRequest = Schema.Struct({
headRef: TrimmedNonEmptyStringSchema,
state: VcsStatusChangeRequestState,
});
export type VcsStatusChangeRequest = typeof VcsStatusChangeRequest.Type;
const VcsStatusLocalShape = {
isRepo: Schema.Boolean,
@@ -253,6 +260,17 @@ export const VcsStatusStreamEvent = Schema.Union([
]);
export type VcsStatusStreamEvent = typeof VcsStatusStreamEvent.Type;
/**
* PR/MR state for one branch of a repository, independent of what is
* currently checked out at the cwd. This is what lets a thread keep its PR
* badge after the user (or another thread) switches the checkout elsewhere.
*/
export const VcsBranchPrResult = Schema.Struct({
branch: TrimmedNonEmptyStringSchema,
pr: Schema.NullOr(VcsStatusChangeRequest),
});
export type VcsBranchPrResult = typeof VcsBranchPrResult.Type;
export const VcsListRefsResult = Schema.Struct({
refs: Schema.Array(VcsRef),
isRepo: Schema.Boolean,
+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({
+10
View File
@@ -21,6 +21,8 @@ import {
import { AssetAccessError, AssetCreateUrlInput, AssetCreateUrlResult } from "./assets.ts";
import {
GitActionProgressEvent,
VcsBranchPrInput,
VcsBranchPrResult,
VcsSwitchRefInput,
VcsSwitchRefResult,
GitCommandError,
@@ -191,6 +193,7 @@ export const WS_METHODS = {
vcsCreateRef: "vcs.createRef",
vcsSwitchRef: "vcs.switchRef",
vcsInit: "vcs.init",
vcsBranchPr: "vcs.branchPr",
// Git workflow methods
gitRunStackedAction: "git.runStackedAction",
@@ -558,6 +561,12 @@ export const WsVcsInitRpc = Rpc.make(WS_METHODS.vcsInit, {
error: Schema.Union([VcsError, EnvironmentAuthorizationError]),
});
export const WsVcsBranchPrRpc = Rpc.make(WS_METHODS.vcsBranchPr, {
payload: VcsBranchPrInput,
success: VcsBranchPrResult,
error: Schema.Union([GitManagerServiceError, EnvironmentAuthorizationError]),
});
/**
* Ephemeral live diff preview for compact/mobile surfaces.
* Not the persisted T3 Review model. Future review sessions should use
@@ -838,6 +847,7 @@ export const WsRpcGroup = RpcGroup.make(
WsVcsCreateRefRpc,
WsVcsSwitchRefRpc,
WsVcsInitRpc,
WsVcsBranchPrRpc,
WsReviewGetDiffPreviewRpc,
WsReviewGetDiffFileContentsRpc,
WsTerminalOpenRpc,
-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