TypeScript
fix(mobile): one No project row at the top of the project picker (#14532)
Julius Marminge39405f1992b4
diff --git a/apps/mobile/src/features/threads/NewTaskContextPickerScreens.tsx b/apps/mobile/src/features/threads/NewTaskContextPickerScreens.tsxindex b30175b5b0d..28e49cbdb5b 100644--- a/apps/mobile/src/features/threads/NewTaskContextPickerScreens.tsx+++ b/apps/mobile/src/features/threads/NewTaskContextPickerScreens.tsx@@ -1,6 +1,8 @@import { MaterialListRow } from "../../components/MaterialListRow";import type { VcsRef } from "@t3tools/client-runtime/state/vcs";-import { resolveEnvironmentMachineKind } from "@t3tools/contracts";+import { type EnvironmentId, resolveEnvironmentMachineKind } from "@t3tools/contracts";+import * as Cause from "effect/Cause";+import { AsyncResult } from "effect/unstable/reactivity";import { LegendList } from "@legendapp/list/react-native";import {isAtomCommandInterrupted,@@ -28,7 +30,8 @@ import { EnvironmentMachineSymbol } from "../../components/EnvironmentMachineSymimport { ThemedSwitch } from "../../components/ThemedSwitch";import { cn } from "../../lib/cn";import { NativeHeaderToolbar, NativeStackScreenOptions } from "../../native/StackHeader";-import { useServerConfigs } from "../../state/entities";+import { useServerConfigs, waitForProject } from "../../state/entities";+import { projectEnvironment } from "../../state/projects";import { useAtomCommand } from "../../state/use-atom-command";import { vcsEnvironment } from "../../state/vcs";import {@@ -203,6 +206,38 @@ export function NewTaskEnvironmentPickerRouteScreen() {const navigation = useNavigation();const insets = useSafeAreaInsets();const serverConfigs = useServerConfigs();+ const ensureScratch = useAtomCommand(projectEnvironment.ensureScratch, {+ reportFailure: false,+ });+ const [movingToEnvironmentId, setMovingToEnvironmentId] = useState<EnvironmentId | null>(null);++ // A thread without a project moves to the other machine's own Scratch+ // project, which is created there first if it does not exist yet.+ async function moveScratchDraft(environmentId: EnvironmentId): Promise<void> {+ setMovingToEnvironmentId(environmentId);+ try {+ const result = await ensureScratch({ environmentId, input: {} });+ if (AsyncResult.isFailure(result)) {+ const error = Cause.squash(result.cause);+ Alert.alert(+ "Could not switch machine",+ error instanceof Error+ ? error.message+ : "The folder for threads without a project could not be created.",+ );+ return;+ }+ const project = await waitForProject({ environmentId, projectId: result.value.projectId });+ if (project === null) {+ Alert.alert("Could not switch machine", "It has not reached this device yet. Try again.");+ return;+ }+ flow.setProject(project);+ navigation.goBack();+ } finally {+ setMovingToEnvironmentId(null);+ }+ }return (<View className="flex-1 bg-sheet" collapsable={false}>@@ -243,9 +278,17 @@ export function NewTaskEnvironmentPickerRouteScreen() {/>}isLast={index === flow.environments.length - 1}+ disabled={movingToEnvironmentId !== null}onPress={() => {void Haptics.selectionAsync();- flow.selectEnvironment(environment.environmentId);+ if (flow.isScratchDraft) {+ if (environment.environmentId !== flow.selectedEnvironmentId) {+ void moveScratchDraft(environment.environmentId);+ return;+ }+ } else {+ flow.selectEnvironment(environment.environmentId);+ }navigation.goBack();}}selected={flow.selectedEnvironmentId === environment.environmentId}diff --git a/apps/mobile/src/features/threads/NewTaskDraftScreen.tsx b/apps/mobile/src/features/threads/NewTaskDraftScreen.tsxindex 12f296a15e6..0772705645f 100644--- a/apps/mobile/src/features/threads/NewTaskDraftScreen.tsx+++ b/apps/mobile/src/features/threads/NewTaskDraftScreen.tsx@@ -1455,7 +1455,49 @@ export function NewTaskDraftScreen(props: {navigation.dispatch(StackActions.push(routeName));};- const hero = (+ const environmentControl = (+ <ComposerInlineControl+ accessibilityLabel={`Environment: ${selectedEnvironmentLabel}`}+ chevronDirection="right"+ disabled={isComposerInteractionLocked || voiceInput.isBusy}+ renderIcon={(size) => (+ <EnvironmentMachineSymbol+ kind={resolveEnvironmentMachineKind(selectedEnvironmentServerConfig)}+ size={size}+ tintColorClassName="accent-icon-muted"+ />+ )}+ label={`on ${selectedEnvironmentLabel}`}+ maxWidth={flow.isScratchDraft ? 170 : 260}+ onPress={+ flow.environments.length > 1 ? () => openContextPicker("NewTaskEnvironment") : undefined+ }+ showChevron={flow.environments.length > 1}+ static={flow.environments.length <= 1}+ />+ );+ // A thread without a project has no project to name, so it asks plainly,+ // like web, and puts the project picker beside the machine as a control.+ const hero = flow.isScratchDraft ? (+ <View className="items-center gap-2 px-6" testID="new-task-hero">+ <Text className="text-center text-2xl font-t3-medium tracking-tight text-foreground">+ What should we work on?+ </Text>+ {/* Wraps onto two lines only when a long machine name leaves no room. */}+ <View className="flex-row flex-wrap items-center justify-center gap-x-1">+ <ComposerInlineControl+ accessibilityHint="Opens the project picker"+ accessibilityLabel="Choose a project"+ chevronDirection="right"+ disabled={isComposerInteractionLocked}+ icon="folder"+ label="Choose a project"+ onPress={chooseProject}+ />+ {environmentControl}+ </View>+ </View>+ ) : (<View className="items-center gap-6 px-6" testID="new-task-hero"><View className="w-full items-center gap-1.5"><Text className="text-center text-2xl font-t3-medium tracking-tight text-foreground">@@ -1482,25 +1524,7 @@ export function NewTaskDraftScreen(props: {</View></View>- <ComposerInlineControl- accessibilityLabel={`Environment: ${selectedEnvironmentLabel}`}- chevronDirection="right"- disabled={isComposerInteractionLocked || voiceInput.isBusy}- renderIcon={(size) => (- <EnvironmentMachineSymbol- kind={resolveEnvironmentMachineKind(selectedEnvironmentServerConfig)}- size={size}- tintColorClassName="accent-icon-muted"- />- )}- label={`on ${selectedEnvironmentLabel}`}- maxWidth={260}- onPress={- flow.environments.length > 1 ? () => openContextPicker("NewTaskEnvironment") : undefined- }- showChevron={flow.environments.length > 1}- static={flow.environments.length <= 1}- />+ {environmentControl}</View>);const heroViewport = (diff --git a/apps/mobile/src/features/threads/NewTaskRouteScreen.tsx b/apps/mobile/src/features/threads/NewTaskRouteScreen.tsxindex 212846e2639..80a35eabd1c 100644--- a/apps/mobile/src/features/threads/NewTaskRouteScreen.tsx+++ b/apps/mobile/src/features/threads/NewTaskRouteScreen.tsx@@ -154,7 +154,16 @@ export function NewTaskRouteScreen({ route }: StaticScreenProps<NewTaskRoutePara: null;const screenTitle = incomingShare ? "Start a task" : "Choose project";const projectEmptyState = deriveProjectEmptyState(catalogState);- const visibleScopes = filterProjectScopes(projectScopes, searchText);+ const serverConfigs = useServerConfigs();+ // Scratch projects are reached through the No project row, never as rows+ // of their own.+ const listScopes = projectScopes.filter(+ (scope) =>+ !scope.projects.every((project) =>+ isScratchProject(project, serverConfigs.get(project.environmentId)?.scratchWorkspaceRoot),+ ),+ );+ const visibleScopes = filterProjectScopes(listScopes, searchText);const resumedDestinationKeyRef = useRef<string | null>(null);const reservedDestinationProject = incomingShare?.destination? (projects.find(@@ -163,14 +172,13 @@ export function NewTaskRouteScreen({ route }: StaticScreenProps<NewTaskRouteParaproject.id === incomingShare.destination?.projectId,) ?? null): null;- const serverConfigs = useServerConfigs();const { connectedEnvironments } = useRemoteConnectionStatus();const ensureScratch = useAtomCommand(projectEnvironment.ensureScratch, {reportFailure: false,});// Threads without a project need a connected environment that offers them.- // The selected environment wins when it has one; otherwise the first that- // does, and the entry names that machine whenever there is a choice.+ // The row starts on the selected environment when it has one, otherwise the+ // first that does; the draft page's machine picker moves it from there.const scratchEnvironments = connectedEnvironments.filter((environment) =>canCreateProjectInEnvironment(environment.connectionState) &&@@ -182,24 +190,7 @@ export function NewTaskRouteScreen({ route }: StaticScreenProps<NewTaskRoutePara) ??scratchEnvironments[0] ??null;- const scratchWorkspaceRoot = scratchEnvironment- ? (serverConfigs.get(scratchEnvironment.environmentId)?.scratchWorkspaceRoot ?? null)- : null;- // Once the Scratch project exists it is an ordinary row in the list.- const scratchProjectExists = projects.some(- (project) =>- project.environmentId === scratchEnvironment?.environmentId &&- isScratchProject(project, scratchWorkspaceRoot),- );- const canStartScratch = scratchWorkspaceRoot !== null && reservedDestinationProject === null;- const scratchMachineLabel =- connectedEnvironments.length > 1 ? (scratchEnvironment?.environmentLabel ?? null) : null;- const startScratchLabel = scratchMachineLabel- ? `Start without a project on ${scratchMachineLabel}`- : "Start without a project";- const scratchRowSubtitle = scratchMachineLabel- ? `On ${scratchMachineLabel}`- : "Start a task without a project";+ const canStartScratch = scratchEnvironment !== null && reservedDestinationProject === null;const scratchStartInFlightRef = useRef(false);async function selectProject(project: EnvironmentProject): Promise<void> {@@ -321,7 +312,56 @@ export function NewTaskRouteScreen({ route }: StaticScreenProps<NewTaskRoutePara: {}),}}>- {projectScopes.length === 0 ? (+ {canStartScratch && listScopes.length > 0 ? (+ Platform.OS === "android" ? (+ <View collapsable={false} className="overflow-hidden rounded-[28px] bg-card">+ <MaterialListRow+ title="No project"+ subtitle="Start a task without a project"+ onPress={() => void startScratch()}+ leading={+ <SymbolView+ name="text.bubble"+ size={22}+ tintColorClassName="accent-icon-muted"+ type="monochrome"+ />+ }+ />+ </View>+ ) : (+ <View collapsable={false} className="overflow-hidden rounded-[24px] bg-card">+ <Pressable+ accessibilityRole="button"+ accessibilityLabel="No project"+ onPress={() => void startScratch()}+ className="flex-row items-center gap-3 bg-card px-4 py-3.5"+ >+ <View className="h-7 w-7 items-center justify-center">+ <SymbolView+ name="text.bubble"+ size={18}+ tintColorClassName="accent-icon-muted"+ type="monochrome"+ />+ </View>+ <View className="min-w-0 flex-1">+ <Text className="text-base font-t3-bold leading-snug">No project</Text>+ <Text className="text-xs leading-snug text-foreground-muted" numberOfLines={1}>+ Start a task without a project+ </Text>+ </View>+ <SymbolView+ name="chevron.right"+ size={14}+ tintColorClassName="accent-chevron"+ type="monochrome"+ />+ </Pressable>+ </View>+ )+ ) : null}+ {listScopes.length === 0 ? (<Viewcollapsable={false}className={cn(@@ -351,7 +391,7 @@ export function NewTaskRouteScreen({ route }: StaticScreenProps<NewTaskRoutePara/>{canStartScratch ? (<MaterialButton- label={startScratchLabel}+ label="Start without a project"tone="secondary"onPress={() => void startScratch()}/>@@ -382,7 +422,7 @@ export function NewTaskRouteScreen({ route }: StaticScreenProps<NewTaskRouteParaonPress={() => void startScratch()}><Text className="text-sm font-t3-bold text-foreground">- {startScratchLabel}+ Start without a project</Text></Pressable>) : null}@@ -486,55 +526,6 @@ export function NewTaskRouteScreen({ route }: StaticScreenProps<NewTaskRoutePara})}</View>)}- {canStartScratch && !scratchProjectExists && projectScopes.length > 0 ? (- Platform.OS === "android" ? (- <View collapsable={false} className="overflow-hidden rounded-[28px] bg-card">- <MaterialListRow- title="No project"- subtitle={scratchRowSubtitle}- onPress={() => void startScratch()}- leading={- <SymbolView- name="text.bubble"- size={22}- tintColorClassName="accent-icon-muted"- type="monochrome"- />- }- />- </View>- ) : (- <View collapsable={false} className="overflow-hidden rounded-[24px] bg-card">- <Pressable- accessibilityRole="button"- accessibilityLabel="No project"- onPress={() => void startScratch()}- className="flex-row items-center gap-3 bg-card px-4 py-3.5"- >- <View className="h-7 w-7 items-center justify-center">- <SymbolView- name="text.bubble"- size={18}- tintColorClassName="accent-icon-muted"- type="monochrome"- />- </View>- <View className="min-w-0 flex-1">- <Text className="text-base font-t3-bold leading-snug">No project</Text>- <Text className="text-xs leading-snug text-foreground-muted" numberOfLines={1}>- {scratchRowSubtitle}- </Text>- </View>- <SymbolView- name="chevron.right"- size={14}- tintColorClassName="accent-chevron"- type="monochrome"- />- </Pressable>- </View>- )- ) : null}</ScrollView></MaterialScreenContent></View>diff --git a/apps/mobile/src/features/threads/new-task-flow-provider.tsx b/apps/mobile/src/features/threads/new-task-flow-provider.tsxindex a723c2fa29f..ab598edd5d0 100644--- a/apps/mobile/src/features/threads/new-task-flow-provider.tsx+++ b/apps/mobile/src/features/threads/new-task-flow-provider.tsx@@ -24,7 +24,12 @@ import { parseT3ProjectFile } from "@t3tools/shared/t3ProjectFile";import * as Arr from "effect/Array";import { pipe } from "effect/Function";-import { useEnvironmentServerConfig, useProjects, useThreadShells } from "../../state/entities";+import {+ useEnvironmentServerConfig,+ useProjects,+ useServerConfigs,+ useThreadShells,+} from "../../state/entities";import type { TurnCommandMetadata } from "../../lib/commandMetadata";import type { DraftComposerAttachment } from "../../lib/composerImages";import type { ModelOption, ProviderGroup } from "../../lib/modelOptions";@@ -77,8 +82,10 @@ import {} from "../../state/use-thread-outbox";import {setPendingConnectionError,+ useRemoteConnectionStatus,useSavedRemoteConnections,} from "../../state/use-remote-environment-registry";+import { canCreateProjectInEnvironment } from "@t3tools/client-runtime/operations/projects";import { isScratchProject } from "@t3tools/client-runtime/state/projects";import { EnvironmentProject } from "@t3tools/client-runtime/state/shell";import { type VcsRef } from "@t3tools/client-runtime/state/vcs";@@ -173,6 +180,8 @@ type NewTaskFlowContextValue = {readonly environmentLabel: string;}>;readonly selectedProject: EnvironmentProject | null;+ /** True when the draft is a thread without a project (its machine's Scratch project). */+ readonly isScratchDraft: boolean;readonly modelOptions: ReadonlyArray<ModelOption>;readonly selectedModel: ModelSelection | null;readonly selectedModelOption: ModelOption | null;@@ -339,6 +348,26 @@ export function NewTaskFlowProvider(props: React.PropsWithChildren) {? editingPendingProject: (projectsForEnvironment[0] ?? null));+ const selectedEnvironmentServerConfig = useEnvironmentServerConfig(+ selectedProject?.environmentId ?? null,+ );+ const isScratchDraft =+ selectedProject !== null &&+ isScratchProject(selectedProject, selectedEnvironmentServerConfig?.scratchWorkspaceRoot);+ const serverConfigs = useServerConfigs();+ const { connectedEnvironments } = useRemoteConnectionStatus();+ // A thread without a project can move to any connected machine that offers+ // one; its Scratch project there is created on the switch if it is missing.+ const scratchEnvironments = useMemo(+ () =>+ connectedEnvironments.filter(+ (environment) =>+ canCreateProjectInEnvironment(environment.connectionState) &&+ serverConfigs.get(environment.environmentId)?.scratchWorkspaceRoot !== undefined,+ ),+ [connectedEnvironments, serverConfigs],+ );+// Only offer machines that actually host the currently selected repository, so// switching computers moves the same repo across machines instead of jumping to// whatever unrelated project happens to be first on the other machine. Repository@@ -350,6 +379,12 @@ export function NewTaskFlowProvider(props: React.PropsWithChildren) {const selectedWorkspaceBasename = selectedProject?.workspaceRoot.split("/").at(-1) || null;const selectedProjectTitle = selectedProject?.title ?? null;const environments = useMemo(() => {+ if (isScratchDraft) {+ return scratchEnvironments.map((environment) => ({+ environmentId: environment.environmentId,+ environmentLabel: environment.environmentLabel,+ }));+ }const seen = new Set<EnvironmentId>();const result: Array<{readonly environmentId: EnvironmentId;@@ -387,16 +422,15 @@ export function NewTaskFlowProvider(props: React.PropsWithChildren) {}return result;}, [+ isScratchDraft,projects,savedConnectionsById,+ scratchEnvironments,selectedRepositoryKey,selectedWorkspaceBasename,selectedProjectTitle,]);- const selectedEnvironmentServerConfig = useEnvironmentServerConfig(- selectedProject?.environmentId ?? null,- );// While a queued pending task is being edited its draft lives under a key// scoped to the queued message, so new-task drafts stay intact.const selectedProjectDraftKey = editingPendingTask@@ -457,10 +491,7 @@ export function NewTaskFlowProvider(props: React.PropsWithChildren) {);// A thread without a project runs in a plain folder, so worktree mode// would leave it unsendable: it is always local and offers no choice.- const canChooseWorkspace = !(- selectedProject !== null &&- isScratchProject(selectedProject, selectedEnvironmentServerConfig?.scratchWorkspaceRoot)- );+ const canChooseWorkspace = !isScratchDraft;const defaultWorkspaceMode: WorkspaceMode = canChooseWorkspace? projectSettings.settings.defaultThreadEnvMode: "local";@@ -1192,6 +1223,7 @@ export function NewTaskFlowProvider(props: React.PropsWithChildren) {expandedProvider,environments,selectedProject,+ isScratchDraft,modelOptions,selectedModel,selectedModelOption,@@ -1241,6 +1273,7 @@ export function NewTaskFlowProvider(props: React.PropsWithChildren) {filteredBranches,finishEditingPendingTask,interactionMode,+ isScratchDraft,planModeEnabled,loadBranches,loadMoreBranches,