Compare commits
20
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
8d8ce194ed | ||
|
|
03044135db | ||
|
|
ac2cd317ce | ||
|
|
ec4f561392 | ||
|
|
f9f3ed7e35 | ||
|
|
a1d871198a | ||
|
|
7251f1a1f1 | ||
|
|
30e471530b | ||
|
|
de592a00e8 | ||
|
|
2a04db134c | ||
|
|
37d3667de4 | ||
|
|
9697b765e5 | ||
|
|
9d9a872bcc | ||
|
|
9235c83eb7 | ||
|
|
e0c85a20ef | ||
|
|
3c5bdb84a9 | ||
|
|
70de6e1786 | ||
|
|
47dfc65265 | ||
|
|
41ebf22eea | ||
|
|
3d429662c9 |
No files matched your search
@@ -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
|
||||
|
||||
@@ -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"
|
||||
|
||||
@@ -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", () => {
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import {
|
||||
deriveLogicalProjectKey,
|
||||
buildProjectGroups,
|
||||
derivePhysicalProjectKey,
|
||||
deriveProjectGroupLabel,
|
||||
} from "@t3tools/client-runtime/state/project-grouping";
|
||||
@@ -37,10 +37,6 @@ export interface HomeProjectScope {
|
||||
readonly projectRefs: ReadonlyArray<ScopedProjectRef>;
|
||||
}
|
||||
|
||||
function getProjectFreshnessTimestamp(project: EnvironmentProject): number {
|
||||
return toSortableTimestamp(project.updatedAt) ?? toSortableTimestamp(project.createdAt) ?? 0;
|
||||
}
|
||||
|
||||
function getProjectSortTimestamp(
|
||||
project: EnvironmentProject,
|
||||
sortOrder: HomeProjectSortOrder,
|
||||
@@ -60,64 +56,19 @@ export function buildHomeProjectScopes(input: {
|
||||
const projects = input.projects.filter(
|
||||
(project) => input.environmentId === null || project.environmentId === input.environmentId,
|
||||
);
|
||||
const projectsByPhysicalKey = new Map<string, EnvironmentProject[]>();
|
||||
for (const project of projects) {
|
||||
const physicalKey = derivePhysicalProjectKey(project);
|
||||
const existing = projectsByPhysicalKey.get(physicalKey);
|
||||
if (existing) existing.push(project);
|
||||
else projectsByPhysicalKey.set(physicalKey, [project]);
|
||||
}
|
||||
|
||||
const winnersByPhysicalKey = new Map<
|
||||
string,
|
||||
{ readonly key: string; readonly project: EnvironmentProject }
|
||||
>();
|
||||
for (const [physicalKey, members] of projectsByPhysicalKey) {
|
||||
const project = members.reduce((winner, candidate) => {
|
||||
const freshnessDelta =
|
||||
getProjectFreshnessTimestamp(candidate) - getProjectFreshnessTimestamp(winner);
|
||||
return freshnessDelta > 0 || (freshnessDelta === 0 && candidate.id > winner.id)
|
||||
? candidate
|
||||
: winner;
|
||||
});
|
||||
const identitySource = members.find((member) => member.repositoryIdentity !== null) ?? project;
|
||||
winnersByPhysicalKey.set(physicalKey, {
|
||||
key: deriveLogicalProjectKey(identitySource, { groupingMode: input.projectGroupingMode }),
|
||||
project,
|
||||
});
|
||||
}
|
||||
|
||||
const groups = new Map<string, EnvironmentProject[]>();
|
||||
for (const { key, project } of winnersByPhysicalKey.values()) {
|
||||
const existing = groups.get(key);
|
||||
if (existing) existing.push(project);
|
||||
else groups.set(key, [project]);
|
||||
}
|
||||
|
||||
const projectRefsByGroup = new Map<string, ScopedProjectRef[]>();
|
||||
const seenProjectRefs = new Set<string>();
|
||||
for (const project of projects) {
|
||||
const refKey = scopedProjectKey(project.environmentId, project.id);
|
||||
if (seenProjectRefs.has(refKey)) continue;
|
||||
seenProjectRefs.add(refKey);
|
||||
|
||||
const key =
|
||||
winnersByPhysicalKey.get(derivePhysicalProjectKey(project))?.key ??
|
||||
deriveLogicalProjectKey(project, { groupingMode: input.projectGroupingMode });
|
||||
const refs = projectRefsByGroup.get(key);
|
||||
const projectRef = { environmentId: project.environmentId, projectId: project.id };
|
||||
if (refs) refs.push(projectRef);
|
||||
else projectRefsByGroup.set(key, [projectRef]);
|
||||
}
|
||||
|
||||
return Array.from(groups, ([key, projects]) => {
|
||||
const representative = projects[0]!;
|
||||
return buildProjectGroups({
|
||||
projects,
|
||||
settings: {
|
||||
sidebarProjectGroupingMode: input.projectGroupingMode,
|
||||
sidebarProjectGroupingOverrides: {},
|
||||
},
|
||||
}).map((group) => {
|
||||
return {
|
||||
key,
|
||||
title: deriveProjectGroupLabel({ representative, members: projects }),
|
||||
representative,
|
||||
projects,
|
||||
projectRefs: projectRefsByGroup.get(key) ?? [],
|
||||
key: group.key,
|
||||
title: group.label,
|
||||
representative: group.representative,
|
||||
projects: group.members.map((member) => member.project),
|
||||
projectRefs: group.memberProjectRefs,
|
||||
};
|
||||
});
|
||||
}
|
||||
@@ -264,9 +215,11 @@ export function buildHomeThreadGroups(input: {
|
||||
}): ReadonlyArray<HomeThreadGroup> {
|
||||
const now = input.now ?? Date.now();
|
||||
const groups = new Map<string, MutableHomeThreadGroup>();
|
||||
const groupTitleByKey = new Map<string, string>();
|
||||
const groupKeyByProjectKey = new Map<string, string>();
|
||||
|
||||
for (const scope of buildHomeProjectScopes(input)) {
|
||||
groupTitleByKey.set(scope.key, scope.title);
|
||||
groups.set(scope.key, {
|
||||
key: scope.key,
|
||||
projects: [...scope.projects],
|
||||
@@ -345,7 +298,9 @@ export function buildHomeThreadGroups(input: {
|
||||
continue;
|
||||
}
|
||||
|
||||
const title = deriveProjectGroupLabel({ representative, members: group.projects });
|
||||
const title =
|
||||
groupTitleByKey.get(group.key) ??
|
||||
deriveProjectGroupLabel({ representative, members: group.projects });
|
||||
const groupMatches =
|
||||
query.length === 0 ||
|
||||
title.toLocaleLowerCase().includes(query) ||
|
||||
|
||||
@@ -37,11 +37,15 @@ import {
|
||||
import { resolveThreadSelectionNavigationAction } from "../../lib/adaptive-navigation";
|
||||
import { scopedThreadKey } from "../../lib/scopedEntities";
|
||||
import { mobilePreferencesAtom } from "../../state/preferences";
|
||||
import {
|
||||
DEFAULT_MOBILE_PROJECT_GROUPING_SETTINGS,
|
||||
resolveMobileProjectGroupingSettings,
|
||||
} from "../../state/project-grouping";
|
||||
import {
|
||||
parseActiveThreadPath,
|
||||
useHardwareKeyboardCommand,
|
||||
} from "../keyboard/hardwareKeyboardCommands";
|
||||
import { HomeListOptionsProvider, resolveProjectGroupingMode } from "../home/home-list-options";
|
||||
import { HomeListOptionsProvider } from "../home/home-list-options";
|
||||
import { ThreadNavigationSidebar } from "../threads/ThreadNavigationSidebar";
|
||||
import { WORKSPACE_PANE_TIMING } from "./workspace-pane-animation";
|
||||
import { WorkspaceInspectorPane } from "./workspace-inspector-pane";
|
||||
@@ -190,15 +194,17 @@ export function AdaptiveWorkspaceLayout(props: {
|
||||
const preferencesResult = useAtomValue(mobilePreferencesAtom);
|
||||
if (!AsyncResult.isSuccess(preferencesResult)) {
|
||||
return AsyncResult.isFailure(preferencesResult) ? (
|
||||
<AdaptiveWorkspaceLayoutContent {...props} projectGroupingMode="repository" />
|
||||
<AdaptiveWorkspaceLayoutContent
|
||||
{...props}
|
||||
projectGroupingMode={DEFAULT_MOBILE_PROJECT_GROUPING_SETTINGS.sidebarProjectGroupingMode}
|
||||
/>
|
||||
) : null;
|
||||
}
|
||||
const groupingSettings = resolveMobileProjectGroupingSettings(preferencesResult.value);
|
||||
return (
|
||||
<AdaptiveWorkspaceLayoutContent
|
||||
{...props}
|
||||
projectGroupingMode={resolveProjectGroupingMode(
|
||||
preferencesResult.value.projectGroupingEnabled,
|
||||
)}
|
||||
projectGroupingMode={groupingSettings.sidebarProjectGroupingMode}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -1,15 +1,25 @@
|
||||
import { ScrollView, View } from "react-native";
|
||||
import { useNavigation } from "@react-navigation/native";
|
||||
import { Platform, ScrollView, View } from "react-native";
|
||||
import { useSafeAreaInsets } from "react-native-safe-area-context";
|
||||
|
||||
import { AndroidScreenHeader } from "../../components/AndroidScreenHeader";
|
||||
import { NativeStackScreenOptions } from "../../native/StackHeader";
|
||||
import { CodeAppearanceSection } from "./appearance/sections/CodeAppearanceSection";
|
||||
import { TerminalAppearanceSection } from "./appearance/sections/TerminalAppearanceSection";
|
||||
import { TextAppearanceSection } from "./appearance/sections/TextAppearanceSection";
|
||||
|
||||
export function SettingsAppearanceRouteScreen() {
|
||||
const navigation = useNavigation();
|
||||
const insets = useSafeAreaInsets();
|
||||
|
||||
return (
|
||||
<View collapsable={false} className="flex-1 bg-sheet">
|
||||
{Platform.OS === "android" ? (
|
||||
<>
|
||||
<NativeStackScreenOptions options={{ headerShown: false }} />
|
||||
<AndroidScreenHeader title="Appearance" onBack={() => navigation.goBack()} />
|
||||
</>
|
||||
) : null}
|
||||
<ScrollView
|
||||
contentInsetAdjustmentBehavior="automatic"
|
||||
showsVerticalScrollIndicator={false}
|
||||
|
||||
@@ -0,0 +1,106 @@
|
||||
import { useAtomSet, useAtomValue } from "@effect/atom-react";
|
||||
import { useNavigation } from "@react-navigation/native";
|
||||
import type { SidebarProjectGroupingMode } from "@t3tools/contracts";
|
||||
import { AsyncResult } from "effect/unstable/reactivity";
|
||||
import { Platform, Pressable, ScrollView, View } from "react-native";
|
||||
import { useSafeAreaInsets } from "react-native-safe-area-context";
|
||||
|
||||
import { AndroidScreenHeader } from "../../components/AndroidScreenHeader";
|
||||
import { AppText as Text } from "../../components/AppText";
|
||||
import { SymbolView } from "../../components/AppSymbol";
|
||||
import { useThemeColor } from "../../lib/useThemeColor";
|
||||
import { NativeStackScreenOptions } from "../../native/StackHeader";
|
||||
import {
|
||||
mobileProjectGroupingModePatch,
|
||||
resolveMobileProjectGroupingSettings,
|
||||
} from "../../state/project-grouping";
|
||||
import { mobilePreferencesAtom, updateMobilePreferencesAtom } from "../../state/preferences";
|
||||
import { SettingsSection } from "./components/SettingsSection";
|
||||
|
||||
const GROUPING_OPTIONS: ReadonlyArray<{
|
||||
readonly mode: SidebarProjectGroupingMode;
|
||||
readonly label: string;
|
||||
readonly description: string;
|
||||
}> = [
|
||||
{
|
||||
mode: "repository",
|
||||
label: "Group by repository",
|
||||
description: "Matching repositories appear as one project.",
|
||||
},
|
||||
{
|
||||
mode: "repository_path",
|
||||
label: "Group by repository path",
|
||||
description: "Keep monorepo paths separate.",
|
||||
},
|
||||
{
|
||||
mode: "separate",
|
||||
label: "Keep separate",
|
||||
description: "Show every workspace as its own project.",
|
||||
},
|
||||
];
|
||||
|
||||
export function SettingsProjectGroupingRouteScreen() {
|
||||
const navigation = useNavigation();
|
||||
const insets = useSafeAreaInsets();
|
||||
const checkmarkColor = useThemeColor("--color-icon");
|
||||
const preferencesResult = useAtomValue(mobilePreferencesAtom);
|
||||
const savePreferences = useAtomSet(updateMobilePreferencesAtom);
|
||||
const preferencesReady = AsyncResult.isSuccess(preferencesResult) && !preferencesResult.waiting;
|
||||
const selectedMode = AsyncResult.isSuccess(preferencesResult)
|
||||
? resolveMobileProjectGroupingSettings(preferencesResult.value).sidebarProjectGroupingMode
|
||||
: null;
|
||||
|
||||
return (
|
||||
<View collapsable={false} className="flex-1 bg-sheet">
|
||||
{Platform.OS === "android" ? (
|
||||
<>
|
||||
<NativeStackScreenOptions options={{ headerShown: false }} />
|
||||
<AndroidScreenHeader title="Project Grouping" onBack={() => navigation.goBack()} />
|
||||
</>
|
||||
) : null}
|
||||
<ScrollView
|
||||
contentInsetAdjustmentBehavior="automatic"
|
||||
showsVerticalScrollIndicator={false}
|
||||
className="flex-1"
|
||||
contentContainerClassName="gap-3 px-5 pt-4"
|
||||
contentContainerStyle={{ paddingBottom: Math.max(insets.bottom, 18) + 18 }}
|
||||
>
|
||||
<SettingsSection title="Default grouping">
|
||||
{GROUPING_OPTIONS.map((option, index) => (
|
||||
<Pressable
|
||||
key={option.mode}
|
||||
accessibilityRole="radio"
|
||||
accessibilityState={{
|
||||
checked: selectedMode === option.mode,
|
||||
disabled: !preferencesReady,
|
||||
}}
|
||||
disabled={!preferencesReady}
|
||||
onPress={() => savePreferences(mobileProjectGroupingModePatch(option.mode))}
|
||||
className={
|
||||
index === 0
|
||||
? "flex-row items-center gap-4 p-4"
|
||||
: "flex-row items-center gap-4 border-t border-border-subtle p-4"
|
||||
}
|
||||
>
|
||||
<View className="min-w-0 flex-1 gap-1">
|
||||
<Text className="text-lg text-foreground">{option.label}</Text>
|
||||
<Text className="text-sm leading-normal text-foreground-muted">
|
||||
{option.description}
|
||||
</Text>
|
||||
</View>
|
||||
{selectedMode === option.mode ? (
|
||||
<SymbolView
|
||||
name="checkmark"
|
||||
size={18}
|
||||
tintColor={checkmarkColor}
|
||||
type="monochrome"
|
||||
weight="semibold"
|
||||
/>
|
||||
) : null}
|
||||
</Pressable>
|
||||
))}
|
||||
</SettingsSection>
|
||||
</ScrollView>
|
||||
</View>
|
||||
);
|
||||
}
|
||||
@@ -530,20 +530,9 @@ function ConfiguredSettingsRouteScreen() {
|
||||
}
|
||||
|
||||
function GeneralSettingsSection() {
|
||||
const preferencesResult = useAtomValue(mobilePreferencesAtom);
|
||||
const savePreferences = useAtomSet(updateMobilePreferencesAtom);
|
||||
const projectGroupingEnabled = AsyncResult.isSuccess(preferencesResult)
|
||||
? preferencesResult.value.projectGroupingEnabled !== false
|
||||
: true;
|
||||
|
||||
return (
|
||||
<SettingsSection title="General">
|
||||
<SettingsSwitchRow
|
||||
icon="folder"
|
||||
label="Project Grouping"
|
||||
value={projectGroupingEnabled}
|
||||
onValueChange={(value) => savePreferences({ projectGroupingEnabled: value })}
|
||||
/>
|
||||
<SettingsRow icon="folder" label="Project Grouping" target="SettingsProjectGrouping" />
|
||||
</SettingsSection>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -1,4 +1,11 @@
|
||||
import { Platform, ScrollView, View, useColorScheme } from "react-native";
|
||||
import {
|
||||
Platform,
|
||||
ScrollView,
|
||||
type StyleProp,
|
||||
type TextStyle,
|
||||
View,
|
||||
useColorScheme,
|
||||
} from "react-native";
|
||||
|
||||
import { AppText as Text } from "../../../../components/AppText";
|
||||
import {
|
||||
@@ -54,14 +61,48 @@ export function TerminalAppearancePreview(props: { readonly fontSize: number })
|
||||
fontSize: props.fontSize,
|
||||
lineHeight,
|
||||
} as const;
|
||||
// AppText stamps the sans font on every node, so nested spans must
|
||||
// re-apply the terminal font instead of relying on inheritance, exactly
|
||||
// like the code preview's tokens below.
|
||||
const span = (color: string, extra?: TextStyle): StyleProp<TextStyle> => [
|
||||
lineStyle,
|
||||
{ color, ...extra },
|
||||
];
|
||||
|
||||
return (
|
||||
<View className="p-4">
|
||||
<Text style={[lineStyle, { color: theme.foreground }]}>$ npm run dev</Text>
|
||||
<Text style={[lineStyle, { color: theme.palette[2] }]}>✓ Ready in 430ms</Text>
|
||||
<Text style={[lineStyle, { color: theme.foreground }]}>
|
||||
Local: http://localhost:3000{" "}
|
||||
<Text style={[lineStyle, { color: theme.cursorForeground }]}>▏</Text>
|
||||
<Text style={span(theme.foreground)}>
|
||||
<Text style={span(theme.palette[2])}>→ </Text>
|
||||
<Text style={span(theme.palette[6])}>t3code </Text>
|
||||
<Text style={span(theme.palette[4])}>git:(</Text>
|
||||
<Text style={span(theme.palette[1])}>main</Text>
|
||||
<Text style={span(theme.palette[4])}>)</Text>
|
||||
<Text style={span(theme.palette[3])}> ✗</Text>
|
||||
<Text style={span(theme.foreground)}> vpr dev</Text>
|
||||
</Text>
|
||||
<Text style={span(theme.foreground)}>
|
||||
<Text style={span(theme.palette[2])}>VITE v7.1.1</Text>
|
||||
<Text style={span(theme.mutedForeground)}> ready in</Text>
|
||||
<Text style={span(theme.foreground)}> 1.24s</Text>
|
||||
</Text>
|
||||
<Text style={span(theme.foreground)}>
|
||||
<Text style={span(theme.palette[2])}>→ </Text>
|
||||
<Text style={span(theme.mutedForeground)}>Local: </Text>
|
||||
<Text style={span(theme.palette[6], { textDecorationLine: "underline" })}>
|
||||
http://127.0.0.1:5173/
|
||||
</Text>
|
||||
</Text>
|
||||
<Text style={span(theme.foreground)}>
|
||||
<Text style={span(theme.palette[2])}>✓ 85 passed</Text>
|
||||
<Text style={span(theme.palette[3])}> △ 2 warnings</Text>
|
||||
<Text style={span(theme.palette[1])}> ✗ 0 failed</Text>
|
||||
</Text>
|
||||
<Text style={span(theme.foreground)}>
|
||||
<Text style={span(theme.background, { backgroundColor: theme.palette[2] })}>
|
||||
{" READY "}
|
||||
</Text>
|
||||
<Text style={span(theme.mutedForeground)}> watching for changes</Text>{" "}
|
||||
<Text style={span(theme.cursorForeground)}>▏</Text>
|
||||
</Text>
|
||||
</View>
|
||||
);
|
||||
|
||||
@@ -2,6 +2,7 @@ export type SettingsSheetTarget =
|
||||
| "SettingsEnvironments"
|
||||
| "SettingsArchive"
|
||||
| "SettingsAppearance"
|
||||
| "SettingsProjectGrouping"
|
||||
| "SettingsClientStorage";
|
||||
|
||||
export type SettingsLegalDocumentTarget = "SettingsLegal";
|
||||
@@ -50,6 +50,7 @@ import { enqueueThreadOutboxMessage, removeThreadOutboxMessage } from "../../sta
|
||||
import { useRemoteConnectionStatus } from "../../state/use-remote-environment-registry";
|
||||
import { branchBadgeLabel, useNewTaskFlow } from "./new-task-flow-provider";
|
||||
import { useCreateProjectThread } from "./use-project-actions";
|
||||
import { resolveDraftProjectSelection } from "./new-task-project-selection";
|
||||
import { useIncomingShare } from "../sharing/IncomingShareProvider";
|
||||
|
||||
function formatWorkspaceLabel(input: {
|
||||
@@ -89,7 +90,7 @@ export function NewTaskDraftScreen(props: {
|
||||
const colorScheme = useColorScheme();
|
||||
const isKeyboardVisible = useKeyboardState((state) => state.isVisible);
|
||||
const controlsBottomPadding = isKeyboardVisible ? 8 : Math.max(insets.bottom, 10);
|
||||
const { logicalProjects, selectedProject, setProject } = flow;
|
||||
const { projectScopes, selectedProject, selectedProjectKey, setProject } = flow;
|
||||
const { connectedEnvironments } = useRemoteConnectionStatus();
|
||||
const selectedEnvironmentServerConfig = useEnvironmentServerConfig(
|
||||
selectedProject?.environmentId ?? null,
|
||||
@@ -277,24 +278,25 @@ export function NewTaskDraftScreen(props: {
|
||||
return;
|
||||
}
|
||||
|
||||
if (selectedProject) {
|
||||
const selection = resolveDraftProjectSelection(selectedProjectKey, projects, projectScopes);
|
||||
if (selection.kind === "preserve") {
|
||||
return;
|
||||
}
|
||||
|
||||
if (logicalProjects.length === 1) {
|
||||
setProject(logicalProjects[0]!.project);
|
||||
if (selection.kind === "select") {
|
||||
setProject(selection.project);
|
||||
return;
|
||||
}
|
||||
|
||||
navigation.dispatch(StackActions.replace("NewTask"));
|
||||
}, [
|
||||
logicalProjects,
|
||||
projectScopes,
|
||||
projects,
|
||||
props.initialProjectRef,
|
||||
props.incomingShareId,
|
||||
props.pendingTaskId,
|
||||
navigation,
|
||||
selectedProject,
|
||||
selectedProjectKey,
|
||||
setProject,
|
||||
]);
|
||||
|
||||
|
||||
@@ -1,8 +1,8 @@
|
||||
import { NativeHeaderToolbar, NativeStackScreenOptions } from "../../native/StackHeader";
|
||||
import { useIsFocused, useNavigation, type StaticScreenProps } from "@react-navigation/native";
|
||||
import { SymbolView } from "../../components/AppSymbol";
|
||||
import type { EnvironmentId, ProjectId } from "@t3tools/contracts";
|
||||
import { useEffect, useMemo, useRef } from "react";
|
||||
import type { EnvironmentProject } from "@t3tools/client-runtime/state/shell";
|
||||
import { useEffect, useRef, useState } from "react";
|
||||
import { ActivityIndicator, Alert, Platform, Pressable, ScrollView, View } from "react-native";
|
||||
import { useSafeAreaInsets } from "react-native-safe-area-context";
|
||||
import { useThemeColor } from "../../lib/useThemeColor";
|
||||
@@ -11,12 +11,13 @@ import { cn } from "../../lib/cn";
|
||||
import { AndroidScreenHeader } from "../../components/AndroidScreenHeader";
|
||||
import { AppText as Text } from "../../components/AppText";
|
||||
import { ProjectFavicon } from "../../components/ProjectFavicon";
|
||||
import { useProjects, useThreadShells } from "../../state/entities";
|
||||
import { useProjects } from "../../state/entities";
|
||||
import type { WorkspaceState } from "../../state/workspaceModel";
|
||||
import { useWorkspaceState } from "../../state/workspace";
|
||||
import { groupProjectsByRepository } from "../../lib/repositoryGroups";
|
||||
import { scopedProjectKey } from "../../lib/scopedEntities";
|
||||
import { useAdaptiveWorkspaceLayout } from "../layout/AdaptiveWorkspaceLayout";
|
||||
import { useIncomingShare } from "../sharing/IncomingShareProvider";
|
||||
import { useNewTaskFlow } from "./new-task-flow-provider";
|
||||
|
||||
type NewTaskRouteParams = {
|
||||
readonly incomingShareId?: string | string[];
|
||||
@@ -79,7 +80,7 @@ function deriveProjectEmptyState(catalogState: WorkspaceState): {
|
||||
|
||||
export function NewTaskRouteScreen({ route }: StaticScreenProps<NewTaskRouteParams | undefined>) {
|
||||
const projects = useProjects();
|
||||
const threads = useThreadShells();
|
||||
const { projectScopes } = useNewTaskFlow();
|
||||
const { state: catalogState } = useWorkspaceState();
|
||||
const navigation = useNavigation();
|
||||
const isFocused = useIsFocused();
|
||||
@@ -87,6 +88,7 @@ export function NewTaskRouteScreen({ route }: StaticScreenProps<NewTaskRoutePara
|
||||
const insets = useSafeAreaInsets();
|
||||
const chevronColor = useThemeColor("--color-chevron");
|
||||
const accentColor = useThemeColor("--color-icon-muted");
|
||||
const [expandedGroupKeys, setExpandedGroupKeys] = useState<ReadonlySet<string>>(() => new Set());
|
||||
const { getShare, releaseShareReservation } = useIncomingShare();
|
||||
const routeShareId = Array.isArray(route.params?.incomingShareId)
|
||||
? route.params.incomingShareId[0]
|
||||
@@ -100,33 +102,6 @@ export function NewTaskRouteScreen({ route }: StaticScreenProps<NewTaskRoutePara
|
||||
: `Choose a project for the ${incomingShare.attachments.length} images you shared`
|
||||
: null;
|
||||
const screenTitle = incomingShare ? "Start a task" : "Choose project";
|
||||
const repositoryGroups = useMemo(
|
||||
() => groupProjectsByRepository({ projects, threads }),
|
||||
[projects, threads],
|
||||
);
|
||||
const items = useMemo(() => {
|
||||
const nextItems: Array<{
|
||||
readonly environmentId: EnvironmentId;
|
||||
readonly id: ProjectId;
|
||||
readonly key: string;
|
||||
readonly title: string;
|
||||
readonly workspaceRoot: string;
|
||||
}> = [];
|
||||
for (const group of repositoryGroups) {
|
||||
const project = group.projects[0]?.project;
|
||||
if (!project) {
|
||||
continue;
|
||||
}
|
||||
nextItems.push({
|
||||
environmentId: project.environmentId,
|
||||
id: project.id,
|
||||
key: group.key,
|
||||
title: project.title,
|
||||
workspaceRoot: project.workspaceRoot,
|
||||
});
|
||||
}
|
||||
return nextItems;
|
||||
}, [repositoryGroups]);
|
||||
const projectEmptyState = deriveProjectEmptyState(catalogState);
|
||||
const resumedDestinationKeyRef = useRef<string | null>(null);
|
||||
const reservedDestinationProject = incomingShare?.destination
|
||||
@@ -137,7 +112,7 @@ export function NewTaskRouteScreen({ route }: StaticScreenProps<NewTaskRoutePara
|
||||
) ?? null)
|
||||
: null;
|
||||
|
||||
async function selectProject(item: (typeof items)[number]): Promise<void> {
|
||||
async function selectProject(project: EnvironmentProject): Promise<void> {
|
||||
if (incomingShare?.destination && !reservedDestinationProject) {
|
||||
try {
|
||||
await releaseShareReservation(incomingShare.id, incomingShare.destination);
|
||||
@@ -154,14 +129,26 @@ export function NewTaskRouteScreen({ route }: StaticScreenProps<NewTaskRoutePara
|
||||
navigation.navigate("NewTaskSheet", {
|
||||
screen: "NewTaskDraft",
|
||||
params: {
|
||||
environmentId: item.environmentId,
|
||||
projectId: item.id,
|
||||
title: item.title,
|
||||
environmentId: project.environmentId,
|
||||
projectId: project.id,
|
||||
title: project.title,
|
||||
incomingShareId: incomingShare?.id,
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
function toggleGroup(groupKey: string): void {
|
||||
setExpandedGroupKeys((current) => {
|
||||
const next = new Set(current);
|
||||
if (next.has(groupKey)) {
|
||||
next.delete(groupKey);
|
||||
} else {
|
||||
next.add(groupKey);
|
||||
}
|
||||
return next;
|
||||
});
|
||||
}
|
||||
|
||||
useEffect(() => {
|
||||
const destination = incomingShare?.destination;
|
||||
if (!destination) {
|
||||
@@ -251,11 +238,12 @@ export function NewTaskRouteScreen({ route }: StaticScreenProps<NewTaskRoutePara
|
||||
contentInset={{ bottom: Math.max(insets.bottom, 18) + 18 }}
|
||||
contentContainerStyle={{
|
||||
gap: 12,
|
||||
paddingBottom: 8,
|
||||
paddingHorizontal: 20,
|
||||
paddingTop: 8,
|
||||
}}
|
||||
>
|
||||
{items.length === 0 ? (
|
||||
{projectScopes.length === 0 ? (
|
||||
<View collapsable={false} className="items-center gap-3 rounded-[24px] bg-card px-6 py-8">
|
||||
{projectEmptyState.loading ? <ActivityIndicator color={accentColor} /> : null}
|
||||
<Text className="text-center text-lg font-t3-bold text-foreground">
|
||||
@@ -286,42 +274,89 @@ export function NewTaskRouteScreen({ route }: StaticScreenProps<NewTaskRoutePara
|
||||
</View>
|
||||
) : (
|
||||
<View collapsable={false} className="overflow-hidden rounded-[24px] bg-card">
|
||||
{items.map((item, index) => {
|
||||
const isFirst = index === 0;
|
||||
const isLast = index === items.length - 1;
|
||||
|
||||
{projectScopes.map((scope, scopeIndex) => {
|
||||
const hasMultipleProjects = scope.projects.length > 1;
|
||||
const expanded = expandedGroupKeys.has(scope.key);
|
||||
const singleProject = hasMultipleProjects ? null : scope.projects[0];
|
||||
return (
|
||||
<Pressable
|
||||
key={item.key}
|
||||
disabled={reservedDestinationProject !== null}
|
||||
onPress={() => void selectProject(item)}
|
||||
className={cn(
|
||||
"bg-card px-4 py-3.5",
|
||||
!isFirst && "border-t border-border-subtle",
|
||||
isFirst && "rounded-t-[24px]",
|
||||
isLast && "rounded-b-[24px]",
|
||||
)}
|
||||
<View
|
||||
key={scope.key}
|
||||
className={cn(scopeIndex > 0 && "border-t border-border-subtle")}
|
||||
>
|
||||
<View className="flex-row items-center justify-between gap-3">
|
||||
<Pressable
|
||||
disabled={singleProject !== null && reservedDestinationProject !== null}
|
||||
onPress={() => {
|
||||
if (singleProject) {
|
||||
void selectProject(singleProject);
|
||||
} else {
|
||||
toggleGroup(scope.key);
|
||||
}
|
||||
}}
|
||||
className="flex-row items-center gap-3 bg-card px-4 py-3.5"
|
||||
>
|
||||
<View className="h-7 w-7 items-center justify-center">
|
||||
<ProjectFavicon
|
||||
environmentId={item.environmentId}
|
||||
environmentId={scope.representative.environmentId}
|
||||
size={20}
|
||||
projectTitle={item.title}
|
||||
workspaceRoot={item.workspaceRoot}
|
||||
projectTitle={scope.title}
|
||||
workspaceRoot={scope.representative.workspaceRoot}
|
||||
/>
|
||||
</View>
|
||||
<View className="flex-1">
|
||||
<Text className="text-base leading-snug font-t3-bold">{item.title}</Text>
|
||||
<View className="min-w-0 flex-1">
|
||||
<Text className="text-base leading-snug font-t3-bold">{scope.title}</Text>
|
||||
<Text
|
||||
className="text-xs leading-snug text-foreground-muted"
|
||||
ellipsizeMode="middle"
|
||||
numberOfLines={1}
|
||||
>
|
||||
{hasMultipleProjects
|
||||
? `${scope.projects.length} workspaces`
|
||||
: singleProject?.workspaceRoot}
|
||||
</Text>
|
||||
</View>
|
||||
<SymbolView
|
||||
name="chevron.right"
|
||||
name={hasMultipleProjects && expanded ? "chevron.down" : "chevron.right"}
|
||||
size={14}
|
||||
tintColor={chevronColor}
|
||||
type="monochrome"
|
||||
/>
|
||||
</View>
|
||||
</Pressable>
|
||||
</Pressable>
|
||||
{hasMultipleProjects && expanded
|
||||
? scope.projects.map((project) => (
|
||||
<Pressable
|
||||
key={scopedProjectKey(project.environmentId, project.id)}
|
||||
disabled={reservedDestinationProject !== null}
|
||||
onPress={() => void selectProject(project)}
|
||||
className="flex-row items-center gap-3 border-t border-border-subtle bg-card py-3 pr-4 pl-10"
|
||||
>
|
||||
<ProjectFavicon
|
||||
environmentId={project.environmentId}
|
||||
size={18}
|
||||
projectTitle={project.title}
|
||||
workspaceRoot={project.workspaceRoot}
|
||||
/>
|
||||
<View className="min-w-0 flex-1">
|
||||
<Text className="text-sm font-t3-bold text-foreground">
|
||||
{project.title}
|
||||
</Text>
|
||||
<Text
|
||||
className="text-xs text-foreground-muted"
|
||||
ellipsizeMode="middle"
|
||||
numberOfLines={1}
|
||||
>
|
||||
{project.workspaceRoot}
|
||||
</Text>
|
||||
</View>
|
||||
<SymbolView
|
||||
name="chevron.right"
|
||||
size={14}
|
||||
tintColor={chevronColor}
|
||||
type="monochrome"
|
||||
/>
|
||||
</Pressable>
|
||||
))
|
||||
: null}
|
||||
</View>
|
||||
);
|
||||
})}
|
||||
</View>
|
||||
|
||||
@@ -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();
|
||||
});
|
||||
});
|
||||
@@ -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,
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -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;
|
||||
}
|
||||
@@ -23,6 +23,7 @@ const emitXAiPromptCompleteThenHang = process.env.T3_ACP_EMIT_XAI_PROMPT_COMPLET
|
||||
const emitForeignSessionUpdates = process.env.T3_ACP_EMIT_FOREIGN_SESSION_UPDATES === "1";
|
||||
const hangPromptForever = process.env.T3_ACP_HANG_PROMPT_FOREVER === "1";
|
||||
const hangFirstPromptForever = process.env.T3_ACP_HANG_FIRST_PROMPT_FOREVER === "1";
|
||||
const hangFirstPrompts = Number(process.env.T3_ACP_HANG_FIRST_PROMPTS ?? "0");
|
||||
const emitLateUpdateAfterCancel = process.env.T3_ACP_EMIT_LATE_UPDATE_AFTER_CANCEL === "1";
|
||||
const omitXAiPromptCompleteStopReason =
|
||||
process.env.T3_ACP_OMIT_XAI_PROMPT_COMPLETE_STOP_REASON === "1";
|
||||
@@ -518,7 +519,13 @@ const program = Effect.gen(function* () {
|
||||
return yield* Effect.never;
|
||||
}
|
||||
|
||||
if (hangPromptForever || (hangFirstPromptForever && promptCount === 1)) {
|
||||
if (
|
||||
hangPromptForever ||
|
||||
(hangFirstPromptForever && promptCount === 1) ||
|
||||
(Number.isFinite(hangFirstPrompts) &&
|
||||
hangFirstPrompts > 0 &&
|
||||
promptCount <= hangFirstPrompts)
|
||||
) {
|
||||
return yield* Effect.never;
|
||||
}
|
||||
|
||||
|
||||
@@ -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`,
|
||||
|
||||
@@ -11,6 +11,7 @@ import * as Deferred from "effect/Deferred";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Fiber from "effect/Fiber";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as Ref from "effect/Ref";
|
||||
import * as Schema from "effect/Schema";
|
||||
import * as Stream from "effect/Stream";
|
||||
import * as TestClock from "effect/testing/TestClock";
|
||||
@@ -60,6 +61,89 @@ exec ${JSON.stringify(mockAgentCommand)} ${mockAgentArgs.map((arg) => JSON.strin
|
||||
return wrapperPath;
|
||||
}
|
||||
|
||||
async function makeTerminalCallbackWrapper(
|
||||
kind: "permission" | "question",
|
||||
promptOutcome: "success" | "failure" | "hang" = "success",
|
||||
) {
|
||||
const dir = await NodeFSP.mkdtemp(NodePath.join(NodeOS.tmpdir(), "cursor-acp-terminal-"));
|
||||
const wrapperPath = NodePath.join(dir, "fake-agent.mjs");
|
||||
const callback =
|
||||
kind === "permission"
|
||||
? {
|
||||
jsonrpc: "2.0",
|
||||
id: 9001,
|
||||
method: "session/request_permission",
|
||||
params: {
|
||||
sessionId: "terminal-callback-session",
|
||||
toolCall: {
|
||||
toolCallId: "terminal-tool-call",
|
||||
title: "Terminal",
|
||||
kind: "execute",
|
||||
status: "pending",
|
||||
content: [
|
||||
{
|
||||
type: "content",
|
||||
content: { type: "text", text: "run terminal command" },
|
||||
},
|
||||
],
|
||||
},
|
||||
options: [
|
||||
{ optionId: "allow-once", name: "Allow once", kind: "allow_once" },
|
||||
{ optionId: "reject-once", name: "Reject", kind: "reject_once" },
|
||||
],
|
||||
},
|
||||
}
|
||||
: {
|
||||
jsonrpc: "2.0",
|
||||
id: 9002,
|
||||
method: "cursor/ask_question",
|
||||
params: {
|
||||
toolCallId: "terminal-question",
|
||||
title: "Question",
|
||||
questions: [
|
||||
{
|
||||
id: "scope",
|
||||
prompt: "Which scope?",
|
||||
options: [{ id: "workspace", label: "Workspace" }],
|
||||
},
|
||||
],
|
||||
},
|
||||
};
|
||||
const script = `#!/usr/bin/env node
|
||||
import readline from "node:readline";
|
||||
const callback = ${JSON.stringify(callback)};
|
||||
const kind = ${JSON.stringify(kind)};
|
||||
const promptOutcome = ${JSON.stringify(promptOutcome)};
|
||||
const send = (message) => process.stdout.write(JSON.stringify(message) + "\\n");
|
||||
readline.createInterface({ input: process.stdin }).on("line", (line) => {
|
||||
const message = JSON.parse(line);
|
||||
if (!("method" in message)) return;
|
||||
if (message.method === "initialize") {
|
||||
send({ jsonrpc: "2.0", id: message.id, result: { protocolVersion: 1, agentCapabilities: {} } });
|
||||
} else if (message.method === "session/new") {
|
||||
send({ jsonrpc: "2.0", id: message.id, result: { sessionId: "terminal-callback-session" } });
|
||||
} else if (message.method === "session/prompt") {
|
||||
const response =
|
||||
promptOutcome === "failure"
|
||||
? { jsonrpc: "2.0", id: message.id, error: { code: -32603, message: "prompt failed" } }
|
||||
: { jsonrpc: "2.0", id: message.id, result: { stopReason: "end_turn" } };
|
||||
const messages =
|
||||
promptOutcome === "hang"
|
||||
? [callback]
|
||||
: kind === "question" && promptOutcome === "success"
|
||||
? [response, callback]
|
||||
: [callback, response];
|
||||
process.stdout.write(messages.map(JSON.stringify).join("\\n") + "\\n");
|
||||
} else if (message.id !== undefined) {
|
||||
send({ jsonrpc: "2.0", id: message.id, result: {} });
|
||||
}
|
||||
});
|
||||
`;
|
||||
await NodeFSP.writeFile(wrapperPath, script, "utf8");
|
||||
await NodeFSP.chmod(wrapperPath, 0o755);
|
||||
return wrapperPath;
|
||||
}
|
||||
|
||||
async function makeProbeWrapper(
|
||||
requestLogPath: string,
|
||||
argvLogPath: string,
|
||||
@@ -130,6 +214,24 @@ function waitForJsonLogMatch(
|
||||
});
|
||||
}
|
||||
|
||||
function waitForJsonLogCount(
|
||||
filePath: string,
|
||||
predicate: (entry: Record<string, unknown>) => boolean,
|
||||
expectedCount: number,
|
||||
attempts = 40,
|
||||
) {
|
||||
return Effect.gen(function* () {
|
||||
for (let attempt = 0; attempt < attempts; attempt += 1) {
|
||||
const entries = yield* Effect.promise(() => readJsonLines(filePath));
|
||||
if (entries.filter(predicate).length >= expectedCount) {
|
||||
return entries;
|
||||
}
|
||||
yield* Effect.yieldNow;
|
||||
}
|
||||
return yield* Effect.promise(() => readJsonLines(filePath));
|
||||
});
|
||||
}
|
||||
|
||||
// Tests mutate `ServerSettingsService` mid-flight (e.g. setting
|
||||
// `providers.cursor.binaryPath` to a mock ACP wrapper). The adapter
|
||||
// captures `cursorSettings` once at construction, so without a resolver
|
||||
@@ -1047,6 +1149,360 @@ cursorAdapterTestLayer("CursorAdapterLive", (it) => {
|
||||
yield* adapter.stopSession(threadId);
|
||||
}),
|
||||
);
|
||||
it.effect("starts a fresh turn immediately after interrupting a hanging prompt", () =>
|
||||
Effect.gen(function* () {
|
||||
const adapter = yield* CursorAdapter;
|
||||
const serverSettings = yield* ServerSettingsService;
|
||||
const threadId = ThreadId.make("cursor-interrupt-follow-up-thread");
|
||||
const tempDir = yield* Effect.promise(() =>
|
||||
NodeFSP.mkdtemp(NodePath.join(NodeOS.tmpdir(), "cursor-acp-")),
|
||||
);
|
||||
const requestLogPath = NodePath.join(tempDir, "requests.ndjson");
|
||||
const argvLogPath = NodePath.join(tempDir, "argv.txt");
|
||||
yield* Effect.promise(() => NodeFSP.writeFile(requestLogPath, "", "utf8"));
|
||||
const wrapperPath = yield* Effect.promise(() =>
|
||||
makeProbeWrapper(requestLogPath, argvLogPath, {
|
||||
T3_ACP_HANG_FIRST_PROMPTS: "2",
|
||||
}),
|
||||
);
|
||||
yield* serverSettings.updateSettings({
|
||||
providers: { cursor: { binaryPath: wrapperPath } },
|
||||
});
|
||||
|
||||
const events: Array<ProviderRuntimeEvent> = [];
|
||||
const firstTurnStarted = yield* Deferred.make<string>();
|
||||
const secondTurnStarted = yield* Deferred.make<string>();
|
||||
const startedCountRef = yield* Ref.make(0);
|
||||
const twoTurnsCompleted = yield* Deferred.make<void>();
|
||||
const completedCountRef = yield* Ref.make(0);
|
||||
const eventFiber = yield* Stream.runForEach(adapter.streamEvents, (event) =>
|
||||
Effect.gen(function* () {
|
||||
if (String(event.threadId) !== String(threadId)) return;
|
||||
events.push(event);
|
||||
if (event.type === "turn.started") {
|
||||
const startedCount = yield* Ref.updateAndGet(startedCountRef, (count) => count + 1);
|
||||
if (startedCount === 1) {
|
||||
yield* Deferred.succeed(firstTurnStarted, String(event.turnId)).pipe(Effect.ignore);
|
||||
}
|
||||
if (startedCount === 2) {
|
||||
yield* Deferred.succeed(secondTurnStarted, String(event.turnId)).pipe(Effect.ignore);
|
||||
}
|
||||
}
|
||||
if (event.type === "turn.completed") {
|
||||
const completedCount = yield* Ref.updateAndGet(completedCountRef, (count) => count + 1);
|
||||
if (completedCount === 2) {
|
||||
yield* Deferred.succeed(twoTurnsCompleted, undefined).pipe(Effect.ignore);
|
||||
}
|
||||
}
|
||||
}),
|
||||
).pipe(Effect.forkChild);
|
||||
|
||||
yield* adapter.startSession({
|
||||
threadId,
|
||||
provider: ProviderDriverKind.make("cursor"),
|
||||
cwd: process.cwd(),
|
||||
runtimeMode: "approval-required",
|
||||
modelSelection: {
|
||||
instanceId: ProviderInstanceId.make("cursor"),
|
||||
model: "default",
|
||||
},
|
||||
});
|
||||
const firstSendFiber = yield* adapter
|
||||
.sendTurn({ threadId, input: "hang", attachments: [] })
|
||||
.pipe(Effect.forkChild);
|
||||
const firstTurnId = yield* Deferred.await(firstTurnStarted).pipe(Effect.timeout("2 seconds"));
|
||||
yield* waitForJsonLogMatch(
|
||||
requestLogPath,
|
||||
(request) => request.method === "session/prompt",
|
||||
80,
|
||||
).pipe(Effect.timeout("2 seconds"));
|
||||
|
||||
yield* adapter.interruptTurn(threadId).pipe(Effect.timeout("2 seconds"));
|
||||
const followUpFiber = yield* adapter
|
||||
.sendTurn({ threadId, input: "follow up", attachments: [] })
|
||||
.pipe(Effect.forkChild);
|
||||
yield* waitForJsonLogCount(
|
||||
requestLogPath,
|
||||
(request) => request.method === "session/prompt",
|
||||
2,
|
||||
80,
|
||||
).pipe(Effect.timeout("2 seconds"));
|
||||
const secondTurnId = yield* Deferred.await(secondTurnStarted).pipe(
|
||||
Effect.timeout("2 seconds"),
|
||||
);
|
||||
yield* Fiber.join(firstSendFiber).pipe(Effect.timeout("2 seconds"));
|
||||
const steeredFollowUpFiber = yield* adapter
|
||||
.sendTurn({ threadId, input: "steer follow up", attachments: [] })
|
||||
.pipe(Effect.forkChild);
|
||||
for (let attempt = 0; attempt < 10; attempt += 1) {
|
||||
yield* Effect.yieldNow;
|
||||
}
|
||||
|
||||
yield* adapter.interruptTurn(threadId).pipe(Effect.timeout("2 seconds"));
|
||||
const steeredFollowUp = yield* Fiber.join(steeredFollowUpFiber).pipe(
|
||||
Effect.timeout("2 seconds"),
|
||||
);
|
||||
const followUp = yield* Fiber.join(followUpFiber).pipe(Effect.timeout("2 seconds"));
|
||||
assert.notEqual(secondTurnId, firstTurnId);
|
||||
assert.equal(String(steeredFollowUp.turnId), secondTurnId);
|
||||
yield* Deferred.await(twoTurnsCompleted).pipe(Effect.timeout("2 seconds"));
|
||||
yield* Fiber.interrupt(eventFiber);
|
||||
|
||||
assert.equal(String(followUp.turnId), secondTurnId);
|
||||
const completed = events.filter(
|
||||
(event) => String(event.threadId) === String(threadId) && event.type === "turn.completed",
|
||||
);
|
||||
assert.lengthOf(completed, 2);
|
||||
assert.equal(String(completed[0]?.turnId), firstTurnId);
|
||||
if (completed[0]?.type === "turn.completed") {
|
||||
assert.equal(completed[0].payload.state, "cancelled");
|
||||
assert.equal(completed[0].payload.stopReason, "cancelled");
|
||||
}
|
||||
assert.equal(String(completed[1]?.turnId), secondTurnId);
|
||||
if (completed[1]?.type === "turn.completed") {
|
||||
assert.equal(completed[1].payload.state, "cancelled");
|
||||
assert.equal(completed[1].payload.stopReason, "cancelled");
|
||||
}
|
||||
|
||||
const requests = yield* Effect.promise(() => readJsonLines(requestLogPath));
|
||||
assert.lengthOf(
|
||||
requests.filter((request) => request.method === "session/prompt"),
|
||||
3,
|
||||
);
|
||||
yield* adapter.stopSession(threadId);
|
||||
}).pipe(TestClock.withLive),
|
||||
);
|
||||
|
||||
it.effect("resolves a pending permission before completing a normally returned turn", () =>
|
||||
Effect.gen(function* () {
|
||||
const adapter = yield* CursorAdapter;
|
||||
const settings = yield* ServerSettingsService;
|
||||
const threadId = ThreadId.make("cursor-terminal-permission");
|
||||
const events: Array<ProviderRuntimeEvent> = [];
|
||||
const completed = yield* Deferred.make<void>();
|
||||
const wrapperPath = yield* Effect.promise(() => makeTerminalCallbackWrapper("permission"));
|
||||
yield* settings.updateSettings({ providers: { cursor: { binaryPath: wrapperPath } } });
|
||||
|
||||
const eventsFiber = yield* Stream.runForEach(adapter.streamEvents, (event) => {
|
||||
if (String(event.threadId) !== String(threadId)) return Effect.void;
|
||||
events.push(event);
|
||||
return event.type === "turn.completed"
|
||||
? Deferred.succeed(completed, undefined).pipe(Effect.ignore)
|
||||
: Effect.void;
|
||||
}).pipe(Effect.forkChild);
|
||||
|
||||
yield* adapter.startSession({
|
||||
threadId,
|
||||
provider: ProviderDriverKind.make("cursor"),
|
||||
cwd: process.cwd(),
|
||||
runtimeMode: "approval-required",
|
||||
});
|
||||
yield* adapter.sendTurn({
|
||||
threadId,
|
||||
input: "finish without permission response",
|
||||
attachments: [],
|
||||
});
|
||||
yield* Deferred.await(completed);
|
||||
yield* Fiber.interrupt(eventsFiber);
|
||||
|
||||
const relevant = events.filter(
|
||||
(event) =>
|
||||
event.type === "request.opened" ||
|
||||
event.type === "request.resolved" ||
|
||||
event.type === "turn.completed",
|
||||
);
|
||||
assert.deepStrictEqual(
|
||||
relevant.map((event) => event.type),
|
||||
["request.opened", "request.resolved", "turn.completed"],
|
||||
);
|
||||
const resolved = relevant[1];
|
||||
assert.equal(resolved?.type, "request.resolved");
|
||||
if (resolved?.type === "request.resolved") assert.equal(resolved.payload.decision, "cancel");
|
||||
yield* adapter.stopSession(threadId);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("settles a pending callback when the terminal prompt fails", () =>
|
||||
Effect.gen(function* () {
|
||||
const adapter = yield* CursorAdapter;
|
||||
const settings = yield* ServerSettingsService;
|
||||
const threadId = ThreadId.make("cursor-terminal-failure");
|
||||
const events: Array<ProviderRuntimeEvent> = [];
|
||||
const requested = yield* Deferred.make<ApprovalRequestId>();
|
||||
const resolved = yield* Deferred.make<void>();
|
||||
const wrapperPath = yield* Effect.promise(() =>
|
||||
makeTerminalCallbackWrapper("permission", "failure"),
|
||||
);
|
||||
yield* settings.updateSettings({ providers: { cursor: { binaryPath: wrapperPath } } });
|
||||
|
||||
const eventsFiber = yield* Stream.runForEach(adapter.streamEvents, (event) => {
|
||||
if (String(event.threadId) !== String(threadId)) return Effect.void;
|
||||
events.push(event);
|
||||
if (event.type === "request.opened") {
|
||||
return Deferred.succeed(requested, ApprovalRequestId.make(String(event.requestId))).pipe(
|
||||
Effect.ignore,
|
||||
);
|
||||
}
|
||||
if (event.type === "request.resolved") {
|
||||
return Deferred.succeed(resolved, undefined).pipe(Effect.ignore);
|
||||
}
|
||||
return Effect.void;
|
||||
}).pipe(Effect.forkChild);
|
||||
|
||||
yield* adapter.startSession({
|
||||
threadId,
|
||||
provider: ProviderDriverKind.make("cursor"),
|
||||
cwd: process.cwd(),
|
||||
runtimeMode: "approval-required",
|
||||
});
|
||||
const sendTurnFiber = yield* adapter
|
||||
.sendTurn({
|
||||
threadId,
|
||||
input: "fail with a pending permission",
|
||||
attachments: [],
|
||||
})
|
||||
.pipe(Effect.forkChild);
|
||||
|
||||
const requestId = yield* Deferred.await(requested);
|
||||
const sendTurnExit = yield* Fiber.await(sendTurnFiber);
|
||||
yield* Deferred.await(resolved);
|
||||
const lateResponseExit = yield* adapter
|
||||
.respondToRequest(threadId, requestId, "accept")
|
||||
.pipe(Effect.exit);
|
||||
assert.equal(sendTurnExit._tag, "Failure");
|
||||
assert.equal(lateResponseExit._tag, "Failure");
|
||||
assert.deepStrictEqual(
|
||||
events
|
||||
.filter(
|
||||
(event) =>
|
||||
event.type === "request.opened" ||
|
||||
event.type === "request.resolved" ||
|
||||
event.type === "turn.completed",
|
||||
)
|
||||
.map((event) => event.type),
|
||||
["request.opened", "request.resolved"],
|
||||
);
|
||||
|
||||
yield* Fiber.interrupt(eventsFiber);
|
||||
yield* adapter.stopSession(threadId);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("settles a pending callback when sendTurn is interrupted", () =>
|
||||
Effect.gen(function* () {
|
||||
const adapter = yield* CursorAdapter;
|
||||
const settings = yield* ServerSettingsService;
|
||||
const threadId = ThreadId.make("cursor-terminal-fiber-interruption");
|
||||
const events: Array<ProviderRuntimeEvent> = [];
|
||||
const requested = yield* Deferred.make<ApprovalRequestId>();
|
||||
const resolved = yield* Deferred.make<void>();
|
||||
const wrapperPath = yield* Effect.promise(() =>
|
||||
makeTerminalCallbackWrapper("permission", "hang"),
|
||||
);
|
||||
yield* settings.updateSettings({ providers: { cursor: { binaryPath: wrapperPath } } });
|
||||
|
||||
const eventsFiber = yield* Stream.runForEach(adapter.streamEvents, (event) => {
|
||||
if (String(event.threadId) !== String(threadId)) return Effect.void;
|
||||
events.push(event);
|
||||
if (event.type === "request.opened") {
|
||||
return Deferred.succeed(requested, ApprovalRequestId.make(String(event.requestId))).pipe(
|
||||
Effect.ignore,
|
||||
);
|
||||
}
|
||||
if (event.type === "request.resolved") {
|
||||
return Deferred.succeed(resolved, undefined).pipe(Effect.ignore);
|
||||
}
|
||||
return Effect.void;
|
||||
}).pipe(Effect.forkChild);
|
||||
|
||||
yield* adapter.startSession({
|
||||
threadId,
|
||||
provider: ProviderDriverKind.make("cursor"),
|
||||
cwd: process.cwd(),
|
||||
runtimeMode: "approval-required",
|
||||
});
|
||||
const sendTurnFiber = yield* adapter
|
||||
.sendTurn({
|
||||
threadId,
|
||||
input: "interrupt with a pending permission",
|
||||
attachments: [],
|
||||
})
|
||||
.pipe(Effect.forkChild);
|
||||
|
||||
const requestId = yield* Deferred.await(requested);
|
||||
yield* Fiber.interrupt(sendTurnFiber);
|
||||
yield* Deferred.await(resolved);
|
||||
const lateResponseExit = yield* adapter
|
||||
.respondToRequest(threadId, requestId, "accept")
|
||||
.pipe(Effect.exit);
|
||||
assert.equal(lateResponseExit._tag, "Failure");
|
||||
assert.deepStrictEqual(
|
||||
events
|
||||
.filter(
|
||||
(event) =>
|
||||
event.type === "request.opened" ||
|
||||
event.type === "request.resolved" ||
|
||||
event.type === "turn.completed",
|
||||
)
|
||||
.map((event) => event.type),
|
||||
["request.opened", "request.resolved"],
|
||||
);
|
||||
|
||||
yield* Fiber.interrupt(eventsFiber);
|
||||
yield* adapter.stopSession(threadId);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("resolves a pending question before completing a normally returned turn", () =>
|
||||
Effect.gen(function* () {
|
||||
const adapter = yield* CursorAdapter;
|
||||
const settings = yield* ServerSettingsService;
|
||||
const threadId = ThreadId.make("cursor-terminal-question");
|
||||
const events: Array<ProviderRuntimeEvent> = [];
|
||||
const completed = yield* Deferred.make<void>();
|
||||
const wrapperPath = yield* Effect.promise(() => makeTerminalCallbackWrapper("question"));
|
||||
yield* settings.updateSettings({ providers: { cursor: { binaryPath: wrapperPath } } });
|
||||
|
||||
const eventsFiber = yield* Stream.runForEach(adapter.streamEvents, (event) => {
|
||||
if (String(event.threadId) !== String(threadId)) return Effect.void;
|
||||
events.push(event);
|
||||
return event.type === "turn.completed"
|
||||
? Deferred.succeed(completed, undefined).pipe(Effect.ignore)
|
||||
: Effect.void;
|
||||
}).pipe(Effect.forkChild);
|
||||
|
||||
yield* adapter.startSession({
|
||||
threadId,
|
||||
provider: ProviderDriverKind.make("cursor"),
|
||||
cwd: process.cwd(),
|
||||
runtimeMode: "full-access",
|
||||
});
|
||||
yield* adapter.sendTurn({
|
||||
threadId,
|
||||
input: "finish without question response",
|
||||
attachments: [],
|
||||
});
|
||||
yield* Deferred.await(completed);
|
||||
yield* Fiber.interrupt(eventsFiber);
|
||||
|
||||
const relevant = events.filter(
|
||||
(event) =>
|
||||
event.type === "user-input.requested" ||
|
||||
event.type === "user-input.resolved" ||
|
||||
event.type === "turn.completed",
|
||||
);
|
||||
assert.deepStrictEqual(
|
||||
relevant.map((event) => event.type),
|
||||
["user-input.requested", "user-input.resolved", "turn.completed"],
|
||||
);
|
||||
const resolved = relevant[1];
|
||||
assert.equal(resolved?.type, "user-input.resolved");
|
||||
if (resolved?.type === "user-input.resolved")
|
||||
assert.deepStrictEqual(resolved.payload.answers, {});
|
||||
yield* adapter.stopSession(threadId);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("stopping a session settles pending approval waits", () =>
|
||||
Effect.gen(function* () {
|
||||
const adapter = yield* CursorAdapter;
|
||||
|
||||
@@ -115,11 +115,19 @@ export interface CursorAdapterLiveOptions {
|
||||
|
||||
interface PendingApproval {
|
||||
readonly decision: Deferred.Deferred<ProviderApprovalDecision>;
|
||||
readonly resolutionOffered: Deferred.Deferred<void>;
|
||||
readonly kind: string | "unknown";
|
||||
}
|
||||
|
||||
interface PendingUserInput {
|
||||
readonly answers: Deferred.Deferred<ProviderUserInputAnswers>;
|
||||
readonly resolutionOffered: Deferred.Deferred<void>;
|
||||
}
|
||||
|
||||
interface CallbackLifecycle {
|
||||
readonly semaphore: Semaphore.Semaphore;
|
||||
generation: number;
|
||||
admissionOpen: boolean;
|
||||
}
|
||||
|
||||
interface CursorSessionContext {
|
||||
@@ -137,33 +145,32 @@ interface CursorSessionContext {
|
||||
* >0 means a turn is actively running, so a new sendTurn is a steer that
|
||||
* continues it, and only the last remaining prompt settles the turn. */
|
||||
promptsInFlight: number;
|
||||
readonly callbackLifecycle: CallbackLifecycle;
|
||||
stopped: boolean;
|
||||
}
|
||||
|
||||
function settlePendingApprovalsAsCancelled(
|
||||
pendingApprovals: ReadonlyMap<ApprovalRequestId, PendingApproval>,
|
||||
function settlePendingCallbacks(
|
||||
approvals: ReadonlyArray<PendingApproval>,
|
||||
userInputs: ReadonlyArray<PendingUserInput>,
|
||||
): Effect.Effect<void> {
|
||||
const pendingEntries = Array.from(pendingApprovals.values());
|
||||
return Effect.forEach(
|
||||
pendingEntries,
|
||||
(pending) => Deferred.succeed(pending.decision, "cancel").pipe(Effect.ignore),
|
||||
{
|
||||
return Effect.gen(function* () {
|
||||
yield* Effect.forEach(
|
||||
approvals,
|
||||
(pending) => Deferred.succeed(pending.decision, "cancel").pipe(Effect.ignore),
|
||||
{ discard: true },
|
||||
);
|
||||
yield* Effect.forEach(
|
||||
userInputs,
|
||||
(pending) => Deferred.succeed(pending.answers, {}).pipe(Effect.ignore),
|
||||
{ discard: true },
|
||||
);
|
||||
yield* Effect.forEach(approvals, (pending) => Deferred.await(pending.resolutionOffered), {
|
||||
discard: true,
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
function settlePendingUserInputsAsEmptyAnswers(
|
||||
pendingUserInputs: ReadonlyMap<ApprovalRequestId, PendingUserInput>,
|
||||
): Effect.Effect<void> {
|
||||
const pendingEntries = Array.from(pendingUserInputs.values());
|
||||
return Effect.forEach(
|
||||
pendingEntries,
|
||||
(pending) => Deferred.succeed(pending.answers, {}).pipe(Effect.ignore),
|
||||
{
|
||||
});
|
||||
yield* Effect.forEach(userInputs, (pending) => Deferred.await(pending.resolutionOffered), {
|
||||
discard: true,
|
||||
},
|
||||
);
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
function isRecord(value: unknown): value is Record<string, unknown> {
|
||||
@@ -458,10 +465,21 @@ export function makeCursorAdapter(
|
||||
|
||||
const stopSessionInternal = (ctx: CursorSessionContext) =>
|
||||
Effect.gen(function* () {
|
||||
if (ctx.stopped) return;
|
||||
ctx.stopped = true;
|
||||
yield* settlePendingApprovalsAsCancelled(ctx.pendingApprovals);
|
||||
yield* settlePendingUserInputsAsEmptyAnswers(ctx.pendingUserInputs);
|
||||
const shouldStop = yield* Effect.uninterruptible(
|
||||
ctx.callbackLifecycle.semaphore.withPermit(
|
||||
Effect.gen(function* () {
|
||||
if (ctx.stopped) return false;
|
||||
ctx.stopped = true;
|
||||
ctx.callbackLifecycle.admissionOpen = false;
|
||||
yield* settlePendingCallbacks(
|
||||
Array.from(ctx.pendingApprovals.values()),
|
||||
Array.from(ctx.pendingUserInputs.values()),
|
||||
);
|
||||
return true;
|
||||
}),
|
||||
),
|
||||
);
|
||||
if (!shouldStop) return;
|
||||
if (ctx.notificationFiber) {
|
||||
yield* Fiber.interrupt(ctx.notificationFiber);
|
||||
}
|
||||
@@ -505,6 +523,11 @@ export function makeCursorAdapter(
|
||||
|
||||
const pendingApprovals = new Map<ApprovalRequestId, PendingApproval>();
|
||||
const pendingUserInputs = new Map<ApprovalRequestId, PendingUserInput>();
|
||||
const callbackLifecycle: CallbackLifecycle = {
|
||||
semaphore: yield* Semaphore.make(1),
|
||||
generation: 0,
|
||||
admissionOpen: false,
|
||||
};
|
||||
const sessionScope = yield* Scope.make("sequential");
|
||||
let sessionScopeTransferred = false;
|
||||
yield* Effect.addFinalizer(() =>
|
||||
@@ -571,47 +594,77 @@ export function makeCursorAdapter(
|
||||
),
|
||||
);
|
||||
const started = yield* Effect.gen(function* () {
|
||||
yield* acp.handleExtRequest("cursor/ask_question", CursorAskQuestionRequest, (params) =>
|
||||
mapExtensionFailure(
|
||||
Effect.gen(function* () {
|
||||
yield* logNative(
|
||||
input.threadId,
|
||||
"cursor/ask_question",
|
||||
params,
|
||||
"acp.cursor.extension",
|
||||
);
|
||||
const requestId = ApprovalRequestId.make(yield* randomUUIDv4);
|
||||
const runtimeRequestId = RuntimeRequestId.make(requestId);
|
||||
const answers = yield* Deferred.make<ProviderUserInputAnswers>();
|
||||
pendingUserInputs.set(requestId, { answers });
|
||||
yield* offerRuntimeEvent({
|
||||
type: "user-input.requested",
|
||||
...(yield* makeEventStamp()),
|
||||
provider: PROVIDER,
|
||||
threadId: input.threadId,
|
||||
turnId: ctx?.activeTurnId,
|
||||
requestId: runtimeRequestId,
|
||||
payload: { questions: extractAskQuestions(params) },
|
||||
raw: {
|
||||
source: "acp.cursor.extension",
|
||||
method: "cursor/ask_question",
|
||||
payload: params,
|
||||
},
|
||||
});
|
||||
const resolved = yield* Deferred.await(answers);
|
||||
pendingUserInputs.delete(requestId);
|
||||
yield* offerRuntimeEvent({
|
||||
type: "user-input.resolved",
|
||||
...(yield* makeEventStamp()),
|
||||
provider: PROVIDER,
|
||||
threadId: input.threadId,
|
||||
turnId: ctx?.activeTurnId,
|
||||
requestId: runtimeRequestId,
|
||||
payload: { answers: resolved },
|
||||
});
|
||||
return { answers: resolved };
|
||||
}),
|
||||
),
|
||||
yield* acp.handleExtRequest(
|
||||
"cursor/ask_question",
|
||||
CursorAskQuestionRequest,
|
||||
(params) => {
|
||||
const callbackGeneration = callbackLifecycle.generation;
|
||||
return mapExtensionFailure(
|
||||
Effect.gen(function* () {
|
||||
yield* logNative(
|
||||
input.threadId,
|
||||
"cursor/ask_question",
|
||||
params,
|
||||
"acp.cursor.extension",
|
||||
);
|
||||
const requestId = ApprovalRequestId.make(yield* randomUUIDv4);
|
||||
const runtimeRequestId = RuntimeRequestId.make(requestId);
|
||||
const answers = yield* Deferred.make<ProviderUserInputAnswers>();
|
||||
const resolutionOffered = yield* Deferred.make<void>();
|
||||
const pending: PendingUserInput = { answers, resolutionOffered };
|
||||
return yield* Effect.gen(function* () {
|
||||
const admitted = yield* callbackLifecycle.semaphore.withPermit(
|
||||
Effect.gen(function* () {
|
||||
if (
|
||||
!callbackLifecycle.admissionOpen ||
|
||||
callbackLifecycle.generation !== callbackGeneration ||
|
||||
ctx?.stopped
|
||||
) {
|
||||
return false;
|
||||
}
|
||||
pendingUserInputs.set(requestId, pending);
|
||||
yield* offerRuntimeEvent({
|
||||
type: "user-input.requested",
|
||||
...(yield* makeEventStamp()),
|
||||
provider: PROVIDER,
|
||||
threadId: input.threadId,
|
||||
turnId: ctx?.activeTurnId,
|
||||
requestId: runtimeRequestId,
|
||||
payload: { questions: extractAskQuestions(params) },
|
||||
raw: {
|
||||
source: "acp.cursor.extension",
|
||||
method: "cursor/ask_question",
|
||||
payload: params,
|
||||
},
|
||||
});
|
||||
return true;
|
||||
}),
|
||||
);
|
||||
if (!admitted) {
|
||||
return { answers: {} };
|
||||
}
|
||||
const resolved = yield* Deferred.await(answers);
|
||||
yield* offerRuntimeEvent({
|
||||
type: "user-input.resolved",
|
||||
...(yield* makeEventStamp()),
|
||||
provider: PROVIDER,
|
||||
threadId: input.threadId,
|
||||
turnId: ctx?.activeTurnId,
|
||||
requestId: runtimeRequestId,
|
||||
payload: { answers: resolved },
|
||||
});
|
||||
return { answers: resolved };
|
||||
}).pipe(
|
||||
Effect.ensuring(
|
||||
Effect.sync(() => pendingUserInputs.delete(requestId)).pipe(
|
||||
Effect.andThen(Deferred.succeed(resolutionOffered, undefined)),
|
||||
Effect.ignore,
|
||||
),
|
||||
),
|
||||
);
|
||||
}),
|
||||
);
|
||||
},
|
||||
);
|
||||
yield* acp.handleExtRequest("cursor/create_plan", CursorCreatePlanRequest, (params) =>
|
||||
mapExtensionFailure(
|
||||
@@ -663,8 +716,9 @@ export function makeCursorAdapter(
|
||||
}),
|
||||
),
|
||||
);
|
||||
yield* acp.handleRequestPermission((params) =>
|
||||
mapExtensionFailure(
|
||||
yield* acp.handleRequestPermission((params) => {
|
||||
const callbackGeneration = callbackLifecycle.generation;
|
||||
return mapExtensionFailure(
|
||||
Effect.gen(function* () {
|
||||
yield* logNative(
|
||||
input.threadId,
|
||||
@@ -675,6 +729,17 @@ export function makeCursorAdapter(
|
||||
if (input.runtimeMode === "full-access") {
|
||||
const autoApprovedOptionId = selectAutoApprovedPermissionOption(params);
|
||||
if (autoApprovedOptionId !== undefined) {
|
||||
const admitted = yield* callbackLifecycle.semaphore.withPermit(
|
||||
Effect.sync(
|
||||
() =>
|
||||
callbackLifecycle.admissionOpen &&
|
||||
callbackLifecycle.generation === callbackGeneration &&
|
||||
!ctx?.stopped,
|
||||
),
|
||||
);
|
||||
if (!admitted) {
|
||||
return { outcome: { outcome: "cancelled" as const } };
|
||||
}
|
||||
return {
|
||||
outcome: {
|
||||
outcome: "selected" as const,
|
||||
@@ -687,53 +752,79 @@ export function makeCursorAdapter(
|
||||
const requestId = ApprovalRequestId.make(yield* randomUUIDv4);
|
||||
const runtimeRequestId = RuntimeRequestId.make(requestId);
|
||||
const decision = yield* Deferred.make<ProviderApprovalDecision>();
|
||||
pendingApprovals.set(requestId, {
|
||||
const resolutionOffered = yield* Deferred.make<void>();
|
||||
const pending: PendingApproval = {
|
||||
decision,
|
||||
resolutionOffered,
|
||||
kind: permissionRequest.kind,
|
||||
});
|
||||
yield* offerRuntimeEvent(
|
||||
makeAcpRequestOpenedEvent({
|
||||
stamp: yield* makeEventStamp(),
|
||||
provider: PROVIDER,
|
||||
threadId: input.threadId,
|
||||
turnId: ctx?.activeTurnId,
|
||||
requestId: runtimeRequestId,
|
||||
permissionRequest,
|
||||
detail:
|
||||
permissionRequest.detail ??
|
||||
encodeJsonStringForDiagnostics(params)?.slice(0, 2000) ??
|
||||
"[unserializable params]",
|
||||
args: params,
|
||||
source: "acp.jsonrpc",
|
||||
method: "session/request_permission",
|
||||
rawPayload: params,
|
||||
}),
|
||||
);
|
||||
const resolved = yield* Deferred.await(decision);
|
||||
pendingApprovals.delete(requestId);
|
||||
yield* offerRuntimeEvent(
|
||||
makeAcpRequestResolvedEvent({
|
||||
stamp: yield* makeEventStamp(),
|
||||
provider: PROVIDER,
|
||||
threadId: input.threadId,
|
||||
turnId: ctx?.activeTurnId,
|
||||
requestId: runtimeRequestId,
|
||||
permissionRequest,
|
||||
decision: resolved,
|
||||
}),
|
||||
);
|
||||
return {
|
||||
outcome:
|
||||
resolved === "cancel"
|
||||
? ({ outcome: "cancelled" } as const)
|
||||
: {
|
||||
outcome: "selected" as const,
|
||||
optionId: acpPermissionOutcome(resolved),
|
||||
},
|
||||
};
|
||||
return yield* Effect.gen(function* () {
|
||||
const admitted = yield* callbackLifecycle.semaphore.withPermit(
|
||||
Effect.gen(function* () {
|
||||
if (
|
||||
!callbackLifecycle.admissionOpen ||
|
||||
callbackLifecycle.generation !== callbackGeneration ||
|
||||
ctx?.stopped
|
||||
) {
|
||||
return false;
|
||||
}
|
||||
pendingApprovals.set(requestId, pending);
|
||||
yield* offerRuntimeEvent(
|
||||
makeAcpRequestOpenedEvent({
|
||||
stamp: yield* makeEventStamp(),
|
||||
provider: PROVIDER,
|
||||
threadId: input.threadId,
|
||||
turnId: ctx?.activeTurnId,
|
||||
requestId: runtimeRequestId,
|
||||
permissionRequest,
|
||||
detail:
|
||||
permissionRequest.detail ??
|
||||
encodeJsonStringForDiagnostics(params)?.slice(0, 2000) ??
|
||||
"[unserializable params]",
|
||||
args: params,
|
||||
source: "acp.jsonrpc",
|
||||
method: "session/request_permission",
|
||||
rawPayload: params,
|
||||
}),
|
||||
);
|
||||
return true;
|
||||
}),
|
||||
);
|
||||
if (!admitted) {
|
||||
return { outcome: { outcome: "cancelled" as const } };
|
||||
}
|
||||
const resolved = yield* Deferred.await(decision);
|
||||
yield* offerRuntimeEvent(
|
||||
makeAcpRequestResolvedEvent({
|
||||
stamp: yield* makeEventStamp(),
|
||||
provider: PROVIDER,
|
||||
threadId: input.threadId,
|
||||
turnId: ctx?.activeTurnId,
|
||||
requestId: runtimeRequestId,
|
||||
permissionRequest,
|
||||
decision: resolved,
|
||||
}),
|
||||
);
|
||||
return {
|
||||
outcome:
|
||||
resolved === "cancel"
|
||||
? ({ outcome: "cancelled" } as const)
|
||||
: {
|
||||
outcome: "selected" as const,
|
||||
optionId: acpPermissionOutcome(resolved),
|
||||
},
|
||||
};
|
||||
}).pipe(
|
||||
Effect.ensuring(
|
||||
Effect.sync(() => pendingApprovals.delete(requestId)).pipe(
|
||||
Effect.andThen(Deferred.succeed(resolutionOffered, undefined)),
|
||||
Effect.ignore,
|
||||
),
|
||||
),
|
||||
);
|
||||
}),
|
||||
),
|
||||
);
|
||||
);
|
||||
});
|
||||
return yield* acp.start();
|
||||
}).pipe(
|
||||
Effect.mapError((error) =>
|
||||
@@ -779,6 +870,7 @@ export function makeCursorAdapter(
|
||||
lastPlanFingerprint: undefined,
|
||||
activeTurnId: undefined,
|
||||
promptsInFlight: 0,
|
||||
callbackLifecycle,
|
||||
stopped: false,
|
||||
};
|
||||
|
||||
@@ -910,15 +1002,60 @@ export function makeCursorAdapter(
|
||||
const sendTurn: CursorAdapterShape["sendTurn"] = (input) =>
|
||||
Effect.gen(function* () {
|
||||
const ctx = yield* requireSession(input.threadId);
|
||||
// A sendTurn while a prompt is in flight is a steer: the agent folds
|
||||
// the new prompt into the ongoing work, so the active turn id is
|
||||
// reused instead of opening a new turn.
|
||||
const steeringTurnId = ctx.promptsInFlight > 0 ? ctx.activeTurnId : undefined;
|
||||
const turnId = steeringTurnId ?? TurnId.make(yield* randomUUIDv4);
|
||||
// Count this prompt immediately so a superseded in-flight prompt
|
||||
// resolving from here on does not settle the turn; the matching
|
||||
// decrement is the `ensuring` below.
|
||||
ctx.promptsInFlight += 1;
|
||||
const candidateTurnId = TurnId.make(yield* randomUUIDv4);
|
||||
const admission = yield* ctx.callbackLifecycle.semaphore.withPermit(
|
||||
Effect.gen(function* () {
|
||||
if (ctx.stopped) {
|
||||
return yield* new ProviderAdapterSessionNotFoundError({
|
||||
provider: PROVIDER,
|
||||
threadId: input.threadId,
|
||||
});
|
||||
}
|
||||
// A prompt sent while another is in flight steers the active turn.
|
||||
const startsTurn = ctx.promptsInFlight === 0;
|
||||
if (startsTurn) {
|
||||
ctx.callbackLifecycle.generation += 1;
|
||||
ctx.callbackLifecycle.admissionOpen = true;
|
||||
ctx.activeTurnId = candidateTurnId;
|
||||
ctx.lastPlanFingerprint = undefined;
|
||||
}
|
||||
// Count it immediately so an older prompt cannot settle the shared turn.
|
||||
ctx.promptsInFlight += 1;
|
||||
return {
|
||||
generation: ctx.callbackLifecycle.generation,
|
||||
startsTurn,
|
||||
turnId: ctx.activeTurnId ?? candidateTurnId,
|
||||
};
|
||||
}),
|
||||
);
|
||||
const { generation, startsTurn, turnId } = admission;
|
||||
let promptFinalized = false;
|
||||
|
||||
const finalizePrompt = (
|
||||
onLastPrompt?: () => Effect.Effect<void, ProviderAdapterRequestError>,
|
||||
): Effect.Effect<boolean, ProviderAdapterRequestError> =>
|
||||
Effect.uninterruptible(
|
||||
ctx.callbackLifecycle.semaphore.withPermit(
|
||||
Effect.gen(function* () {
|
||||
if (promptFinalized) return false;
|
||||
promptFinalized = true;
|
||||
if (ctx.callbackLifecycle.generation !== generation) return false;
|
||||
ctx.promptsInFlight = Math.max(0, ctx.promptsInFlight - 1);
|
||||
// Only the final prompt for this generation may settle and complete the turn.
|
||||
if (ctx.promptsInFlight !== 0) return false;
|
||||
|
||||
ctx.callbackLifecycle.admissionOpen = false;
|
||||
yield* settlePendingCallbacks(
|
||||
Array.from(ctx.pendingApprovals.values()),
|
||||
Array.from(ctx.pendingUserInputs.values()),
|
||||
);
|
||||
if (!ctx.stopped && onLastPrompt) {
|
||||
yield* onLastPrompt();
|
||||
}
|
||||
return true;
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
return yield* Effect.gen(function* () {
|
||||
const turnModelSelection =
|
||||
@@ -939,17 +1076,13 @@ export function makeCursorAdapter(
|
||||
mapError: ({ cause, method }) =>
|
||||
mapAcpToAdapterError(PROVIDER, input.threadId, method, cause),
|
||||
});
|
||||
ctx.activeTurnId = turnId;
|
||||
if (steeringTurnId === undefined) {
|
||||
ctx.lastPlanFingerprint = undefined;
|
||||
}
|
||||
ctx.session = {
|
||||
...ctx.session,
|
||||
activeTurnId: turnId,
|
||||
updatedAt: yield* nowIso,
|
||||
};
|
||||
|
||||
if (steeringTurnId === undefined) {
|
||||
if (startsTurn) {
|
||||
yield* offerRuntimeEvent({
|
||||
type: "turn.started",
|
||||
...(yield* makeEventStamp()),
|
||||
@@ -1027,42 +1160,53 @@ export function makeCursorAdapter(
|
||||
model: resolvedModel,
|
||||
};
|
||||
|
||||
// Only the last remaining prompt settles the turn — a steer-
|
||||
// superseded prompt resolving (usually cancelled) while another is
|
||||
// in flight or pending must leave the merged turn running.
|
||||
if (ctx.promptsInFlight === 1) {
|
||||
yield* offerRuntimeEvent({
|
||||
type: "turn.completed",
|
||||
...(yield* makeEventStamp()),
|
||||
provider: PROVIDER,
|
||||
threadId: input.threadId,
|
||||
turnId,
|
||||
payload: {
|
||||
state: result.stopReason === "cancelled" ? "cancelled" : "completed",
|
||||
stopReason: result.stopReason ?? null,
|
||||
},
|
||||
});
|
||||
}
|
||||
yield* finalizePrompt(() =>
|
||||
makeEventStamp().pipe(
|
||||
Effect.flatMap((stamp) =>
|
||||
offerRuntimeEvent({
|
||||
type: "turn.completed",
|
||||
...stamp,
|
||||
provider: PROVIDER,
|
||||
threadId: input.threadId,
|
||||
turnId,
|
||||
payload: {
|
||||
state: result.stopReason === "cancelled" ? "cancelled" : "completed",
|
||||
stopReason: result.stopReason ?? null,
|
||||
},
|
||||
}),
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
return {
|
||||
threadId: input.threadId,
|
||||
turnId,
|
||||
resumeCursor: ctx.session.resumeCursor,
|
||||
};
|
||||
}).pipe(
|
||||
Effect.ensuring(
|
||||
Effect.sync(() => {
|
||||
ctx.promptsInFlight = Math.max(0, ctx.promptsInFlight - 1);
|
||||
}),
|
||||
),
|
||||
);
|
||||
}).pipe(Effect.ensuring(finalizePrompt().pipe(Effect.ignore)));
|
||||
});
|
||||
|
||||
const interruptTurn: CursorAdapterShape["interruptTurn"] = (threadId) =>
|
||||
Effect.gen(function* () {
|
||||
const ctx = yield* requireSession(threadId);
|
||||
yield* settlePendingApprovalsAsCancelled(ctx.pendingApprovals);
|
||||
yield* settlePendingUserInputsAsEmptyAnswers(ctx.pendingUserInputs);
|
||||
const interruptedTurnId = yield* Effect.uninterruptible(
|
||||
ctx.callbackLifecycle.semaphore.withPermit(
|
||||
Effect.gen(function* () {
|
||||
const turnId = ctx.promptsInFlight > 0 ? ctx.activeTurnId : undefined;
|
||||
ctx.callbackLifecycle.admissionOpen = false;
|
||||
yield* settlePendingCallbacks(
|
||||
Array.from(ctx.pendingApprovals.values()),
|
||||
Array.from(ctx.pendingUserInputs.values()),
|
||||
);
|
||||
if (turnId) {
|
||||
ctx.promptsInFlight = 0;
|
||||
ctx.callbackLifecycle.generation += 1;
|
||||
ctx.lastPlanFingerprint = undefined;
|
||||
}
|
||||
return turnId;
|
||||
}),
|
||||
),
|
||||
);
|
||||
yield* Effect.ignore(
|
||||
ctx.acp.cancel.pipe(
|
||||
Effect.mapError((error) =>
|
||||
@@ -1070,6 +1214,20 @@ export function makeCursorAdapter(
|
||||
),
|
||||
),
|
||||
);
|
||||
if (interruptedTurnId && !ctx.stopped) {
|
||||
yield* makeEventStamp().pipe(
|
||||
Effect.flatMap((stamp) =>
|
||||
offerRuntimeEvent({
|
||||
type: "turn.completed",
|
||||
...stamp,
|
||||
provider: PROVIDER,
|
||||
threadId,
|
||||
turnId: interruptedTurnId,
|
||||
payload: { state: "cancelled", stopReason: "cancelled" },
|
||||
}),
|
||||
),
|
||||
);
|
||||
}
|
||||
});
|
||||
|
||||
const respondToRequest: CursorAdapterShape["respondToRequest"] = (
|
||||
@@ -1087,7 +1245,14 @@ export function makeCursorAdapter(
|
||||
detail: `Unknown pending approval request: ${requestId}`,
|
||||
});
|
||||
}
|
||||
yield* Deferred.succeed(pending.decision, decision);
|
||||
const accepted = yield* Deferred.succeed(pending.decision, decision);
|
||||
if (!accepted) {
|
||||
return yield* new ProviderAdapterRequestError({
|
||||
provider: PROVIDER,
|
||||
method: "session/request_permission",
|
||||
detail: `Approval request is no longer pending: ${requestId}`,
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
const respondToUserInput: CursorAdapterShape["respondToUserInput"] = (
|
||||
@@ -1105,7 +1270,14 @@ export function makeCursorAdapter(
|
||||
detail: `Unknown pending user-input request: ${requestId}`,
|
||||
});
|
||||
}
|
||||
yield* Deferred.succeed(pending.answers, answers);
|
||||
const accepted = yield* Deferred.succeed(pending.answers, answers);
|
||||
if (!accepted) {
|
||||
return yield* new ProviderAdapterRequestError({
|
||||
provider: PROVIDER,
|
||||
method: "cursor/ask_question",
|
||||
detail: `User-input request is no longer pending: ${requestId}`,
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
const readThread: CursorAdapterShape["readThread"] = (threadId) =>
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import { describe, expect, it } from "vite-plus/test";
|
||||
|
||||
import {
|
||||
areFontAdvancesMonospace,
|
||||
clampCodeFontSize,
|
||||
clampInterfaceFontSize,
|
||||
clampPromptFontSize,
|
||||
@@ -9,8 +10,22 @@ import {
|
||||
appearanceFontStack,
|
||||
cssFontFamilies,
|
||||
resolveDefaultFamilyLabel,
|
||||
resolveTerminalFontPreference,
|
||||
} from "./appearanceFonts";
|
||||
|
||||
describe("areFontAdvancesMonospace", () => {
|
||||
it("accepts a fixed advance and rejects any proportional glyph", () => {
|
||||
expect(areFontAdvancesMonospace([10, 10, 10, 10])).toBe(true);
|
||||
expect(areFontAdvancesMonospace([10, 10, 7, 10])).toBe(false);
|
||||
expect(areFontAdvancesMonospace([10, 10.02])).toBe(false);
|
||||
});
|
||||
|
||||
it("fails open when canvas metrics are unavailable", () => {
|
||||
expect(areFontAdvancesMonospace([])).toBe(true);
|
||||
expect(areFontAdvancesMonospace([Number.NaN, Number.NaN])).toBe(true);
|
||||
});
|
||||
});
|
||||
|
||||
describe("cssFontFamilies", () => {
|
||||
it("returns null for effectively empty input", () => {
|
||||
expect(cssFontFamilies("")).toBeNull();
|
||||
@@ -54,6 +69,34 @@ describe("appearanceFontStack", () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe("resolveTerminalFontPreference", () => {
|
||||
it("inherits the code font in simple mode", () => {
|
||||
expect(
|
||||
resolveTerminalFontPreference({ advanced: false, code: "Fira Code", terminal: "" }),
|
||||
).toBe("Fira Code");
|
||||
expect(
|
||||
resolveTerminalFontPreference({
|
||||
advanced: false,
|
||||
code: "Fira Code",
|
||||
terminal: "Berkeley Mono",
|
||||
}),
|
||||
).toBe("Fira Code");
|
||||
});
|
||||
|
||||
it("keeps code and terminal fonts independent in advanced mode", () => {
|
||||
expect(resolveTerminalFontPreference({ advanced: true, code: "Fira Code", terminal: "" })).toBe(
|
||||
"",
|
||||
);
|
||||
expect(
|
||||
resolveTerminalFontPreference({
|
||||
advanced: true,
|
||||
code: "Fira Code",
|
||||
terminal: "Berkeley Mono",
|
||||
}),
|
||||
).toBe("Berkeley Mono");
|
||||
});
|
||||
});
|
||||
|
||||
describe("font size clamping", () => {
|
||||
it("keeps sizes inside the ranges the UI can absorb", () => {
|
||||
expect(clampInterfaceFontSize(16)).toBe(16);
|
||||
|
||||
@@ -25,6 +25,22 @@ export const DEFAULT_SANS_FONT_STACK =
|
||||
export const DEFAULT_CODE_FONT_STACK =
|
||||
'"SF Mono", "SFMono-Regular", Menlo, Consolas, "Liberation Mono", monospace';
|
||||
|
||||
export const TYPOGRAPHY_ADVANCED_STORAGE_KEY = "t3code:typography-advanced";
|
||||
|
||||
/**
|
||||
* Simple typography treats the terminal as another monospace surface. In
|
||||
* Advanced mode an empty terminal preference means the terminal default,
|
||||
* keeping later code-font changes isolated to code surfaces.
|
||||
*/
|
||||
export function resolveTerminalFontPreference(input: {
|
||||
readonly advanced: boolean;
|
||||
readonly code: string;
|
||||
readonly terminal: string;
|
||||
}): string {
|
||||
if (input.advanced) return input.terminal;
|
||||
return input.code;
|
||||
}
|
||||
|
||||
function quoteFontFamilyName(name: string): string {
|
||||
const bare = name.trim();
|
||||
if (bare.length === 0) return "";
|
||||
@@ -165,6 +181,22 @@ export function isFontFamilyAvailable(family: string): boolean {
|
||||
}
|
||||
}
|
||||
|
||||
const MONOSPACE_PROBE_VARIANTS = ["normal 400", "normal 700", "italic 400", "italic 700"] as const;
|
||||
const MONOSPACE_PROBE_GLYPHS = ["i", "M", "W", "0", "@", "#", ".", " "] as const;
|
||||
const MONOSPACE_ADVANCE_TOLERANCE = 0.01;
|
||||
|
||||
export function areFontAdvancesMonospace(advances: readonly number[]): boolean {
|
||||
const reference = advances[0];
|
||||
if (
|
||||
reference === undefined ||
|
||||
reference <= 0 ||
|
||||
advances.some((advance) => !Number.isFinite(advance) || advance <= 0)
|
||||
) {
|
||||
return true;
|
||||
}
|
||||
return advances.every((advance) => Math.abs(advance - reference) < MONOSPACE_ADVANCE_TOLERANCE);
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether a family renders every character on the same advance. Cell-grid
|
||||
* surfaces (the terminal) require this: a proportional face draws its text
|
||||
@@ -182,13 +214,15 @@ export function isMonospaceFamily(family: string): boolean {
|
||||
fontProbeContext = document.createElement("canvas").getContext("2d");
|
||||
}
|
||||
if (fontProbeContext === null) return true;
|
||||
const context = fontProbeContext;
|
||||
// Fall back to a generic mono so an absent face measures as monospace and
|
||||
// is left for the normal fallback chain to resolve.
|
||||
fontProbeContext.font = `32px ${families}, monospace`;
|
||||
const narrow = fontProbeContext.measureText("i").width;
|
||||
const wide = fontProbeContext.measureText("M").width;
|
||||
if (!Number.isFinite(narrow) || !Number.isFinite(wide) || wide === 0) return true;
|
||||
return Math.abs(wide - narrow) < 0.5;
|
||||
for (const variant of MONOSPACE_PROBE_VARIANTS) {
|
||||
context.font = `${variant} 32px ${families}, monospace`;
|
||||
const advances = MONOSPACE_PROBE_GLYPHS.map((glyph) => context.measureText(glyph).width);
|
||||
if (!areFontAdvancesMonospace(advances)) return false;
|
||||
}
|
||||
return true;
|
||||
} catch {
|
||||
return true;
|
||||
}
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -138,9 +138,20 @@ 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";
|
||||
@@ -924,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],
|
||||
@@ -948,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 =
|
||||
|
||||
@@ -18,6 +18,7 @@ import {
|
||||
type ThreadId,
|
||||
} from "@t3tools/contracts";
|
||||
import { getTerminalLabel } from "@t3tools/shared/terminalLabels";
|
||||
import * as Schema from "effect/Schema";
|
||||
import {
|
||||
type PointerEvent as ReactPointerEvent,
|
||||
type ReactNode,
|
||||
@@ -57,6 +58,7 @@ import {
|
||||
} from "../types";
|
||||
import { readLocalApi } from "~/localApi";
|
||||
import { useClientSettings } from "../hooks/useSettings";
|
||||
import { useLocalStorage } from "../hooks/useLocalStorage";
|
||||
import { useAttachedTerminalSession } from "../state/terminalSessions";
|
||||
import { serverEnvironment } from "../state/server";
|
||||
import { previewEnvironment } from "../state/preview";
|
||||
@@ -64,6 +66,7 @@ import { terminalEnvironment } from "../state/terminal";
|
||||
import { openTerminalLinkInPreview } from "./preview/openTerminalLinkInPreview";
|
||||
import { useAtomCommand } from "../state/use-atom-command";
|
||||
import { preventTerminalCloseShortcut } from "../lib/terminalCloseShortcut";
|
||||
import { resolveTerminalFontPreference, TYPOGRAPHY_ADVANCED_STORAGE_KEY } from "../appearanceFonts";
|
||||
|
||||
const MIN_DRAWER_HEIGHT = 180;
|
||||
const MAX_DRAWER_HEIGHT_RATIO = 0.75;
|
||||
@@ -241,6 +244,7 @@ export function shouldHandleTerminalExit(
|
||||
}
|
||||
|
||||
interface TerminalViewportProps {
|
||||
advancedTypography: boolean;
|
||||
threadRef: ScopedThreadRef;
|
||||
threadId: ThreadId;
|
||||
terminalId: string;
|
||||
@@ -264,6 +268,7 @@ interface TerminalLaunchLocation {
|
||||
}
|
||||
|
||||
export function TerminalViewport({
|
||||
advancedTypography,
|
||||
threadRef,
|
||||
threadId,
|
||||
terminalId,
|
||||
@@ -312,10 +317,12 @@ export function TerminalViewport({
|
||||
onAddTerminalContext(selection);
|
||||
});
|
||||
const readTerminalLabel = useEffectEvent(() => terminalLabel);
|
||||
// The terminal inherits the monospace (code) preference unless it has an
|
||||
// override of its own, so one font choice drives every mono surface.
|
||||
const terminalFontFamily = useClientSettings(
|
||||
(settings) => settings.fontFamilyTerminal.trim() || settings.fontFamilyCode,
|
||||
const terminalFontFamily = useClientSettings((settings) =>
|
||||
resolveTerminalFontPreference({
|
||||
advanced: advancedTypography,
|
||||
code: settings.fontFamilyCode,
|
||||
terminal: settings.fontFamilyTerminal,
|
||||
}),
|
||||
);
|
||||
const terminalFontSize = useClientSettings((settings) => settings.fontSizeTerminal);
|
||||
const terminalFontRef = useRef({ family: terminalFontFamily, size: terminalFontSize });
|
||||
@@ -921,6 +928,11 @@ export default function ThreadTerminalDrawer({
|
||||
terminalLaunchLocationsById,
|
||||
}: ThreadTerminalDrawerProps) {
|
||||
const isPanel = mode === "panel";
|
||||
const [advancedTypography] = useLocalStorage(
|
||||
TYPOGRAPHY_ADVANCED_STORAGE_KEY,
|
||||
false,
|
||||
Schema.Boolean,
|
||||
);
|
||||
const controlledDrawerHeight = clampDrawerHeight(height);
|
||||
const [drawerHeightState, setDrawerHeightState] = useState(() => ({
|
||||
threadId,
|
||||
@@ -1357,6 +1369,7 @@ export default function ThreadTerminalDrawer({
|
||||
>
|
||||
<div className="h-full p-1">
|
||||
<TerminalViewport
|
||||
advancedTypography={advancedTypography}
|
||||
threadRef={threadRef}
|
||||
threadId={threadId}
|
||||
terminalId={terminalId}
|
||||
@@ -1384,6 +1397,7 @@ export default function ThreadTerminalDrawer({
|
||||
) : (
|
||||
<div className="h-full p-1">
|
||||
<TerminalViewport
|
||||
advancedTypography={advancedTypography}
|
||||
key={resolvedActiveTerminalId}
|
||||
threadRef={threadRef}
|
||||
threadId={threadId}
|
||||
|
||||
@@ -108,13 +108,24 @@ import { basenameOfPath } from "../../pierre-icons";
|
||||
import { cn, randomUUID } from "~/lib/utils";
|
||||
import { Separator } from "../ui/separator";
|
||||
|
||||
type ComposerCommandMenuPosition = {
|
||||
bottom: number;
|
||||
left: number;
|
||||
maxHeight: number;
|
||||
width: number;
|
||||
};
|
||||
|
||||
function composerCommandMenuPositionsEqual(
|
||||
a: ComposerCommandMenuPosition,
|
||||
b: ComposerCommandMenuPosition,
|
||||
): boolean {
|
||||
return (
|
||||
a.bottom === b.bottom && a.left === b.left && a.maxHeight === b.maxHeight && a.width === b.width
|
||||
);
|
||||
}
|
||||
|
||||
function ComposerCommandMenuLayer(props: { anchor: HTMLElement | null; children: ReactNode }) {
|
||||
const [position, setPosition] = useState<{
|
||||
bottom: number;
|
||||
left: number;
|
||||
maxHeight: number;
|
||||
width: number;
|
||||
} | null>(null);
|
||||
const [position, setPosition] = useState<ComposerCommandMenuPosition | null>(null);
|
||||
|
||||
useLayoutEffect(() => {
|
||||
const anchor = props.anchor;
|
||||
@@ -125,12 +136,15 @@ function ComposerCommandMenuLayer(props: { anchor: HTMLElement | null; children:
|
||||
|
||||
const updatePosition = () => {
|
||||
const rect = anchor.getBoundingClientRect();
|
||||
setPosition({
|
||||
const next = {
|
||||
bottom: window.innerHeight - rect.top + 8,
|
||||
left: rect.left,
|
||||
maxHeight: Math.max(96, rect.top - 24),
|
||||
width: rect.width,
|
||||
});
|
||||
};
|
||||
setPosition((current) =>
|
||||
current && composerCommandMenuPositionsEqual(current, next) ? current : next,
|
||||
);
|
||||
};
|
||||
|
||||
updatePosition();
|
||||
@@ -139,7 +153,16 @@ function ComposerCommandMenuLayer(props: { anchor: HTMLElement | null; children:
|
||||
|
||||
const observer =
|
||||
typeof ResizeObserver === "undefined" ? null : new ResizeObserver(updatePosition);
|
||||
observer?.observe(anchor);
|
||||
if (observer) {
|
||||
// The composer is centered and capped at a max width, so opening a side
|
||||
// panel slides it sideways without ever resizing it. Watching the anchor
|
||||
// alone would leave the menu behind; the ancestors are what shrink, and
|
||||
// they resize on every frame of the panel animation.
|
||||
observer.observe(anchor);
|
||||
for (let element = anchor.parentElement; element; element = element.parentElement) {
|
||||
observer.observe(element);
|
||||
}
|
||||
}
|
||||
|
||||
return () => {
|
||||
observer?.disconnect();
|
||||
|
||||
@@ -101,7 +101,8 @@ export function DraftHeroHeadline({
|
||||
<Menu>
|
||||
<MenuTrigger
|
||||
aria-label={hasResolvedProject ? "Change project" : "Choose a project"}
|
||||
className="pointer-events-auto inline cursor-pointer border-foreground/60 border-b border-dotted text-foreground transition-colors hover:border-foreground/80 focus-visible:rounded-sm focus-visible:outline-hidden focus-visible:ring-2 focus-visible:ring-ring"
|
||||
className="pointer-events-auto inline-block max-w-64 truncate border-foreground/60 border-b border-dotted align-bottom text-foreground transition-colors hover:border-foreground/80 focus-visible:rounded-sm focus-visible:outline-hidden focus-visible:ring-2 focus-visible:ring-ring"
|
||||
title={activeProjectDisplayName ?? undefined}
|
||||
>
|
||||
{activeProjectDisplayName ?? "Choose a project"}
|
||||
</MenuTrigger>
|
||||
@@ -122,7 +123,9 @@ export function DraftHeroHeadline({
|
||||
{projectPickerEntries.map(({ group }) => {
|
||||
return (
|
||||
<MenuRadioItem key={group.projectKey} value={group.projectKey} closeOnClick>
|
||||
<span className="min-w-0 truncate">{group.displayName}</span>
|
||||
<span className="block min-w-0 truncate" title={group.displayName}>
|
||||
{group.displayName}
|
||||
</span>
|
||||
</MenuRadioItem>
|
||||
);
|
||||
})}
|
||||
|
||||
@@ -541,6 +541,10 @@ export const ModelPickerContent = memo(function ModelPickerContent(props: {
|
||||
}
|
||||
return mapping.size > 0 ? mapping : EMPTY_MODEL_JUMP_LABELS;
|
||||
}, [keybindings, modelJumpCommandByKey, modelJumpShortcutContext]);
|
||||
const modelListExtraData = useMemo(
|
||||
() => ({ favoritesSet, modelJumpLabelByKey }),
|
||||
[favoritesSet, modelJumpLabelByKey],
|
||||
);
|
||||
|
||||
useEffect(() => {
|
||||
const onWindowKeyDown = (event: globalThis.KeyboardEvent) => {
|
||||
@@ -710,7 +714,7 @@ export const ModelPickerContent = memo(function ModelPickerContent(props: {
|
||||
<LegendList<string>
|
||||
ref={modelListRef}
|
||||
data={filteredItemKeys}
|
||||
extraData={favoritesSet}
|
||||
extraData={modelListExtraData}
|
||||
keyExtractor={(modelKey) => modelKey}
|
||||
renderItem={({ item: modelKey, index }) => {
|
||||
if (legacySection?.key === modelKey) {
|
||||
|
||||
@@ -129,7 +129,6 @@ export function FontFamilyPicker({
|
||||
if (initialOpen) setOpen(true);
|
||||
// The prop is only meaningful at mount - the control just swapped in
|
||||
// under an active focus - so later changes are deliberately ignored.
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, []);
|
||||
const listRef = useRef<LegendListRef | null>(null);
|
||||
const enumeration = useFontEnumeration();
|
||||
|
||||
@@ -113,18 +113,33 @@ export function CodeFontPreview() {
|
||||
if (htmlByFile === null) return null;
|
||||
return (
|
||||
<div className="mt-1 mb-2 space-y-2">
|
||||
{htmlByFile.map((html, index) => (
|
||||
<StaticDiffHtml key={index} html={html} />
|
||||
{htmlByFile.map((html) => (
|
||||
<StaticDiffHtml key={html} html={html} />
|
||||
))}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
const TERMINAL_PROMPT = "\x1b[2m$\x1b[0m ";
|
||||
// A zsh-style prompt: green arrow, cyan project, blue/red git segment,
|
||||
// yellow dirty marker. It doubles as the echo loop's fresh-line prompt.
|
||||
const TERMINAL_PROMPT =
|
||||
"\x1b[1;32m→\x1b[0m \x1b[1;36mt3code\x1b[0m \x1b[1;34mgit:(\x1b[1;31mmain\x1b[1;34m)\x1b[0m \x1b[1;33m✗\x1b[0m ";
|
||||
// A dev-server startup: brand line, addresses, a test summary, and a READY
|
||||
// badge. Together the lines cover bold, dim, underline, the six accent
|
||||
// colors, and a background cell, so a font choice shows every SGR the
|
||||
// terminal actually renders.
|
||||
const TERMINAL_PREVIEW_TRANSCRIPT =
|
||||
`${TERMINAL_PROMPT}npm run dev\r\n` +
|
||||
"\x1b[32m✓\x1b[0m Ready in 430ms\r\n" +
|
||||
"\x1b[2mLocal:\x1b[0m \x1b[36mhttp://localhost:3000\x1b[0m\r\n" +
|
||||
`${TERMINAL_PROMPT}vpr dev\r\n` +
|
||||
"\r\n" +
|
||||
" \x1b[1;32mVITE\x1b[0m \x1b[32mv7.1.1\x1b[0m \x1b[2mready in\x1b[0m \x1b[1m1.24s\x1b[0m\r\n" +
|
||||
"\r\n" +
|
||||
" \x1b[32m→\x1b[0m \x1b[2mLocal:\x1b[0m \x1b[4;36mhttp://127.0.0.1:5173/\x1b[0m\r\n" +
|
||||
" \x1b[32m→\x1b[0m \x1b[2mNetwork:\x1b[0m \x1b[4;36mhttp://192.168.1.24:5173/\x1b[0m\r\n" +
|
||||
"\r\n" +
|
||||
" \x1b[32m✓ 85 passed\x1b[0m \x1b[33m△ 2 warnings\x1b[0m \x1b[31m✗ 0 failed\x1b[0m\r\n" +
|
||||
"\r\n" +
|
||||
" \x1b[42;30m READY \x1b[0m \x1b[2mwatching for changes — press\x1b[0m \x1b[1mq\x1b[0m \x1b[2mto quit\x1b[0m\r\n" +
|
||||
"\r\n" +
|
||||
TERMINAL_PROMPT;
|
||||
|
||||
/** The surface treats an omitted family or size as "use the built-in default". */
|
||||
@@ -225,7 +240,7 @@ export function TerminalFontPreview({ family, size }: { family: string; size: nu
|
||||
return (
|
||||
<div
|
||||
ref={mountRef}
|
||||
className="relative mt-1 mb-2 h-36 overflow-hidden rounded-lg border border-border"
|
||||
className="relative mt-1 mb-2 h-52 overflow-hidden rounded-lg border border-border"
|
||||
aria-label="Terminal font preview"
|
||||
/>
|
||||
);
|
||||
|
||||
@@ -115,8 +115,9 @@ import {
|
||||
isFontFamilyAvailable,
|
||||
isMonospaceFamily,
|
||||
resolveDefaultFamilyLabel,
|
||||
resolveTerminalFontPreference,
|
||||
TYPOGRAPHY_ADVANCED_STORAGE_KEY,
|
||||
} from "../../appearanceFonts";
|
||||
import { DEFAULT_TERMINAL_FONT_FAMILY } from "~/terminal/ghostty/surface";
|
||||
import { CodeFontPreview, PromptFontPreview, TerminalFontPreview } from "./SettingsFontPreviews";
|
||||
import { discoverInstalledFonts, FontFamilyPicker, useFontEnumeration } from "./FontFamilyPicker";
|
||||
import {
|
||||
@@ -1152,10 +1153,8 @@ function useFontDefaultFamilies() {
|
||||
return {
|
||||
sans: defaults.sans,
|
||||
code: defaults.code,
|
||||
// The composer inherits whatever the interface preference resolves to;
|
||||
// the terminal inherits the monospace preference the same way.
|
||||
// The composer inherits whatever the interface preference resolves to.
|
||||
interfaceFamily: settings.fontFamilySans.trim() || defaults.sans,
|
||||
monoFamily: settings.fontFamilyCode.trim() || defaults.code,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -1245,8 +1244,8 @@ function TerminalFontRow() {
|
||||
return (
|
||||
<FontFamilySettingsRow
|
||||
{...searchableSetting("terminal-font")}
|
||||
description="Terminal output. Follows the monospace font unless set."
|
||||
defaultFamily={defaults.monoFamily}
|
||||
description="Terminal output, independent from code blocks and diffs."
|
||||
defaultFamily={defaults.code}
|
||||
value={settings.fontFamilyTerminal}
|
||||
onValueChange={(fontFamilyTerminal) => updateSettings({ fontFamilyTerminal })}
|
||||
requireMonospace
|
||||
@@ -1259,7 +1258,11 @@ function TerminalFontRow() {
|
||||
}}
|
||||
preview={
|
||||
<TerminalFontPreview
|
||||
family={settings.fontFamilyTerminal.trim() || settings.fontFamilyCode}
|
||||
family={resolveTerminalFontPreference({
|
||||
advanced: true,
|
||||
code: settings.fontFamilyCode,
|
||||
terminal: settings.fontFamilyTerminal,
|
||||
})}
|
||||
size={settings.fontSizeTerminal}
|
||||
/>
|
||||
}
|
||||
@@ -1351,7 +1354,11 @@ function SimpleFontRows() {
|
||||
<>
|
||||
<CodeFontPreview />
|
||||
<TerminalFontPreview
|
||||
family={settings.fontFamilyTerminal.trim() || settings.fontFamilyCode}
|
||||
family={resolveTerminalFontPreference({
|
||||
advanced: false,
|
||||
code: settings.fontFamilyCode,
|
||||
terminal: settings.fontFamilyTerminal,
|
||||
})}
|
||||
size={settings.fontSizeTerminal}
|
||||
/>
|
||||
</>
|
||||
@@ -1371,8 +1378,6 @@ const ADVANCED_TYPOGRAPHY_TARGET_IDS: ReadonlySet<string> = new Set([
|
||||
: []),
|
||||
]);
|
||||
|
||||
const TYPOGRAPHY_ADVANCED_KEY = "t3code:typography-advanced";
|
||||
|
||||
/**
|
||||
* The two-font view by default - one sans, one monospace, each cascading to
|
||||
* every surface it reaches - with an Advanced switch in the section header
|
||||
@@ -1381,7 +1386,11 @@ const TYPOGRAPHY_ADVANCED_KEY = "t3code:typography-advanced";
|
||||
* target exists to scroll to.
|
||||
*/
|
||||
function TypographySection() {
|
||||
const [advanced, setAdvanced] = useLocalStorage(TYPOGRAPHY_ADVANCED_KEY, false, Schema.Boolean);
|
||||
const [advanced, setAdvanced] = useLocalStorage(
|
||||
TYPOGRAPHY_ADVANCED_STORAGE_KEY,
|
||||
false,
|
||||
Schema.Boolean,
|
||||
);
|
||||
const searchTargetId = useSettingsSearchTargetId();
|
||||
// Flip Advanced on once per search jump so the hidden target can mount and
|
||||
// scroll; tracking the handled id lets the user turn it back off without
|
||||
|
||||
@@ -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>
|
||||
))}
|
||||
|
||||
@@ -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";
|
||||
@@ -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 = {
|
||||
|
||||
@@ -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);
|
||||
}
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { describe, expect, it } from "vite-plus/test";
|
||||
import { describe, expect, it, vi } from "vite-plus/test";
|
||||
|
||||
import type { GhosttyCell, GhosttyRow } from "./core";
|
||||
import {
|
||||
@@ -11,15 +11,18 @@ import {
|
||||
isTerminalCopyShortcut,
|
||||
isTerminalLinkPointerGesture,
|
||||
isTerminalPasteShortcut,
|
||||
loadTerminalFontFamily,
|
||||
shouldBlinkTerminalCursor,
|
||||
shouldReportTerminalMouse,
|
||||
shouldShowTerminalLinkHover,
|
||||
terminalGridCellAt,
|
||||
terminalScrollbarGeometry,
|
||||
terminalScrollbarOffsetAtPointer,
|
||||
terminalLinkAtColumn,
|
||||
terminalLinkAtPosition,
|
||||
terminalLinkAtPositionWithRange,
|
||||
terminalContentOriginY,
|
||||
terminalFontFamily,
|
||||
fittedTerminalFontSize,
|
||||
terminalFontSize,
|
||||
terminalWheelArrowData,
|
||||
terminalWheelDeltaRows,
|
||||
@@ -56,6 +59,32 @@ describe("isTerminalAltGraphText", () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe("terminalGridCellAt", () => {
|
||||
const options = {
|
||||
bounds: { left: 100, top: 200 },
|
||||
cols: 3,
|
||||
rows: 2,
|
||||
metrics: { width: 10, height: 20 },
|
||||
padding: 4,
|
||||
originY: 24,
|
||||
};
|
||||
|
||||
it("maps points inside the rendered grid without clamping its padding", () => {
|
||||
expect(terminalGridCellAt({ ...options, clientX: 104, clientY: 224 })).toEqual({
|
||||
x: 0,
|
||||
y: 0,
|
||||
});
|
||||
expect(terminalGridCellAt({ ...options, clientX: 133, clientY: 263 })).toEqual({
|
||||
x: 2,
|
||||
y: 1,
|
||||
});
|
||||
expect(terminalGridCellAt({ ...options, clientX: 103, clientY: 224 })).toBeNull();
|
||||
expect(terminalGridCellAt({ ...options, clientX: 104, clientY: 223 })).toBeNull();
|
||||
expect(terminalGridCellAt({ ...options, clientX: 134, clientY: 224 })).toBeNull();
|
||||
expect(terminalGridCellAt({ ...options, clientX: 104, clientY: 264 })).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
describe("shouldBlinkTerminalCursor", () => {
|
||||
const blinking = {
|
||||
focused: true,
|
||||
@@ -99,6 +128,10 @@ describe("terminalLinkAtColumn", () => {
|
||||
expect(terminalLinkAtColumn(row, 2)).toBe("https://t3.codes");
|
||||
expect(terminalLinkAtColumn(row, cells.length - 1)).toBe("https://t3.codes");
|
||||
expect(terminalLinkAtColumn(row, 0)).toBeNull();
|
||||
expect(terminalLinkAtPositionWithRange([row], 0, 8)?.range).toEqual({
|
||||
start: { x: 2, y: 0 },
|
||||
end: { x: cells.length - 1, y: 0 },
|
||||
});
|
||||
});
|
||||
|
||||
it("uses shared path matching and reconstructs soft-wrapped links", () => {
|
||||
@@ -119,6 +152,13 @@ describe("terminalLinkAtColumn", () => {
|
||||
expect(terminalLinkAtPosition(rows, 1, 4)).toBe("https://example.com/reference");
|
||||
expect(terminalLinkAtPosition(rows, 2, 2)).toBe("~/project/file");
|
||||
expect(terminalLinkAtPosition(rows, 3, 4)).toBe("C:\\repo\\file.ts");
|
||||
expect(terminalLinkAtPositionWithRange(rows, 1, 4)).toEqual({
|
||||
text: "https://example.com/reference",
|
||||
range: {
|
||||
start: { x: 0, y: 0 },
|
||||
end: { x: 12, y: 1 },
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
it("refuses links truncated at the viewport edges instead of mis-resolving", () => {
|
||||
@@ -245,9 +285,37 @@ describe("application mouse reporting", () => {
|
||||
it("maps browser buttons to Ghostty's button enum", () => {
|
||||
expect([0, 1, 2, 3, 4, 5].map(ghosttyMouseButton)).toEqual([1, 3, 2, 4, 5, null]);
|
||||
});
|
||||
|
||||
it("only shows link hover during mouse tracking when the link modifier is held", () => {
|
||||
expect(shouldShowTerminalLinkHover(false, false)).toBe(true);
|
||||
expect(shouldShowTerminalLinkHover(false, true)).toBe(true);
|
||||
expect(shouldShowTerminalLinkHover(true, false)).toBe(false);
|
||||
expect(shouldShowTerminalLinkHover(true, true)).toBe(true);
|
||||
});
|
||||
});
|
||||
|
||||
describe("terminal font resolution", () => {
|
||||
it("validates the requested face after its styles load", async () => {
|
||||
let loaded = false;
|
||||
const load = vi.fn(async () => {
|
||||
loaded = true;
|
||||
return [];
|
||||
});
|
||||
const resolve = vi.fn(() => {
|
||||
expect(loaded).toBe(true);
|
||||
return DEFAULT_TERMINAL_FONT_FAMILY;
|
||||
});
|
||||
|
||||
await expect(
|
||||
loadTerminalFontFamily("Proportional Test", 12, {
|
||||
load,
|
||||
resolve,
|
||||
}),
|
||||
).resolves.toBe(DEFAULT_TERMINAL_FONT_FAMILY);
|
||||
expect(load).toHaveBeenCalledTimes(4);
|
||||
expect(resolve).toHaveBeenCalledWith("Proportional Test");
|
||||
});
|
||||
|
||||
it("keeps the glyph fallbacks behind a custom text face", () => {
|
||||
expect(terminalFontFamily()).toBe(DEFAULT_TERMINAL_FONT_FAMILY);
|
||||
expect(terminalFontFamily(" ")).toBe(DEFAULT_TERMINAL_FONT_FAMILY);
|
||||
@@ -274,24 +342,6 @@ describe("terminal font resolution", () => {
|
||||
expect(terminalFontFamily(" , ")).toBe(DEFAULT_TERMINAL_FONT_FAMILY);
|
||||
});
|
||||
|
||||
it("slides the rendered size down until a full-width grid fits the canvas", () => {
|
||||
// SF Mono-like advance: 0.6em per cell.
|
||||
const cellWidthAt = (size: number) => size * 0.6;
|
||||
// A wide drawer keeps the preference untouched.
|
||||
expect(fittedTerminalFontSize(cellWidthAt, 20, 1140)).toBe(20);
|
||||
// A split pane at the same preference shrinks until 80 columns fit.
|
||||
const fitted = fittedTerminalFontSize(cellWidthAt, 20, 570);
|
||||
expect(fitted).toBeLessThan(20);
|
||||
expect(Math.floor((570 - 8) / cellWidthAt(fitted))).toBeGreaterThanOrEqual(80);
|
||||
// A tiny pane stops at the legibility floor instead of vanishing.
|
||||
expect(fittedTerminalFontSize(cellWidthAt, 20, 220)).toBe(8);
|
||||
// A preference below the floor is honored as-is.
|
||||
expect(fittedTerminalFontSize(cellWidthAt, 6, 220)).toBe(6);
|
||||
// Unmeasured layouts leave the preference alone.
|
||||
expect(fittedTerminalFontSize(cellWidthAt, 14, 0)).toBe(14);
|
||||
expect(fittedTerminalFontSize(() => 0, 14, 600)).toBe(14);
|
||||
});
|
||||
|
||||
it("clamps requested font sizes to the supported range", () => {
|
||||
expect(terminalFontSize()).toBe(DEFAULT_TERMINAL_FONT_SIZE);
|
||||
expect(terminalFontSize(Number.NaN)).toBe(DEFAULT_TERMINAL_FONT_SIZE);
|
||||
|
||||
@@ -10,6 +10,7 @@ import {
|
||||
measureGhosttyCell,
|
||||
renderGhosttySnapshot,
|
||||
terminalGridSize,
|
||||
type GhosttyCellRange,
|
||||
type GhosttyCellMetrics,
|
||||
} from "./renderer";
|
||||
import symbolsFontUrl from "./fonts/SymbolsNerdFontMono-Regular.woff2?url";
|
||||
@@ -35,6 +36,13 @@ const CONTENT_PADDING = 4;
|
||||
const MIN_SCROLLBAR_THUMB_HEIGHT = 18;
|
||||
/** Half a blink cycle: the visible and hidden phases are equally long. */
|
||||
const CURSOR_BLINK_INTERVAL_MS = 500;
|
||||
const TERMINAL_FONT_LOAD_TEXT = "iMW0@# .";
|
||||
const TERMINAL_FONT_LOAD_VARIANTS = [
|
||||
"normal 400",
|
||||
"normal 700",
|
||||
"italic 400",
|
||||
"italic 700",
|
||||
] as const;
|
||||
|
||||
/** Requested terminal font; omitted fields fall back to the defaults. */
|
||||
export interface GhosttyTerminalFont {
|
||||
@@ -77,6 +85,13 @@ function quoteTerminalFontFamilies(list: string): string {
|
||||
.join(", ");
|
||||
}
|
||||
|
||||
function uncheckedTerminalFontFamily(family?: string): string {
|
||||
const custom = family === undefined ? "" : quoteTerminalFontFamilies(family);
|
||||
return custom.length === 0
|
||||
? DEFAULT_TERMINAL_FONT_FAMILY
|
||||
: `${custom}, ${TERMINAL_GLYPH_FALLBACKS}`;
|
||||
}
|
||||
|
||||
export function terminalFontFamily(family?: string): string {
|
||||
// Quote non-ident names ("3270 Nerd Font", "M+ 1m"): an unquoted one makes
|
||||
// the whole canvas font string invalid and the assignment silently no-ops.
|
||||
@@ -87,43 +102,31 @@ export function terminalFontFamily(family?: string): string {
|
||||
// it here rather than render a ragged grid with a stranded cursor.
|
||||
if (!isMonospaceFamily(custom)) return DEFAULT_TERMINAL_FONT_FAMILY;
|
||||
// A custom face keeps the glyph fallbacks so prompt symbols stay covered.
|
||||
return `${custom}, ${TERMINAL_GLYPH_FALLBACKS}`;
|
||||
return uncheckedTerminalFontFamily(custom);
|
||||
}
|
||||
|
||||
/**
|
||||
* Grids narrower than a classic 80-column terminal wrap command output hard,
|
||||
* so the rendered font size follows the canvas width: the preference is the
|
||||
* ceiling, and the size slides down (to a legibility floor) until a full-width
|
||||
* grid fits. A widening pane slides it back up toward the preference.
|
||||
*/
|
||||
const MIN_TERMINAL_FIT_COLUMNS = 80;
|
||||
const MIN_TERMINAL_FIT_FONT_SIZE = 8;
|
||||
|
||||
export function fittedTerminalFontSize(
|
||||
cellWidthAt: (size: number) => number,
|
||||
requested: number,
|
||||
mountWidth: number,
|
||||
): number {
|
||||
const available = mountWidth - CONTENT_PADDING * 2;
|
||||
if (available <= 0) return requested;
|
||||
const floor = Math.min(requested, MIN_TERMINAL_FIT_FONT_SIZE);
|
||||
const fits = (cellWidth: number) =>
|
||||
cellWidth > 0 && Math.floor(available / cellWidth) >= MIN_TERMINAL_FIT_COLUMNS;
|
||||
let cellWidth = cellWidthAt(requested);
|
||||
if (cellWidth <= 0 || fits(cellWidth)) return requested;
|
||||
// The advance scales linearly with size for monospace faces: jump close to
|
||||
// the fitting size, then settle the remaining rounding one step at a time.
|
||||
const targetCellWidth = available / MIN_TERMINAL_FIT_COLUMNS;
|
||||
let size = Math.max(
|
||||
floor,
|
||||
Math.min(requested, Math.floor((requested * targetCellWidth) / cellWidth)),
|
||||
);
|
||||
while (size > floor) {
|
||||
cellWidth = cellWidthAt(size);
|
||||
if (cellWidth <= 0 || fits(cellWidth)) break;
|
||||
size -= 1;
|
||||
/** Load every style the renderer can request, then validate the actual face. */
|
||||
export async function loadTerminalFontFamily(
|
||||
family: string | undefined,
|
||||
size: number,
|
||||
environment?: {
|
||||
readonly load: (font: string, text: string) => Promise<unknown>;
|
||||
readonly resolve: (family: string | undefined) => string;
|
||||
},
|
||||
): Promise<string> {
|
||||
const candidate = uncheckedTerminalFontFamily(family);
|
||||
const load =
|
||||
environment?.load ?? ((font: string, text: string) => document.fonts.load(font, text));
|
||||
try {
|
||||
await Promise.all(
|
||||
TERMINAL_FONT_LOAD_VARIANTS.map((variant) =>
|
||||
load(`${variant} ${size}px ${candidate}`, TERMINAL_FONT_LOAD_TEXT),
|
||||
),
|
||||
);
|
||||
} catch {
|
||||
// The fixed-width fallback stack remains available if a face cannot load.
|
||||
}
|
||||
return size;
|
||||
return (environment?.resolve ?? terminalFontFamily)(family);
|
||||
}
|
||||
|
||||
export function terminalFontSize(size?: number): number {
|
||||
@@ -205,6 +208,28 @@ export function terminalScrollbarOffsetAtPointer(
|
||||
return Math.round((thumbTop / travel) * geometry.maxOffset);
|
||||
}
|
||||
|
||||
export function terminalGridCellAt(options: {
|
||||
bounds: { left: number; top: number };
|
||||
clientX: number;
|
||||
clientY: number;
|
||||
cols: number;
|
||||
rows: number;
|
||||
metrics: Pick<GhosttyCellMetrics, "width" | "height">;
|
||||
padding: number;
|
||||
originY: number;
|
||||
}): { x: number; y: number } | null {
|
||||
const { bounds, clientX, clientY, cols, rows, metrics, padding, originY } = options;
|
||||
const gridX = clientX - bounds.left - padding;
|
||||
const gridY = clientY - bounds.top - originY;
|
||||
if (gridX < 0 || gridY < 0 || gridX >= cols * metrics.width || gridY >= rows * metrics.height) {
|
||||
return null;
|
||||
}
|
||||
return {
|
||||
x: Math.floor(gridX / metrics.width),
|
||||
y: Math.floor(gridY / metrics.height),
|
||||
};
|
||||
}
|
||||
|
||||
function terminalRowText(row: GhosttySnapshot["rowData"][number], trimRight: boolean): string {
|
||||
const text = row.cells.map((cell) => cell.text || " ").join("");
|
||||
return trimRight ? text.trimEnd() : text;
|
||||
@@ -223,6 +248,27 @@ export function terminalLinkAtPosition(
|
||||
rowIndex: number,
|
||||
column: number,
|
||||
): string | null {
|
||||
return terminalLinkAtPositionWithRange(rows, rowIndex, column)?.text ?? null;
|
||||
}
|
||||
|
||||
export interface TerminalLinkWithRange {
|
||||
readonly text: string;
|
||||
readonly range: GhosttyCellRange;
|
||||
}
|
||||
|
||||
function terminalColumnAtOffset(row: GhosttySnapshot["rowData"][number], offset: number): number {
|
||||
for (let column = 0; column < row.cells.length; column += 1) {
|
||||
const nextOffset = terminalColumnOffset(row, column + 1);
|
||||
if (offset < nextOffset) return column;
|
||||
}
|
||||
return Math.max(0, row.cells.length - 1);
|
||||
}
|
||||
|
||||
export function terminalLinkAtPositionWithRange(
|
||||
rows: GhosttySnapshot["rowData"],
|
||||
rowIndex: number,
|
||||
column: number,
|
||||
): TerminalLinkWithRange | null {
|
||||
const wrappedLine = collectWrappedTerminalLinkLine(rowIndex + 1, (index) => {
|
||||
const row = rows[index];
|
||||
if (!row) return null;
|
||||
@@ -251,7 +297,28 @@ export function terminalLinkAtPosition(
|
||||
if (offset >= match.start && offset < match.end) {
|
||||
// A truncated tail must not activate as a complete link.
|
||||
if (match.end === wrappedLine.text.length && continuesBelowViewport) return null;
|
||||
return match.text;
|
||||
const startSegment = wrappedLine.segments.find(
|
||||
(value) => match.start >= value.startIndex && match.start < value.endIndex,
|
||||
);
|
||||
const endSegment = wrappedLine.segments.find(
|
||||
(value) => match.end - 1 >= value.startIndex && match.end - 1 < value.endIndex,
|
||||
);
|
||||
const startRow = startSegment ? rows[startSegment.bufferLineNumber - 1] : undefined;
|
||||
const endRow = endSegment ? rows[endSegment.bufferLineNumber - 1] : undefined;
|
||||
if (!startSegment || !endSegment || !startRow || !endRow) return null;
|
||||
return {
|
||||
text: match.text,
|
||||
range: {
|
||||
start: {
|
||||
x: terminalColumnAtOffset(startRow, match.start - startSegment.startIndex),
|
||||
y: startSegment.bufferLineNumber - 1,
|
||||
},
|
||||
end: {
|
||||
x: terminalColumnAtOffset(endRow, match.end - 1 - endSegment.startIndex),
|
||||
y: endSegment.bufferLineNumber - 1,
|
||||
},
|
||||
},
|
||||
};
|
||||
}
|
||||
}
|
||||
return null;
|
||||
@@ -338,6 +405,13 @@ export function isTerminalLinkPointerGesture(
|
||||
: event.ctrlKey && !event.metaKey;
|
||||
}
|
||||
|
||||
export function shouldShowTerminalLinkHover(
|
||||
mouseTracking: boolean,
|
||||
linkModifierActive: boolean,
|
||||
): boolean {
|
||||
return !mouseTracking || linkModifierActive;
|
||||
}
|
||||
|
||||
export function ghosttyMouseButton(button: number): number | null {
|
||||
switch (button) {
|
||||
case 0:
|
||||
@@ -407,9 +481,10 @@ export class GhosttyTerminalSurface {
|
||||
private readonly options: GhosttyTerminalSurfaceOptions;
|
||||
private metrics: GhosttyCellMetrics;
|
||||
private fontFamily: string;
|
||||
private requestedFontFamily: string | undefined;
|
||||
private fontSize: number;
|
||||
private requestedFontSize: number;
|
||||
private fontEpoch = 0;
|
||||
private pendingFontEpoch: number | null = null;
|
||||
private readonly resizeObserver: ResizeObserver;
|
||||
private readonly scrollbarThumb: HTMLDivElement;
|
||||
private snapshot: GhosttySnapshot | null = null;
|
||||
@@ -444,6 +519,9 @@ export class GhosttyTerminalSurface {
|
||||
private mouseReportingPointerId: number | null = null;
|
||||
private mouseReportingButton: number | null = null;
|
||||
private linkActivationPointerId: number | null = null;
|
||||
private hoveredLink: TerminalLinkWithRange | null = null;
|
||||
private hoverPointer: { x: number; y: number } | null = null;
|
||||
private linkModifierActive = false;
|
||||
private selectionClickSequence: TerminalSelectionClickSequence | null = null;
|
||||
private selectionMoved = false;
|
||||
private composing = false;
|
||||
@@ -470,6 +548,7 @@ export class GhosttyTerminalSurface {
|
||||
context: CanvasRenderingContext2D,
|
||||
core: GhosttyTerminalCore,
|
||||
metrics: GhosttyCellMetrics,
|
||||
fontFamily: string,
|
||||
options: GhosttyTerminalSurfaceOptions,
|
||||
) {
|
||||
this.mount = mount;
|
||||
@@ -482,9 +561,9 @@ export class GhosttyTerminalSurface {
|
||||
this.metrics = metrics;
|
||||
this.options = options;
|
||||
this.theme = options.theme;
|
||||
this.fontFamily = terminalFontFamily(options.font?.family);
|
||||
this.fontFamily = fontFamily;
|
||||
this.requestedFontFamily = options.font?.family;
|
||||
this.fontSize = terminalFontSize(options.font?.size);
|
||||
this.requestedFontSize = this.fontSize;
|
||||
this.resizeObserver = new ResizeObserver(() => this.fit());
|
||||
this.installEvents();
|
||||
this.watchDevicePixelRatio();
|
||||
@@ -525,16 +604,20 @@ export class GhosttyTerminalSurface {
|
||||
|
||||
const context = canvas.getContext("2d", { alpha: false });
|
||||
if (!context) throw new Error("Canvas 2D is unavailable");
|
||||
const fontFamily = terminalFontFamily(options.font?.family);
|
||||
// An opaque canvas backing store initializes to solid black, and the font
|
||||
// and WASM loads below leave it on screen for the whole setup window; paint
|
||||
// the theme background first so the mount never flashes a black box.
|
||||
context.fillStyle = `rgb(${options.theme.background.r}, ${options.theme.background.g}, ${options.theme.background.b})`;
|
||||
context.fillRect(0, 0, canvas.width, canvas.height);
|
||||
const fontSize = terminalFontSize(options.font?.size);
|
||||
try {
|
||||
// Cell metrics must come from the faces that will render; measuring before
|
||||
// the bundled webfonts load would size the grid from a fallback font.
|
||||
await ensureTerminalSymbolsFont();
|
||||
await document.fonts.load(`${fontSize}px ${fontFamily}`);
|
||||
} catch {
|
||||
// Metrics fall back to whichever faces are already available.
|
||||
}
|
||||
const fontFamily = await loadTerminalFontFamily(options.font?.family, fontSize);
|
||||
const metrics = measureGhosttyCell(context, fontSize, fontFamily);
|
||||
const grid = terminalGridSize(mount.clientWidth, mount.clientHeight, metrics, CONTENT_PADDING);
|
||||
const core = await GhosttyTerminalCore.create(
|
||||
@@ -554,6 +637,7 @@ export class GhosttyTerminalSurface {
|
||||
context,
|
||||
core,
|
||||
metrics,
|
||||
fontFamily,
|
||||
options,
|
||||
);
|
||||
surface.fit();
|
||||
@@ -592,19 +676,16 @@ export class GhosttyTerminalSurface {
|
||||
|
||||
async setFont(font: GhosttyTerminalFont): Promise<void> {
|
||||
if (this.disposed) return;
|
||||
const fontFamily = terminalFontFamily(font.family);
|
||||
const fontSize = terminalFontSize(font.size);
|
||||
// The fields only change together with their metrics after the load, and
|
||||
// the epoch lets the newest overlapping call win regardless of load order.
|
||||
const epoch = ++this.fontEpoch;
|
||||
try {
|
||||
await document.fonts.load(`${fontSize}px ${fontFamily}`);
|
||||
} catch {
|
||||
// Metrics fall back to whichever faces are already available.
|
||||
}
|
||||
this.pendingFontEpoch = epoch;
|
||||
const fontFamily = await loadTerminalFontFamily(font.family, fontSize);
|
||||
if (this.disposed || epoch !== this.fontEpoch) return;
|
||||
this.pendingFontEpoch = null;
|
||||
this.fontFamily = fontFamily;
|
||||
this.requestedFontSize = fontSize;
|
||||
this.requestedFontFamily = font.family;
|
||||
this.fontSize = fontSize;
|
||||
this.applyFontMetrics();
|
||||
}
|
||||
@@ -631,6 +712,17 @@ export class GhosttyTerminalSurface {
|
||||
|
||||
private readonly onFontsLoaded = () => {
|
||||
if (this.disposed) return;
|
||||
// The explicit load validates every style and applies the newest request.
|
||||
// Its own loading events must not revalidate the previously applied face.
|
||||
if (this.pendingFontEpoch !== null) return;
|
||||
// A face may become available after an earlier fallback measurement. Run
|
||||
// the fixed-width guard again before using its newly loaded metrics.
|
||||
const fontFamily = terminalFontFamily(this.requestedFontFamily);
|
||||
if (fontFamily !== this.fontFamily) {
|
||||
this.fontFamily = fontFamily;
|
||||
this.applyFontMetrics();
|
||||
return;
|
||||
}
|
||||
// A face that finished loading after the initial measurement changes glyph
|
||||
// advances; re-measure and refit so the grid matches what actually renders.
|
||||
const metrics = measureGhosttyCell(this.context, this.fontSize, this.fontFamily);
|
||||
@@ -649,22 +741,6 @@ export class GhosttyTerminalSurface {
|
||||
const width = this.mount.clientWidth;
|
||||
const height = this.mount.clientHeight;
|
||||
if (width <= 0 || height <= 0) return false;
|
||||
const fitted = fittedTerminalFontSize(
|
||||
(size) => measureGhosttyCell(this.context, size, this.fontFamily).width,
|
||||
this.requestedFontSize,
|
||||
width,
|
||||
);
|
||||
if (fitted !== this.fontSize) {
|
||||
this.fontSize = fitted;
|
||||
this.metrics = measureGhosttyCell(this.context, this.fontSize, this.fontFamily);
|
||||
// The grid-change branch below resizes the core, but only when the
|
||||
// column count moved; the cell geometry always did, so sync it here.
|
||||
this.core.resize(this.cols, this.rows, this.metrics.width, this.metrics.height);
|
||||
this.inputLeft = -1;
|
||||
this.inputTop = -1;
|
||||
this.forceFullRender = true;
|
||||
this.scrollbarDirty = true;
|
||||
}
|
||||
const ratio = window.devicePixelRatio || 1;
|
||||
const pixelWidth = Math.max(1, Math.round(width * ratio));
|
||||
const pixelHeight = Math.max(1, Math.round(height * ratio));
|
||||
@@ -815,6 +891,7 @@ export class GhosttyTerminalSurface {
|
||||
}
|
||||
|
||||
private readonly onKeyDown = (event: KeyboardEvent) => {
|
||||
this.updateLinkModifier(event);
|
||||
// Presses handled outside the terminal must also swallow their release:
|
||||
// beforeKey runs side effects (keybindings, navigation sends), so it cannot
|
||||
// be consulted again on keyup, and Kitty report-event-types sessions would
|
||||
@@ -866,6 +943,7 @@ export class GhosttyTerminalSurface {
|
||||
};
|
||||
|
||||
private readonly onKeyUp = (event: KeyboardEvent) => {
|
||||
this.updateLinkModifier(event);
|
||||
if (this.suppressedKeyCodes.delete(event.code)) return;
|
||||
if (event.isComposing || this.composing || event.key === "Process" || event.keyCode === 229) {
|
||||
return;
|
||||
@@ -887,6 +965,8 @@ export class GhosttyTerminalSurface {
|
||||
|
||||
private readonly onBlur = () => {
|
||||
this.focused = false;
|
||||
this.linkModifierActive = false;
|
||||
this.refreshHoveredLink();
|
||||
// Suppressions survive blur deliberately: a shortcut that moves focus (for
|
||||
// example terminal-toggle) must still swallow its own keyup if focus comes
|
||||
// back before release. Stale entries are harmless — an encoding keydown
|
||||
@@ -968,6 +1048,7 @@ export class GhosttyTerminalSurface {
|
||||
if (button === null) return;
|
||||
event.preventDefault();
|
||||
event.stopPropagation();
|
||||
this.clearHoveredLink("default");
|
||||
this.mouseReportingPointerId = event.pointerId;
|
||||
this.mouseReportingButton = button;
|
||||
this.sendMouse("press", button, event);
|
||||
@@ -982,6 +1063,7 @@ export class GhosttyTerminalSurface {
|
||||
this.canvas.setPointerCapture(event.pointerId);
|
||||
return;
|
||||
}
|
||||
this.clearHoveredLink();
|
||||
const cell = this.cellAt(event.clientX, event.clientY);
|
||||
this.selectionMoved = false;
|
||||
this.selectionClickSequence = advanceTerminalSelectionClickSequence(
|
||||
@@ -1029,6 +1111,11 @@ export class GhosttyTerminalSurface {
|
||||
shouldReportTerminalMouse(this.core.isMouseAnyEventTracking(), event)
|
||||
) {
|
||||
event.preventDefault();
|
||||
this.hoverPointer = { x: event.clientX, y: event.clientY };
|
||||
this.linkModifierActive = isTerminalLinkPointerGesture(event);
|
||||
// A drag whose press was already sent to the terminal application cannot
|
||||
// turn into link activation midway through, so link feedback would lie.
|
||||
this.setHoveredLink(null);
|
||||
this.canvas.style.cursor = "default";
|
||||
this.sendMouse("motion", this.buttonFromButtons(event.buttons), event);
|
||||
return;
|
||||
@@ -1037,6 +1124,7 @@ export class GhosttyTerminalSurface {
|
||||
this.updateHoverCursor(event);
|
||||
return;
|
||||
}
|
||||
this.clearHoveredLink();
|
||||
this.selectionPointer = { x: event.clientX, y: event.clientY };
|
||||
const bounds = this.canvas.getBoundingClientRect();
|
||||
this.setSelectionAutoscroll(
|
||||
@@ -1097,10 +1185,50 @@ export class GhosttyTerminalSurface {
|
||||
}
|
||||
|
||||
private updateHoverCursor(event: PointerEvent): void {
|
||||
const overLink =
|
||||
isTerminalLinkPointerGesture(event) && this.linkAt(event.clientX, event.clientY) !== null;
|
||||
const cursor = overLink ? "pointer" : "";
|
||||
if (this.canvas.style.cursor !== cursor) this.canvas.style.cursor = cursor;
|
||||
this.hoverPointer = { x: event.clientX, y: event.clientY };
|
||||
this.linkModifierActive = isTerminalLinkPointerGesture(event);
|
||||
this.refreshHoveredLink();
|
||||
}
|
||||
|
||||
private updateLinkModifier(event: Pick<KeyboardEvent, "ctrlKey" | "metaKey">): void {
|
||||
const active = isTerminalLinkPointerGesture(event);
|
||||
if (active === this.linkModifierActive) return;
|
||||
this.linkModifierActive = active;
|
||||
this.refreshHoveredLink();
|
||||
}
|
||||
|
||||
private readonly onPointerLeave = () => {
|
||||
this.clearHoveredLink();
|
||||
};
|
||||
|
||||
private clearHoveredLink(cursor = ""): void {
|
||||
this.hoverPointer = null;
|
||||
this.setHoveredLink(null);
|
||||
this.canvas.style.cursor = cursor;
|
||||
}
|
||||
|
||||
private refreshHoveredLink(): void {
|
||||
const pointer = this.hoverPointer;
|
||||
const link =
|
||||
pointer && shouldShowTerminalLinkHover(this.core.isMouseTracking(), this.linkModifierActive)
|
||||
? this.linkAt(pointer.x, pointer.y)
|
||||
: null;
|
||||
this.setHoveredLink(link);
|
||||
}
|
||||
|
||||
private setHoveredLink(link: TerminalLinkWithRange | null): void {
|
||||
const previous = this.hoveredLink;
|
||||
const unchanged =
|
||||
previous?.text === link?.text &&
|
||||
previous?.range.start.x === link?.range.start.x &&
|
||||
previous?.range.start.y === link?.range.start.y &&
|
||||
previous?.range.end.x === link?.range.end.x &&
|
||||
previous?.range.end.y === link?.range.end.y;
|
||||
this.canvas.style.cursor = link ? "pointer" : "";
|
||||
if (unchanged) return;
|
||||
this.hoveredLink = link;
|
||||
this.forceFullRender = true;
|
||||
this.requestRender();
|
||||
}
|
||||
|
||||
private readonly onPointerUp = (event: PointerEvent) => {
|
||||
@@ -1114,7 +1242,7 @@ export class GhosttyTerminalSurface {
|
||||
}
|
||||
if (event.type !== "pointercancel") {
|
||||
const link = this.linkAt(event.clientX, event.clientY);
|
||||
if (link) this.options.onLinkActivate(link, event);
|
||||
if (link) this.options.onLinkActivate(link.text, event);
|
||||
}
|
||||
return;
|
||||
}
|
||||
@@ -1127,6 +1255,13 @@ export class GhosttyTerminalSurface {
|
||||
if (this.canvas.hasPointerCapture(event.pointerId)) {
|
||||
this.canvas.releasePointerCapture(event.pointerId);
|
||||
}
|
||||
if (event.type === "pointercancel") {
|
||||
this.clearHoveredLink();
|
||||
} else {
|
||||
this.hoverPointer = { x: event.clientX, y: event.clientY };
|
||||
this.linkModifierActive = isTerminalLinkPointerGesture(event);
|
||||
this.refreshHoveredLink();
|
||||
}
|
||||
return;
|
||||
}
|
||||
if (this.canvas.hasPointerCapture(event.pointerId)) {
|
||||
@@ -1253,6 +1388,7 @@ export class GhosttyTerminalSurface {
|
||||
this.input.addEventListener("compositionend", this.onCompositionEnd);
|
||||
this.canvas.addEventListener("pointerdown", this.onPointerDown);
|
||||
this.canvas.addEventListener("pointermove", this.onPointerMove);
|
||||
this.canvas.addEventListener("pointerleave", this.onPointerLeave);
|
||||
this.canvas.addEventListener("pointerup", this.onPointerUp);
|
||||
this.canvas.addEventListener("pointercancel", this.onPointerUp);
|
||||
this.canvas.addEventListener("wheel", this.onWheel, { passive: false });
|
||||
@@ -1276,6 +1412,7 @@ export class GhosttyTerminalSurface {
|
||||
this.input.removeEventListener("compositionend", this.onCompositionEnd);
|
||||
this.canvas.removeEventListener("pointerdown", this.onPointerDown);
|
||||
this.canvas.removeEventListener("pointermove", this.onPointerMove);
|
||||
this.canvas.removeEventListener("pointerleave", this.onPointerLeave);
|
||||
this.canvas.removeEventListener("pointerup", this.onPointerUp);
|
||||
this.canvas.removeEventListener("pointercancel", this.onPointerUp);
|
||||
this.canvas.removeEventListener("wheel", this.onWheel);
|
||||
@@ -1378,6 +1515,7 @@ export class GhosttyTerminalSurface {
|
||||
this.originY = nextOriginY;
|
||||
this.forceFullRender = true;
|
||||
}
|
||||
this.refreshHoveredLink();
|
||||
renderGhosttySnapshot({
|
||||
context: this.context,
|
||||
snapshot: this.snapshot,
|
||||
@@ -1390,6 +1528,7 @@ export class GhosttyTerminalSurface {
|
||||
cursorOn: this.cursorOn,
|
||||
previousCursorY: this.renderedCursorY,
|
||||
focused: this.focused,
|
||||
hoveredLinkRange: this.hoveredLink?.range ?? null,
|
||||
...(this.theme.selectionBackground !== undefined
|
||||
? { selectionBackground: this.theme.selectionBackground }
|
||||
: {}),
|
||||
@@ -1466,12 +1605,51 @@ export class GhosttyTerminalSurface {
|
||||
};
|
||||
}
|
||||
|
||||
private linkAt(clientX: number, clientY: number): string | null {
|
||||
private linkAt(clientX: number, clientY: number): TerminalLinkWithRange | null {
|
||||
if (!this.snapshot) return null;
|
||||
const cell = this.cellAt(clientX, clientY);
|
||||
const cell = terminalGridCellAt({
|
||||
bounds: this.canvas.getBoundingClientRect(),
|
||||
clientX,
|
||||
clientY,
|
||||
cols: this.cols,
|
||||
rows: this.rows,
|
||||
metrics: this.metrics,
|
||||
padding: CONTENT_PADDING,
|
||||
originY: this.originY,
|
||||
});
|
||||
if (!cell) return null;
|
||||
const explicitHyperlink = this.core.hyperlinkAt(cell.x, cell.y);
|
||||
if (explicitHyperlink) return explicitHyperlink;
|
||||
return terminalLinkAtPosition(this.snapshot.rowData, cell.y, cell.x);
|
||||
if (explicitHyperlink) {
|
||||
const start = { ...cell };
|
||||
const end = { ...cell };
|
||||
while (true) {
|
||||
const previous =
|
||||
start.x > 0
|
||||
? { x: start.x - 1, y: start.y }
|
||||
: start.y > 0 && this.snapshot.rowData[start.y]?.isWrapContinuation
|
||||
? { x: this.cols - 1, y: start.y - 1 }
|
||||
: null;
|
||||
if (!previous || this.core.hyperlinkAt(previous.x, previous.y) !== explicitHyperlink) break;
|
||||
start.x = previous.x;
|
||||
start.y = previous.y;
|
||||
}
|
||||
while (true) {
|
||||
const next =
|
||||
end.x + 1 < this.cols
|
||||
? { x: end.x + 1, y: end.y }
|
||||
: end.y + 1 < this.rows && this.snapshot.rowData[end.y]?.wrapsToNext
|
||||
? { x: 0, y: end.y + 1 }
|
||||
: null;
|
||||
if (!next || this.core.hyperlinkAt(next.x, next.y) !== explicitHyperlink) break;
|
||||
end.x = next.x;
|
||||
end.y = next.y;
|
||||
}
|
||||
return {
|
||||
text: explicitHyperlink,
|
||||
range: { start, end },
|
||||
};
|
||||
}
|
||||
return terminalLinkAtPositionWithRange(this.snapshot.rowData, cell.y, cell.x);
|
||||
}
|
||||
|
||||
private sendMouse(
|
||||
|
||||
@@ -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
|
||||
|
||||
|
||||
@@ -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,
|
||||
]);
|
||||
}
|
||||
|
||||
@@ -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({
|
||||
|
||||
@@ -44,17 +44,27 @@ const PROJECT_SCRIPTS = JSON.stringify([
|
||||
},
|
||||
]);
|
||||
|
||||
const SHOWCASE_TERMINAL_PROMPT =
|
||||
"\u001b[1;32m→\u001b[0m \u001b[1;36mt3code\u001b[0m \u001b[1;34mgit:(\u001b[1;31mfeat/remote-command-center\u001b[1;34m)\u001b[0m \u001b[1;33m✗\u001b[0m ";
|
||||
|
||||
// A dev-server startup mirroring the web settings' terminal font preview:
|
||||
// zsh-style prompt, brand line, addresses, the thread's 612-test summary,
|
||||
// and a READY badge, so the scene exercises bold, dim, underline, the six
|
||||
// accent colors, and a background cell.
|
||||
export const SHOWCASE_TERMINAL_BUFFER = [
|
||||
"\u001b[38;5;75m~/Code/t3code\u001b[0m \u001b[38;5;212mfeat/remote-command-center\u001b[0m",
|
||||
"$ vp test run --changed",
|
||||
`${SHOWCASE_TERMINAL_PROMPT}vpr dev`,
|
||||
"",
|
||||
" \u001b[38;5;117mt3code-mobile\u001b[0m 184 passed",
|
||||
" \u001b[38;5;213mclient-runtime\u001b[0m 263 passed",
|
||||
" \u001b[38;5;221mserver\u001b[0m 165 passed",
|
||||
" \u001b[1;32mVITE\u001b[0m \u001b[32mv7.1.1\u001b[0m \u001b[2mready in\u001b[0m \u001b[1m1.24s\u001b[0m",
|
||||
"",
|
||||
"\u001b[32m✨ 612 tests passed\u001b[0m · 3 environments online",
|
||||
" \u001b[32m→\u001b[0m \u001b[2mLocal:\u001b[0m \u001b[4;36mhttp://127.0.0.1:5173/\u001b[0m",
|
||||
" \u001b[32m→\u001b[0m \u001b[2mNetwork:\u001b[0m \u001b[4;36mhttp://192.168.1.24:5173/\u001b[0m",
|
||||
" \u001b[32m→\u001b[0m \u001b[2mProject:\u001b[0m \u001b[1mt3code\u001b[0m \u001b[2m— ~/Code/t3code\u001b[0m",
|
||||
"",
|
||||
"\u001b[38;5;75m~/Code/t3code\u001b[0m \u001b[38;5;212mfeat/remote-command-center\u001b[0m $ ",
|
||||
" \u001b[32m✓ 612 passed\u001b[0m \u001b[33m△ 2 warnings\u001b[0m \u001b[31m✗ 0 failed\u001b[0m",
|
||||
"",
|
||||
" \u001b[42;30m READY \u001b[0m \u001b[2mwatching for changes — press\u001b[0m \u001b[1mq\u001b[0m \u001b[2mto quit\u001b[0m",
|
||||
"",
|
||||
SHOWCASE_TERMINAL_PROMPT,
|
||||
].join("\r\n");
|
||||
|
||||
const BASE_ENVIRONMENT_PRESENCE = `export function environmentLabel(count: number): string {
|
||||
|
||||
Reference in new issue
Block a user