diff --git a/apps/mobile/src/App.tsx b/apps/mobile/src/App.tsx index 8dff8bdc50396..2033b45d563d2 100644 --- a/apps/mobile/src/App.tsx +++ b/apps/mobile/src/App.tsx @@ -1,4 +1,6 @@ import { installPermissionUpdateNotice } from "./features/connection/permissionUpdateNotice"; +import { installComposerAttachmentUploads } from "./state/composer-attachment-uploads"; +import { installThreadOutboxDelivery } from "./state/threadOutboxDelivery"; import * as Linking from "expo-linking"; import * as SplashScreen from "expo-splash-screen"; import { useEffect } from "react"; @@ -86,11 +88,14 @@ const navigationRef = createNavigationContainerRef(); declare const module: { readonly hot?: FoundationHotModule } | undefined; -const disposePermissionUpdateNotice = installPermissionUpdateNotice(); -disposeOnFoundationReplace( - typeof module === "undefined" ? undefined : module.hot, - disposePermissionUpdateNotice, -); +const appServiceDisposers = [ + installPermissionUpdateNotice(), + installThreadOutboxDelivery(), + installComposerAttachmentUploads(), +]; +disposeOnFoundationReplace(typeof module === "undefined" ? undefined : module.hot, () => { + for (const dispose of appServiceDisposers) dispose(); +}); function SplashScreenCoordinator() { const { isReady } = useAppearancePreferences(); diff --git a/apps/mobile/src/Stack.tsx b/apps/mobile/src/Stack.tsx index ffc4b0bc8de93..74a8600f1e3aa 100644 --- a/apps/mobile/src/Stack.tsx +++ b/apps/mobile/src/Stack.tsx @@ -97,9 +97,9 @@ import { SettingsEnvironmentDetailRouteScreen } from "./features/settings/Settin import { SettingsEnvironmentsRouteScreen } from "./features/settings/SettingsEnvironmentsRouteScreen"; import { SettingsFollowUpRouteScreen } from "./features/settings/SettingsFollowUpRouteScreen"; import { - SettingsEnvironmentAgentBehaviorRouteScreen, SettingsEnvironmentMaintenanceRouteScreen, - SettingsEnvironmentNewThreadsRouteScreen, + SettingsThreadsRouteScreen, + SettingsWorktreesRouteScreen, SettingsEnvironmentSourceControlRouteScreen, } from "./features/settings/SettingsServerControlsRouteScreen"; import { @@ -125,7 +125,7 @@ import { UsageRouteScreen } from "./features/usage/UsageRouteScreen"; import { SettingsAboutRouteScreen } from "./features/settings/SettingsAboutRouteScreen"; import { SettingsNotificationsRouteScreen } from "./features/settings/SettingsNotificationsRouteScreen"; import { SettingsRouteScreen } from "./features/settings/SettingsRouteScreen"; -import { SettingsThreadsRouteScreen } from "./features/settings/SettingsThreadsRouteScreen"; +import { SettingsLabsRouteScreen } from "./features/settings/ThreadSettingsSections"; import { SettingsEnvironmentFilterProvider } from "./features/settings/settings-environment-filter"; import { openSettings, settingsOpenIn } from "./features/settings/settings-navigation"; import { DEFAULT_SETTINGS_PAGE } from "./features/workspace/workspace-tab-navigation"; @@ -149,8 +149,6 @@ import { deriveLayout } from "./lib/layout"; import { useNativeLayoutMetrics } from "./native/native-layout-metrics"; import { nativeHeaderScrollEdgeEffects } from "./native/StackHeader"; import { HORIZONTAL_FORM_SHEET_OPTIONS, formSheetDetents } from "./native/sheet-surface"; -import { useThreadOutboxDrain } from "./state/use-thread-outbox-drain"; -import { useComposerAttachmentUploadWorker } from "./state/composer-attachment-uploads"; import { selectWorkspaceDetail, workspaceDetailRouter, @@ -263,10 +261,11 @@ const SETTINGS_SCREENS = { linking: "settings/environments/:environmentId", options: { ...SETTINGS_PAGE_OPTIONS, title: "Environment" }, }), + // Old links to New threads and Agent behavior open Threads, which absorbed them. SettingsEnvironmentNewThreads: createNativeStackScreen({ - screen: SettingsEnvironmentNewThreadsRouteScreen, + screen: SettingsThreadsRouteScreen, linking: "settings/new-threads", - options: { ...SETTINGS_PAGE_OPTIONS, title: "New threads" }, + options: { ...SETTINGS_PAGE_OPTIONS, title: "Threads" }, }), SettingsEnvironmentSourceControl: createNativeStackScreen({ screen: SettingsEnvironmentSourceControlRouteScreen, @@ -274,14 +273,24 @@ const SETTINGS_SCREENS = { options: { ...SETTINGS_PAGE_OPTIONS, title: "Source control" }, }), SettingsEnvironmentAgentBehavior: createNativeStackScreen({ - screen: SettingsEnvironmentAgentBehaviorRouteScreen, + screen: SettingsThreadsRouteScreen, linking: "settings/agent-behavior", - options: { ...SETTINGS_PAGE_OPTIONS, title: "Agent behavior" }, + options: { ...SETTINGS_PAGE_OPTIONS, title: "Threads" }, + }), + SettingsWorktrees: createNativeStackScreen({ + screen: SettingsWorktreesRouteScreen, + linking: "settings/worktrees", + options: { ...SETTINGS_PAGE_OPTIONS, title: "Worktrees" }, + }), + SettingsLabs: createNativeStackScreen({ + screen: SettingsLabsRouteScreen, + linking: "settings/labs", + options: { ...SETTINGS_PAGE_OPTIONS, title: "Labs" }, }), SettingsProviderAccounts: createNativeStackScreen({ screen: SettingsProviderAccountsRouteScreen, linking: "settings/provider-accounts", - options: { ...SETTINGS_PAGE_OPTIONS, title: "Provider accounts" }, + options: { ...SETTINGS_PAGE_OPTIONS, title: "Providers" }, }), SettingsEnvironmentMaintenance: createNativeStackScreen({ screen: SettingsEnvironmentMaintenanceRouteScreen, @@ -296,12 +305,12 @@ const SETTINGS_SCREENS = { SettingsThreads: createNativeStackScreen({ screen: SettingsThreadsRouteScreen, linking: "settings/thread-preferences", - options: { ...SETTINGS_PAGE_OPTIONS, title: "Thread behavior" }, + options: { ...SETTINGS_PAGE_OPTIONS, title: "Threads" }, }), SettingsAbout: createNativeStackScreen({ screen: SettingsAboutRouteScreen, linking: "settings/about", - options: { ...SETTINGS_PAGE_OPTIONS, title: "About T3 Code" }, + options: { ...SETTINGS_PAGE_OPTIONS, title: "About" }, }), SettingsEnvironmentNew: createNativeStackScreen({ screen: ConnectionsNewRouteScreen, @@ -316,7 +325,7 @@ const SETTINGS_SCREENS = { linking: "settings/archive", options: { ...SETTINGS_PAGE_OPTIONS, - title: "Archived Threads", + title: "Archive", }, }), SettingsNavigation: createNativeStackScreen({ @@ -337,7 +346,7 @@ const SETTINGS_SCREENS = { linking: "settings/project-grouping", options: { ...SETTINGS_PAGE_OPTIONS, - title: "Organization", + title: "General", }, }), SettingsOrganization: createNativeStackScreen({ @@ -345,13 +354,13 @@ const SETTINGS_SCREENS = { linking: "settings/organization", options: { ...SETTINGS_PAGE_OPTIONS, - title: "Organization", + title: "General", }, }), SettingsProjectOverview: createNativeStackScreen({ screen: SettingsProjectOverviewRouteScreen, linking: "settings/project", - options: { ...SETTINGS_PAGE_OPTIONS, title: "Project overview" }, + options: { ...SETTINGS_PAGE_OPTIONS, title: "Projects" }, }), SettingsKeyboard: createNativeStackScreen({ screen: SettingsKeyboardRouteScreen, @@ -374,7 +383,7 @@ const SETTINGS_SCREENS = { linking: "settings/follow-ups", options: { ...SETTINGS_PAGE_OPTIONS, - title: "Follow-ups", + title: "Chat", }, }), SettingsScheduledTasks: createNativeStackScreen({ @@ -382,7 +391,7 @@ const SETTINGS_SCREENS = { linking: "settings/scheduled-tasks", options: { ...SETTINGS_PAGE_OPTIONS, - title: "Scheduled Tasks", + title: "Scheduled tasks", headerTitleStyle: { fontSize: 16, fontWeight: "800" }, }, }), @@ -485,13 +494,6 @@ function workspaceLocationFromState(state: NavigationState) { }; } -// Isolate subscriptions so streaming updates cannot re-render RootStackLayout and every screen. -function ThreadOutboxDrainWorker() { - useThreadOutboxDrain(); - useComposerAttachmentUploadWorker(); - return null; -} - function RootStackLayout(props: { readonly children: React.ReactNode; readonly state: NavigationState; @@ -509,16 +511,11 @@ function RootStackLayout(props: { ); const draftRoute = props.state.routes.findLast((route) => route.name === "Thread"); const draftParams = ( - draftRoute?.params as - | { draft?: { draftId?: string | string[]; pendingTaskId?: string | string[] } } - | undefined + draftRoute?.params as { draft?: { draftId?: string | string[] } } | undefined )?.draft; const routeDraftId = Array.isArray(draftParams?.draftId) ? draftParams.draftId[0] : draftParams?.draftId; - const routePendingTaskId = Array.isArray(draftParams?.pendingTaskId) - ? draftParams.pendingTaskId[0] - : draftParams?.pendingTaskId; useAgentNotificationNavigation(workspaceLocation.pathname); useConnectOnboardingNavigation(); useAppShortcuts(props.state); @@ -540,13 +537,8 @@ function RootStackLayout(props: { }, [navigation, pendingShare, props.state]); return ( - + - diff --git a/apps/mobile/src/components/ui/ListChoiceRow.tsx b/apps/mobile/src/components/ui/ListChoiceRow.tsx index 748752f5cd415..9e231b7c25b90 100644 --- a/apps/mobile/src/components/ui/ListChoiceRow.tsx +++ b/apps/mobile/src/components/ui/ListChoiceRow.tsx @@ -26,10 +26,8 @@ export function ListChoiceRow(props: { onPress={props.onPress} android_ripple={{ color: rippleStyle.backgroundColor }} unstable_pressDelay={Platform.OS === "android" ? 50 : undefined} - className={cn( - props.selected ? "bg-subtle" : "bg-grouped-card", - props.separated && "border-t border-border-subtle", - )} + // Like UIKit and Material lists, only the checkmark or radio marks the selected row. + className={cn("bg-grouped-card", props.separated && "border-t border-border-subtle")} > void; - /** Whether any filter, the environment, or a non-default sort is active. */ - readonly customized: boolean; -} - -const MenuContext = createContext(null); -const PublishContext = createContext> | null>( - null, -); - -/** - * The Android PR header opens the full filter menu, but the facets (authors, labels) and the - * controls live in the list below it. The list publishes its menu here; only the header reads - * it, so the list's own renders don't fan out. - */ -export function PullRequestFilterMenuProvider(props: { readonly children: ReactNode }) { - const [menu, setMenu] = useState(null); - return ( - - {props.children} - - ); -} - -export function usePullRequestFilterMenu() { - return use(MenuContext); -} - -export function usePublishPullRequestFilterMenu(menu: PullRequestFilterMenu | null) { - const publish = use(PublishContext); - // A layout effect, so the header's filter button lands in the same frame as the list. There is - // no cleanup: the list lives exactly as long as this provider, and a hidden tab runs its - // cleanups, which would drop the button for a few frames every time the tab came back. - useLayoutEffect(() => { - if (publish && menu) publish(menu); - }, [publish, menu]); -} diff --git a/apps/mobile/src/features/pull-requests/PullRequestListFilters.tsx b/apps/mobile/src/features/pull-requests/PullRequestListFilters.tsx index d7359680d3f1a..a9a5abaaea8ad 100644 --- a/apps/mobile/src/features/pull-requests/PullRequestListFilters.tsx +++ b/apps/mobile/src/features/pull-requests/PullRequestListFilters.tsx @@ -1,10 +1,13 @@ +import { useAtomValue } from "@effect/atom-react"; import { sortProjectsByGroupOrder } from "@t3tools/client-runtime/state/project-grouping"; +import type { ScopedProjectRef, SidebarProjectGroupingMode } from "@t3tools/contracts"; +import { Atom } from "effect/reactivity"; import { useMemo } from "react"; import { Platform, ScrollView } from "react-native"; import type { MenuProps } from "../../components/ui/Menu.types"; import { ListFilterMenu } from "../workspace/ListFilterMenu"; -import { usePublishPullRequestFilterMenu } from "./PullRequestFilterMenuContext"; -import { useProjects, useThreadShells } from "../../state/entities"; +import { environmentProjects } from "../../state/projects"; +import { environmentThreadShells } from "../../state/threads"; import { useMobileProjectGroupingSettings } from "../../state/project-grouping"; import { buildHomeProjectScopes, sortHomeProjectScopes } from "../home/homeThreadList"; import { DEFAULT_PR_LIST_CONTROLS, type PullRequestListControls } from "./pullRequestList"; @@ -39,32 +42,58 @@ function choices(field: string, options: Readonly>, selec })); } +type ProjectOrder = readonly { readonly memberProjectRefs: readonly ScopedProjectRef[] }[]; +const sameProjectOrder = (previous: ProjectOrder, next: ProjectOrder) => + previous.length === next.length && + previous.every((group, index) => { + const members = next[index]!.memberProjectRefs; + return ( + group.memberProjectRefs.length === members.length && + group.memberProjectRefs.every( + (ref, member) => + ref.environmentId === members[member]!.environmentId && + ref.projectId === members[member]!.projectId, + ) + ); + }); + +// Thread shells change on every agent tick, but the sidebar order they decide rarely does. The +// equality check keeps the list screen, which builds these filters, from re-rendering on each tick. +const sidebarProjectOrderFamily = Atom.family((mode: SidebarProjectGroupingMode) => + Atom.make((get) => + sortHomeProjectScopes({ + scopes: buildHomeProjectScopes({ + projects: get(environmentProjects.projectsAtom), + environmentId: null, + projectGroupingMode: mode, + }), + threads: get(environmentThreadShells.threadShellsAtom), + pendingTasks: [], + projectSortOrder: "updated_at", + }).map((scope) => ({ memberProjectRefs: scope.projectRefs })), + ).pipe(Atom.withEquality(sameProjectOrder)), +); + function useProjectsInSidebarOrder( projects: readonly Project[], ) { - const allProjects = useProjects(); - const threads = useThreadShells(); const { sidebarProjectGroupingMode } = useMobileProjectGroupingSettings(); - const scopes = useMemo( - () => - sortHomeProjectScopes({ - scopes: buildHomeProjectScopes({ - projects: allProjects, - environmentId: null, - projectGroupingMode: sidebarProjectGroupingMode, - }), - threads, - pendingTasks: [], - projectSortOrder: "updated_at", - }).map((scope) => ({ memberProjectRefs: scope.projectRefs })), - [allProjects, sidebarProjectGroupingMode, threads], - ); + const scopes = useAtomValue(sidebarProjectOrderFamily(sidebarProjectGroupingMode)); return useMemo(() => sortProjectsByGroupOrder(projects, scopes), [projects, scopes]); } -export function PullRequestListFilters(props: { - /** Android sidebar rows sit further in than full-width rows; the pills follow them. */ - readonly sidebar?: boolean; +export interface PullRequestFilterMenu { + readonly actions: MenuProps["actions"]; + readonly onSelect: (id: string) => void; + /** Whether any filter, the environment, or a non-default sort is active. */ + readonly customized: boolean; +} + +/** + * Builds the filter pills and, on Android, the header's full filter menu. The list screen owns + * the call so both the pills and the header it frames read the same menu. + */ +export function usePullRequestListFilters(props: { readonly environments: readonly { id: string; label: string }[]; readonly environmentId: string | null; readonly onEnvironmentChange: (id: string | null) => void; @@ -280,7 +309,7 @@ export function PullRequestListFilters(props: { ]; const customized = count > 0 || value.sort !== "updated" || props.environmentId !== null; // The Android header's filter button opens every filter. - const headerMenu = + const headerMenu: PullRequestFilterMenu | null = Platform.OS === "android" ? { actions: [ @@ -296,7 +325,35 @@ export function PullRequestListFilters(props: { customized, } : null; - usePublishPullRequestFilterMenu(headerMenu); + return { + headerMenu, + select, + count, + more, + reset, + environmentLabel: + props.environments.length > 1 + ? (props.environments.find((environment) => environment.id === props.environmentId) + ?.label ?? "All environments") + : null, + environmentActions, + state: value.state, + stateActions, + involvement: value.involvement, + involvementActions, + selectedLabelCount: selectedLabels.length, + labelActions, + author, + authorActions, + }; +} + +export function PullRequestListFilters(props: { + /** Android sidebar rows sit further in than full-width rows; the pills follow them. */ + readonly sidebar?: boolean; + readonly filters: ReturnType; +}) { + const { count, more, reset, select, author, selectedLabelCount } = props.filters; return ( )} - {props.environments.length > 1 ? ( + {props.filters.environmentLabel !== null ? ( environment.id === props.environmentId) - ?.label ?? "All environments" - } + label={props.filters.environmentLabel} accessibilityLabel="Choose pull request environment" - actions={environmentActions} + actions={props.filters.environmentActions} onSelect={select} /> ) : null} 0} + label={selectedLabelCount ? `Labels ${selectedLabelCount}` : "Labels"} + active={selectedLabelCount > 0} accessibilityLabel="Filter by label" - actions={labelActions} + actions={props.filters.labelActions} onSelect={select} /> diff --git a/apps/mobile/src/features/pull-requests/PullRequestReviewersScreen.tsx b/apps/mobile/src/features/pull-requests/PullRequestReviewersScreen.tsx index 1fa5cd83b874f..829a62d4b4b7f 100644 --- a/apps/mobile/src/features/pull-requests/PullRequestReviewersScreen.tsx +++ b/apps/mobile/src/features/pull-requests/PullRequestReviewersScreen.tsx @@ -7,7 +7,7 @@ import { useNavigation, type StaticScreenProps } from "@react-navigation/native" import { squashAtomCommandFailure } from "@t3tools/client-runtime/state/runtime"; import { sourceControlClients } from "@t3tools/client-runtime/source-control-clients"; import type { PullRequestReviewerCandidate } from "@t3tools/contracts"; -import { useEffect, useRef, useState } from "react"; +import { useRef, useState } from "react"; import { FlatList, Platform, @@ -86,13 +86,14 @@ export function PullRequestReviewersScreen({ route }: StaticScreenProps Number(b.isRequested) - Number(a.isRequested) || a.login.localeCompare(b.login), ); })(); - useEffect(() => { - if (candidates.length === 0) return; + // A new search shows its best matches from the top. + const search = (next: string) => { + setQuery(next); listRef.current?.scrollToOffset({ offset: Platform.OS === "ios" ? -insets.top : 0, animated: false, }); - }, [candidates, insets.top]); + }; const update = async ( candidate: Pick, ) => { @@ -118,7 +119,7 @@ export function PullRequestReviewersScreen({ route }: StaticScreenProps setQuery(event.nativeEvent.text), - onCancelButtonPress: () => setQuery(""), + onChangeText: (event: { nativeEvent: { text: string } }) => search(event.nativeEvent.text), + onCancelButtonPress: () => search(""), hideNavigationBar: false, hideWhenScrolling: false, obscureBackground: false, @@ -150,7 +151,7 @@ export function PullRequestReviewersScreen({ route }: StaticScreenProps @@ -287,7 +288,7 @@ export function PullRequestReviewersScreen({ route }: StaticScreenProps void }) { +export function PullRequestToolbar(props: { + readonly filters: PullRequestFilterMenu | null; + readonly onRequestVisibility?: () => void; +}) { const navigation = useNavigation(); - const filters = usePullRequestFilterMenu(); + const { filters } = props; const workspace = useWorkspaceTabs()!; const { dispatch, getScrollOffset, recordScrollOffset, isTabActive } = workspace; - const homeFocused = useNavigationState((state) => state.routes[state.index]?.name === "Home"); - const listFocused = homeFocused && workspace.state.selectedTab === "pullRequests"; const { onRequestVisibility } = props; const tab = workspace.state.tabs.pullRequests; const input = useRef(null); @@ -41,9 +42,10 @@ export function PullRequestToolbar(props: { readonly onRequestVisibility?: () => dispatch({ type: "cancel", tab: "pullRequests" }); }, [dispatch, recordScrollOffset, tab.searchEntryOffset]); useEffect(() => { - if (!searching || !listFocused) return; + if (!searching) return; const subscription = BackHandler.addEventListener("hardwareBackPress", () => { - // Frozen Home screens can keep effects alive after a detail route opens. + // Frozen Home screens stay mounted under a detail route or another tab, + // so back only applies while the PR list is in front. const state = navigation.getState(); if (!state || state.routes[state.index]?.name !== "Home" || !isTabActive("pullRequests")) return false; @@ -52,7 +54,7 @@ export function PullRequestToolbar(props: { readonly onRequestVisibility?: () => return true; }); return () => subscription.remove(); - }, [searching, closeSearch, listFocused, navigation, isTabActive]); + }, [searching, closeSearch, navigation, isTabActive]); const { paddingTop, paddingBottom } = useToolbarLayout(); return ( diff --git a/apps/mobile/src/features/pull-requests/PullRequestsScreen.tsx b/apps/mobile/src/features/pull-requests/PullRequestsScreen.tsx index 1554c184d3906..096f12c4204b3 100644 --- a/apps/mobile/src/features/pull-requests/PullRequestsScreen.tsx +++ b/apps/mobile/src/features/pull-requests/PullRequestsScreen.tsx @@ -6,7 +6,7 @@ import { import { AppActivityIndicator } from "../../components/ui/AppActivityIndicator"; import { LegendList, type LegendListRef } from "@legendapp/list/react-native"; import { useNavigation } from "@react-navigation/native"; -import { use, useCallback, useEffect, useMemo, useRef, useState } from "react"; +import { use, useCallback, useEffect, useMemo, useRef, useState, type ReactNode } from "react"; import { useAtomValue } from "@effect/atom-react"; import { Keyboard, @@ -26,7 +26,11 @@ import { useWorkspaceState } from "../../state/workspace"; import { useProjects } from "../../state/entities"; import { environmentServerConfigsAtom } from "../../state/server"; import { PullRequestListRow } from "./PullRequestListRow"; -import { PullRequestListFilters } from "./PullRequestListFilters"; +import { + PullRequestListFilters, + usePullRequestListFilters, + type PullRequestFilterMenu, +} from "./PullRequestListFilters"; import { PullRequestCardRow } from "./PullRequestControls"; import { usePullRequestList } from "./usePullRequestList"; import { usePullRequestListControls } from "./usePullRequestListControls"; @@ -79,6 +83,11 @@ export function PullRequestsScreen( props: { readonly sidebar?: boolean; readonly selectedPullRequestKey?: string | null; + /** + * Places the list under a header that opens the full filter menu (the Android toolbar). The + * filters live here, so the header gets them in the same render as the list. + */ + readonly renderFrame?: (filters: PullRequestFilterMenu | null, list: ReactNode) => ReactNode; } = {}, ) { const navigation = useNavigation(); @@ -87,9 +96,23 @@ export function PullRequestsScreen( const { environments } = useWorkspaceState(); const configs = useAtomValue(environmentServerConfigsAtom); const insets = useSafeAreaInsets(); - const [initialOffset] = useState(() => workspace.getScrollOffset("pullRequests")); const listRef = useRef(null); const tab = workspace.state.tabs.pullRequests; + const [initialScrollOffset] = useState(() => workspace.getScrollOffset("pullRequests")); + // Cancelling search restores the offset recorded when search opened. The + // toolbar that cancels has no handle on this list, so the list scrolls itself + // once it sees the tab come back to resting. + const previousSearchMode = useRef(tab.searchMode); + useEffect(() => { + const restoringSearch = + previousSearchMode.current !== "resting" && tab.searchMode === "resting"; + previousSearchMode.current = tab.searchMode; + if (restoringSearch) + void listRef.current?.scrollToOffset({ + offset: tab.scrollOffset - (Platform.OS === "ios" ? insets.top : 0), + animated: false, + }); + }, [tab.searchMode, tab.scrollOffset, insets.top]); const maintainVisiblePosition = useMemo( () => ({ data: tab.searchMode === "resting", @@ -203,6 +226,39 @@ export function PullRequestsScreen( (project) => !project.isScratch && (environmentId === null || project.environmentId === environmentId), ); + const filters = usePullRequestListFilters({ + environments: environments.map((item) => ({ + id: String(item.environmentId), + label: item.environmentLabel, + })), + environmentId, + onEnvironmentChange: listControls.setEnvironmentId, + value: typedDraft + ? { ...controls, filters: { ...controls.filters, draft: typedDraft } } + : controls, + onChange: (next) => { + const update = applyPullRequestDraftFilterChange(typedQuery, controls.filters, next.filters); + listControls.setControls(environmentId, { ...next, filters: update.filters }); + if (update.query !== typedQuery) + workspace.dispatch({ type: "query", tab: "pullRequests", query: update.query }); + void listRef.current?.scrollToOffset({ + offset: Platform.OS === "ios" ? -insets.top : 0, + animated: false, + }); + }, + authors: knownFacets.environmentId === environmentId ? knownFacets.authors : facets.authors, + labels: knownFacets.environmentId === environmentId ? knownFacets.labels : facets.labels, + labelColors, + projects, + onSearch: (kind) => + navigation.navigate("PullRequestFilterSearch", { + kind, + environmentId, + environmentIds: targets.map((target) => String(target.environmentId)), + suggestions: knownFacets.environmentId === environmentId ? knownFacets[kind] : facets[kind], + labelColors, + }), + }); const renderPullRequest = useCallback( ({ item }: { readonly item: EnvironmentPullRequestListEntry }) => ( { - const restoringSearch = - previousSearchMode.current !== "resting" && tab.searchMode === "resting"; - previousSearchMode.current = tab.searchMode; - if (restoringSearch) - void listRef.current?.scrollToOffset({ - offset: tab.scrollOffset - (Platform.OS === "ios" ? insets.top : 0), - animated: false, - }); - }, [tab.searchMode, tab.scrollOffset, insets.top]); - - return ( + const list = ( 0 ? initialOffset - (Platform.OS === "ios" ? insets.top : 0) : undefined + initialScrollOffset > 0 + ? initialScrollOffset - (Platform.OS === "ios" ? insets.top : 0) + : undefined } contentInsetStartAdjustment={Platform.OS === "ios" ? insets.top : 0} contentContainerStyle={{ @@ -285,52 +331,7 @@ export function PullRequestsScreen( renderItem={renderPullRequest} ListHeaderComponent={ <> - ({ - id: String(item.environmentId), - label: item.environmentLabel, - }))} - environmentId={environmentId} - onEnvironmentChange={listControls.setEnvironmentId} - value={ - typedDraft - ? { ...controls, filters: { ...controls.filters, draft: typedDraft } } - : controls - } - onChange={(next) => { - const update = applyPullRequestDraftFilterChange( - typedQuery, - controls.filters, - next.filters, - ); - listControls.setControls(environmentId, { ...next, filters: update.filters }); - if (update.query !== typedQuery) - workspace.dispatch({ type: "query", tab: "pullRequests", query: update.query }); - void listRef.current?.scrollToOffset({ - offset: Platform.OS === "ios" ? -insets.top : 0, - animated: false, - }); - }} - authors={ - knownFacets.environmentId === environmentId ? knownFacets.authors : facets.authors - } - labels={ - knownFacets.environmentId === environmentId ? knownFacets.labels : facets.labels - } - labelColors={labelColors} - projects={projects} - onSearch={(kind) => - navigation.navigate("PullRequestFilterSearch", { - kind, - environmentId, - environmentIds: targets.map((target) => String(target.environmentId)), - suggestions: - knownFacets.environmentId === environmentId ? knownFacets[kind] : facets[kind], - labelColors, - }) - } - /> + {result.data?.errors.length ? ( ); + return props.renderFrame ? props.renderFrame(filters.headerMenu, list) : list; } diff --git a/apps/mobile/src/features/pull-requests/pullRequestFilesViewed.test.ts b/apps/mobile/src/features/pull-requests/pullRequestFilesViewed.test.ts new file mode 100644 index 0000000000000..ee438e6187215 --- /dev/null +++ b/apps/mobile/src/features/pull-requests/pullRequestFilesViewed.test.ts @@ -0,0 +1,24 @@ +import type { PullRequestFilesViewedResult } from "@t3tools/contracts"; +import { describe, expect, it } from "vite-plus/test"; +import { viewedOverlay } from "./pullRequestFilesViewed"; + +// The overlay compares reads by identity, so each call is a distinct read. +const read = (): PullRequestFilesViewedResult => ({ files: [], truncated: false }); + +describe("viewedOverlay", () => { + it("keeps a press while its write is in flight", () => { + const before = read(); + expect( + viewedOverlay({ "a.ts": { viewed: true, version: 1, awaitingReadAfter: undefined } }, before), + ).toEqual({ "a.ts": true }); + }); + + it("keeps a landed press until a read newer than the one current at the write", () => { + const before = read(); + const presses = { + "a.ts": { viewed: true, version: 1, awaitingReadAfter: { read: before } }, + }; + expect(viewedOverlay(presses, before)).toEqual({ "a.ts": true }); + expect(viewedOverlay(presses, read())).toEqual({}); + }); +}); diff --git a/apps/mobile/src/features/pull-requests/pullRequestFilesViewed.ts b/apps/mobile/src/features/pull-requests/pullRequestFilesViewed.ts new file mode 100644 index 0000000000000..b76d3193c9c8e --- /dev/null +++ b/apps/mobile/src/features/pull-requests/pullRequestFilesViewed.ts @@ -0,0 +1,28 @@ +import type { PullRequestFilesViewedResult } from "@t3tools/contracts"; + +export type FilesViewedRead = PullRequestFilesViewedResult | null; + +export interface ViewedPress { + readonly viewed: boolean; + readonly version: number; + /** Set once the write lands: the press yields to the server once a read newer than this lands. */ + readonly awaitingReadAfter: { readonly read: FilesViewedRead } | undefined; +} + +export interface ViewedState { + readonly key: string; + readonly presses: Readonly>; + readonly error: string | null; +} + +/** The pressed states the server's read has not caught up with yet. */ +export function viewedOverlay( + presses: Readonly>, + read: FilesViewedRead, +): Record { + const overlay: Record = {}; + for (const [path, press] of Object.entries(presses)) + if (press.awaitingReadAfter === undefined || press.awaitingReadAfter.read === read) + overlay[path] = press.viewed; + return overlay; +} diff --git a/apps/mobile/src/features/pull-requests/usePullRequestFilesViewed.ts b/apps/mobile/src/features/pull-requests/usePullRequestFilesViewed.ts index cf882ac0daee2..46f6f941806a7 100644 --- a/apps/mobile/src/features/pull-requests/usePullRequestFilesViewed.ts +++ b/apps/mobile/src/features/pull-requests/usePullRequestFilesViewed.ts @@ -1,15 +1,19 @@ import { usePullRequestConnected } from "./usePullRequestConnected"; -import { useAtomRefresh, useAtomValue } from "@effect/atom-react"; +import { RegistryContext, useAtomRefresh, useAtomValue } from "@effect/atom-react"; import { squashAtomCommandFailure } from "@t3tools/client-runtime/state/runtime"; import type { PullRequestDetail } from "@t3tools/contracts"; -import { useCallback, useEffect, useRef, useState } from "react"; +import * as Option from "effect/Option"; +import { AsyncResult } from "effect/reactivity"; +import { use, useState } from "react"; import { composerPullRequests } from "../../state/pull-requests"; import { useEnvironmentQuery } from "../../state/query"; import { useAtomCommand } from "../../state/use-atom-command"; import { pullRequestTarget, type PullRequestParams } from "./usePullRequestDiff"; import { pullRequestReviewKey } from "./pullRequestReviewDrafts"; +import { viewedOverlay, type ViewedState } from "./pullRequestFilesViewed"; export function usePullRequestFilesViewed(params: PullRequestParams, pr: PullRequestDetail | null) { + const registry = use(RegistryContext); const target = pullRequestTarget(params); const scopeKey = pullRequestReviewKey(params); const supported = Boolean(pr?.capabilities.viewedFiles); @@ -21,90 +25,53 @@ export function usePullRequestFilesViewed(params: PullRequestParams, pr: PullReq const query = useEnvironmentQuery(supported ? composerPullRequests.filesViewed(target) : null); const refresh = useAtomRefresh(composerPullRequests.filesViewed(target)); const write = useAtomCommand(composerPullRequests.setFilesViewed, { reportFailure: false }); - const [state, setState] = useState<{ - key: string; - overlay: Record; - error: string | null; - }>({ key: scopeKey, overlay: {}, error: null }); - const overlay = state.key === scopeKey ? state.overlay : {}; + const [state, setState] = useState({ key: scopeKey, presses: {}, error: null }); + const presses = state.key === scopeKey ? state.presses : {}; const error = state.key === scopeKey ? state.error : null; - const setOverlay = useCallback( - (overlay: Record) => - setState((current) => ({ - key: scopeKey, - overlay, - error: current.key === scopeKey ? current.error : null, - })), - [scopeKey], - ); - const setError = (error: string | null) => - setState((current) => ({ - key: scopeKey, - error, - overlay: current.key === scopeKey ? current.overlay : {}, - })); - const versions = useRef(new Map()); - const pressed = useRef>({}); - const reads = useRef(query.data); - useEffect(() => { - reads.current = query.data; - }, [query.data]); - const awaitingRead = useRef(new Map()); - const scope = useRef(scopeKey); - useEffect(() => { - scope.current = scopeKey; - versions.current.clear(); - awaitingRead.current.clear(); - pressed.current = {}; - }, [scopeKey]); - useEffect(() => { - if (supported && pr?.headSha) refresh(); - }, [supported, pr?.headSha, refresh]); - useEffect(() => { - let changed = false; - const next = { ...pressed.current }; - for (const [path, from] of awaitingRead.current) { - if (from === query.data) continue; - delete next[path]; - awaitingRead.current.delete(path); - changed = true; - } - if (changed) { - pressed.current = next; - setOverlay(next); - } - }, [query.data, setOverlay]); - const isViewed = (path: string) => - overlay[path] ?? - query.data?.files.some((file) => file.path === path && file.state === "viewed") ?? - false; + const overlay = viewedOverlay(presses, query.data); + const update = (change: (current: ViewedState) => ViewedState) => + setState((current) => + change(current.key === scopeKey ? current : { key: scopeKey, presses: {}, error: null }), + ); + const serverViewed = (path: string) => + query.data?.files.some((file) => file.path === path && file.state === "viewed") ?? false; + const isViewed = (path: string) => overlay[path] ?? serverViewed(path); const toggle = async (path: string) => { if (!supported || !allowed || !query.data) return; - const viewed = !( - pressed.current[path] ?? - query.data.files.some((file) => file.path === path && file.state === "viewed") - ); - const version = (versions.current.get(path) ?? 0) + 1; - versions.current.set(path, version); - awaitingRead.current.delete(path); - pressed.current = { ...pressed.current, [path]: viewed }; - setOverlay(pressed.current); - setError(null); + const viewed = !isViewed(path); + const version = (presses[path]?.version ?? 0) + 1; + update((current) => ({ + ...current, + error: null, + presses: { ...current.presses, [path]: { viewed, version, awaitingReadAfter: undefined } }, + })); const response = await write({ ...target, input: { ...target.input, files: [{ path, viewed }] }, }); - if (scope.current !== scopeKey) return; - if (response._tag === "Failure" && versions.current.get(path) === version) { - const next = { ...pressed.current }; - delete next[path]; - pressed.current = next; - setOverlay(next); + // The read that is current once the write lands still predates it; a newer one carries it. + const readAtWrite = Option.getOrNull( + AsyncResult.value(registry.get(composerPullRequests.filesViewed(target))), + ); + setState((current) => { + if (current.key !== scopeKey || current.presses[path]?.version !== version) return current; + if (response._tag === "Success") + return { + ...current, + presses: { + ...current.presses, + [path]: { viewed, version, awaitingReadAfter: { read: readAtWrite } }, + }, + }; + const rest = { ...current.presses }; + delete rest[path]; const cause = squashAtomCommandFailure(response); - setError(cause instanceof Error ? cause.message : "Could not update viewed files."); - } - if (response._tag === "Success" && versions.current.get(path) === version) - awaitingRead.current.set(path, reads.current); + return { + ...current, + presses: rest, + error: cause instanceof Error ? cause.message : "Could not update viewed files.", + }; + }); refresh(); }; return { diff --git a/apps/mobile/src/features/pull-requests/usePullRequestList.ts b/apps/mobile/src/features/pull-requests/usePullRequestList.ts index 73dad15cafd2f..477caa0559b19 100644 --- a/apps/mobile/src/features/pull-requests/usePullRequestList.ts +++ b/apps/mobile/src/features/pull-requests/usePullRequestList.ts @@ -1,6 +1,6 @@ import { RegistryContext, useAtomValue } from "@effect/atom-react"; import { executeAtomQuery, squashAtomCommandFailure } from "@t3tools/client-runtime/state/runtime"; -import type { EnvironmentId, PullRequestListInput } from "@t3tools/contracts"; +import type { EnvironmentId, PullRequestDiffStat, PullRequestListInput } from "@t3tools/contracts"; import * as Cause from "effect/Cause"; import * as Effect from "effect/Effect"; import * as Option from "effect/Option"; @@ -156,15 +156,20 @@ export function usePullRequestList(targets: readonly ListTarget[]) { // Starting one kind of load clears the other, so at most one holds an error. const loadError = settledError(refresh) ?? settledError(page); + // Read from the registry, not the render: a second onEndReached before React re-renders must + // see the load the first one started. const loadMore = (retry = false) => { - if (page.waiting || refresh.waiting || (!retry && loadError)) return; + const pageResult = registry.get(pageAtom); + const refreshResult = registry.get(refreshAtom); + if (pageResult.waiting || refreshResult.waiting) return; + if (!retry && (settledError(refreshResult) ?? settledError(pageResult))) return; if (!continuations(registry, targets).length) return; registry.set(refreshAtom, Atom.Reset); registry.set(pageAtom, retry); }; const onRefresh = () => { - if (!targets.length || refresh.waiting) return; + if (!targets.length || registry.get(refreshAtom).waiting) return; registry.set(pageAtom, Atom.Reset); registry.set(refreshAtom, undefined); }; @@ -249,16 +254,13 @@ export function usePullRequestList(targets: readonly ListTarget[]) { }, [statsKey]); const counts = useAtomValue(statsAtom); // Server answers land in pullRequestListStatsFamily; these cover a cached answer, which is - // all an offline environment has. + // all an offline environment has. Scrolling makes a new stats query, which has no answer until + // its cached rows load, so each environment keeps the answer it showed until the new one lands. + const [shown, setShown] = useState({ counts, answers: answeredStats(counts, []) }); + if (shown.counts !== counts) setShown({ counts, answers: answeredStats(counts, shown.answers) }); const entries = useMemo( - () => - withShownPullRequestStats( - data.entries, - counts.flatMap(({ environmentId, result }) => - AsyncResult.isSuccess(result) ? [{ environmentId, stats: result.value.stats }] : [], - ), - ), - [data.entries, counts], + () => withShownPullRequestStats(data.entries, shown.answers), + [data.entries, shown.answers], ); const updateEntry = useCallback( @@ -332,3 +334,32 @@ function requestErrors(results: readonly PromiseSettledResult[]) { .join("\n") || null ); } + +type StatsAnswer = { + readonly environmentId: EnvironmentId; + readonly stats: readonly PullRequestDiffStat[]; +}; + +/** Each environment's newest stats answer, or the one it had while its query has none. */ +function answeredStats( + counts: readonly { + readonly environmentId: EnvironmentId; + readonly result: AsyncResult.AsyncResult< + { readonly stats: readonly PullRequestDiffStat[] }, + unknown + >; + }[], + previous: readonly StatsAnswer[], +): readonly StatsAnswer[] { + const next = counts.flatMap(({ environmentId, result }) => { + const kept = previous.find((answer) => answer.environmentId === environmentId); + if (!AsyncResult.isSuccess(result)) return kept ? [kept] : []; + return kept?.stats === result.value.stats + ? [kept] + : [{ environmentId, stats: result.value.stats }]; + }); + return next.length === previous.length && + next.every((answer, index) => answer === previous[index]) + ? previous + : next; +} diff --git a/apps/mobile/src/features/settings/SettingsAboutRouteScreen.tsx b/apps/mobile/src/features/settings/SettingsAboutRouteScreen.tsx index 5267130b1b39f..096513c0e0a3c 100644 --- a/apps/mobile/src/features/settings/SettingsAboutRouteScreen.tsx +++ b/apps/mobile/src/features/settings/SettingsAboutRouteScreen.tsx @@ -23,7 +23,7 @@ export function SettingsAboutRouteScreen() { const insets = useSafeAreaInsets(); return ( - + - navigation.goBack()} /> + navigation.goBack()} /> ) : null} props.onHeight(event.nativeEvent.layout.height)} className={cn( - "flex-row items-center gap-4 pl-4", + "flex-row items-center", props.position > 1 && !lifted && "border-t border-border-subtle", lifted && "bg-grouped-card shadow-md", - !props.reorderable && "pr-4", )} > {props.editing && props.onForget ? ( @@ -264,7 +264,7 @@ function MicrophoneRow(props: { accessibilityLabel={`Forget ${title}`} hitSlop={8} onPress={props.onForget} - className="active:opacity-70" + className="pl-4 active:opacity-70" > ) : props.editing ? ( - + + + ) : null} - - - - {title} - - - {isMicrophoneDevice(entry) ? kind.label : kind.rowDescription} - - {props.reorderable ? ( + ))} + ); diff --git a/apps/mobile/src/features/settings/SettingsProjectOverviewRouteScreen.tsx b/apps/mobile/src/features/settings/SettingsProjectOverviewRouteScreen.tsx index c252ddd81b398..c848304e75167 100644 --- a/apps/mobile/src/features/settings/SettingsProjectOverviewRouteScreen.tsx +++ b/apps/mobile/src/features/settings/SettingsProjectOverviewRouteScreen.tsx @@ -83,7 +83,7 @@ export function SettingsProjectOverviewRouteScreen() { return ( <> - }> + }> - {members.length === 0 ? ( + {selectedProjectKey === null ? ( + + Choose a project with the filter above to manage its name, checkouts and removal. + + ) : members.length === 0 ? ( This project has no checkout on the selected connected environments. Change the filter above. diff --git a/apps/mobile/src/features/settings/SettingsProviderAccountsRouteScreen.tsx b/apps/mobile/src/features/settings/SettingsProviderAccountsRouteScreen.tsx index 25cd506a55366..dfb07954a3acd 100644 --- a/apps/mobile/src/features/settings/SettingsProviderAccountsRouteScreen.tsx +++ b/apps/mobile/src/features/settings/SettingsProviderAccountsRouteScreen.tsx @@ -38,7 +38,7 @@ export function SettingsProviderAccountsRouteScreen() { return ( <> - }> + }> {sections.length ? ( - sections.map((section) => ( - + sections.map((section, index) => ( + {section.rows.map(({ id, ...row }) => ( ))} @@ -229,11 +229,13 @@ function useSettingsIndexSections(): SettingsListSection[] { ): SettingsListRow => ({ id: target, icon, label, target, ...extra }); const serverPage = (target: SettingsPageTarget, icon: SettingsListRow["icon"], label: string) => page(target, icon, label, { disabled: noServerTargets }); + // The same pages and groups as Settings on web, minus what mobile has no setting for. return [ { - title: "Interface", rows: [ + page("SettingsOrganization", "gearshape", "General"), page("SettingsAppearance", "paintbrush", "Appearance"), + page("SettingsFollowUp", "bubble.left.and.bubble.right", "Chat"), ...(navigationCustomizationAvailable() ? [page("SettingsNavigation", "line.3.horizontal", "Navigation tabs")] : []), @@ -246,34 +248,33 @@ function useSettingsIndexSections(): SettingsListSection[] { ], }, { - title: "Automations", - rows: [page("SettingsScheduledTasks", "clock", "Scheduled tasks")], - }, - { - title: "Projects & threads", + title: "Agents", rows: [ - ...(selectedProjectKey !== null - ? [page("SettingsProjectOverview", "folder", "Overview", { value: projectLabel })] - : []), - page("SettingsOrganization", "folder", "Organization"), - page("SettingsThreads", "text.bubble", "Thread behavior"), - page("SettingsFollowUp", "arrow.turn.left.up", "Follow-ups"), - page("SettingsArchive", "archivebox", "Archived Threads"), + serverPage("SettingsProviderAccounts", "person.crop.circle", "Providers"), + serverPage("SettingsThreads", "text.bubble", "Threads"), + page("SettingsScheduledTasks", "clock", "Scheduled tasks"), ], }, { - title: "Server settings", + title: "Code", rows: [ - serverPage("SettingsProviderAccounts", "person.crop.circle", "Provider accounts"), - serverPage("SettingsEnvironmentNewThreads", "text.bubble", "New threads"), + page( + "SettingsProjectOverview", + "folder", + "Projects", + selectedProjectKey !== null ? { value: projectLabel } : undefined, + ), serverPage("SettingsEnvironmentSourceControl", "arrow.triangle.branch", "Source control"), - serverPage("SettingsEnvironmentAgentBehavior", "text.alignleft", "Agent behavior"), - serverPage("SettingsEnvironmentMaintenance", "arrow.clockwise", "Maintenance"), + serverPage("SettingsWorktrees", "square.on.square", "Worktrees"), ], }, { - title: "App", - rows: [page("SettingsAbout", "info.circle", "About T3 Code")], + rows: [ + serverPage("SettingsEnvironmentMaintenance", "arrow.clockwise", "Maintenance"), + page("SettingsLabs", "sparkles", "Labs"), + page("SettingsAbout", "info.circle", "About"), + page("SettingsArchive", "archivebox", "Archive"), + ], }, ]; } diff --git a/apps/mobile/src/features/settings/SettingsScheduledTasksRouteScreen.tsx b/apps/mobile/src/features/settings/SettingsScheduledTasksRouteScreen.tsx index bc768b32ff875..d16e08035ca75 100644 --- a/apps/mobile/src/features/settings/SettingsScheduledTasksRouteScreen.tsx +++ b/apps/mobile/src/features/settings/SettingsScheduledTasksRouteScreen.tsx @@ -186,7 +186,11 @@ function SelectRow(props: { const value = ( {props.valueIcon} - + {props.value} @@ -200,7 +204,9 @@ function SelectRow(props: { : "min-h-14 flex-row items-center gap-3 px-4 py-3" } > - {props.label} + + {props.label} + {value} ); @@ -219,7 +225,9 @@ function SelectRow(props: { : "min-h-14 flex-row items-center gap-3 px-4 py-3 active:opacity-70" } > - {props.label} + + {props.label} + {value} props.onChange([...props.filters, emptyWebhookFilterDraft()])} className="min-h-14 flex-row items-center gap-3 border-t border-border-subtle px-4 py-3 active:opacity-70" > - Add filter + + Add filter + ) : null} @@ -330,8 +340,14 @@ function PickerRow(props: { : "min-h-14 flex-row items-center gap-3 px-4 py-3 active:opacity-70 disabled:opacity-50" } > - {props.label} - + + {props.label} + + {props.value} @@ -962,8 +978,13 @@ function TaskForm({ onPress={() => setTimePickerOpen((open) => !open)} className="min-h-14 flex-row items-center gap-3 border-t border-border-subtle px-4 py-3 active:opacity-70" > - Time - + + Time + + {formatTime(draft.schedule.timeOfDay)} )} - Enabled + + Enabled + void tryCopyTextWithHaptic(resolved.address)} className="gap-1 active:opacity-70" > - + {resolved.copyable ? "Webhook URL" : "Webhook path"} @@ -1310,8 +1333,8 @@ function EnvironmentTasks({ key={task.id} className={ index === 0 - ? "flex-row items-start gap-1 px-4 py-4" - : "flex-row items-start gap-1 border-t border-border-subtle px-4 py-4" + ? "flex-row items-start gap-1 px-4 py-3" + : "flex-row items-start gap-1 border-t border-border-subtle px-4 py-3" } > - + {task.title} diff --git a/apps/mobile/src/features/settings/SettingsServerControlsRouteScreen.test.tsx b/apps/mobile/src/features/settings/SettingsServerControlsRouteScreen.test.tsx index 6cf6a8853d5ae..179eceba6c6fd 100644 --- a/apps/mobile/src/features/settings/SettingsServerControlsRouteScreen.test.tsx +++ b/apps/mobile/src/features/settings/SettingsServerControlsRouteScreen.test.tsx @@ -12,6 +12,7 @@ const { Children, mocks } = vi.hoisted(() => ({ updateSettings: vi.fn(), alert: vi.fn(), targets: [] as ReturnType[], + readOnly: new Set(), projectSelected: false, }, })); @@ -48,7 +49,12 @@ vi.mock("react-native-safe-area-context", () => ({ useSafeAreaInsets: () => ({ b vi.mock("@react-navigation/native", () => ({ useNavigation: () => ({}) })); vi.mock("../../state/session", () => ({ readEnvironmentScope: () => true, - useEnvironmentsWithScope: () => new Set(mocks.targets.map((target) => target.environmentId)), + useEnvironmentsWithScope: () => + new Set( + mocks.targets + .map((target) => target.environmentId) + .filter((environmentId) => !mocks.readOnly.has(environmentId)), + ), })); vi.mock("../../state/server", () => ({ serverEnvironment: { updateSettings: {} } })); vi.mock("../../state/use-atom-command", () => ({ @@ -125,7 +131,10 @@ vi.mock("./settings-environment-filter", () => ({ }), })); -import { SettingsEnvironmentSourceControlRouteScreen } from "./SettingsServerControlsRouteScreen"; +import { + SettingsThreadsRouteScreen, + SettingsWorktreesRouteScreen, +} from "./SettingsServerControlsRouteScreen"; function environment(environmentId: string, label: string) { return { @@ -154,6 +163,7 @@ beforeEach(() => { root = createRoot(container); mocks.targets = [environment("local", "Local")]; mocks.projectSelected = false; + mocks.readOnly = new Set(); mocks.alert.mockReset(); mocks.updateSettings.mockReset(); mocks.updateSettings.mockResolvedValue(AsyncResult.success(undefined)); @@ -167,7 +177,7 @@ describe("SettingsServerControlsRouteScreen", () => { it("sends a draft saved during a pending write once that write settles", async () => { const pending = Promise.withResolvers>(); mocks.updateSettings.mockReturnValueOnce(pending.promise); - act(() => root.render()); + act(() => root.render()); act(() => mocks.branchNaming.onChange({ branchNamingMode: "custom" })); act(() => mocks.branchNaming.onChange({ branchNameInstructions: "Use issue IDs." })); @@ -183,4 +193,36 @@ describe("SettingsServerControlsRouteScreen", () => { }, }); }); + + it("holds auto-settle changes until a pending project override write settles", async () => { + mocks.projectSelected = true; + const pending = Promise.withResolvers>(); + mocks.updateSettings.mockReturnValueOnce(pending.promise); + act(() => root.render()); + const toggle = (label: string) => + [...container.querySelectorAll('[role="switch"]')].find( + (button) => button.textContent === label, + )!; + + act(() => toggle("Agent browser access").click()); + act(() => toggle("Auto-settle merged threads").click()); + + // Both rewrite the whole project override, so a second write planned now would drop the first. + expect(mocks.updateSettings).toHaveBeenCalledOnce(); + await act(async () => pending.resolve(AsyncResult.success(undefined))); + }); + + it("disables auto-settle when a selected environment cannot save settings", () => { + const remote = environment("remote", "Remote"); + // Auto-settle rows skip a server without auto-settlement, but the page still saves to it. + remote.serverConfig.environment.capabilities.threadAutoSettlement = false; + mocks.targets = [environment("local", "Local"), remote]; + mocks.readOnly = new Set(["remote"]); + act(() => root.render()); + + const autoSettle = [...container.querySelectorAll('[role="switch"]')].find( + (button) => button.textContent === "Auto-settle merged threads", + )!; + expect(autoSettle.disabled).toBe(true); + }); }); diff --git a/apps/mobile/src/features/settings/SettingsServerControlsRouteScreen.tsx b/apps/mobile/src/features/settings/SettingsServerControlsRouteScreen.tsx index 676f42d35eba5..94a54db718db5 100644 --- a/apps/mobile/src/features/settings/SettingsServerControlsRouteScreen.tsx +++ b/apps/mobile/src/features/settings/SettingsServerControlsRouteScreen.tsx @@ -39,27 +39,35 @@ import { type ScopedMobileSettingsTarget, } from "./settings-scoped-server"; import { PullRequestGlyph } from "../pull-requests/pullRequestGlyphs"; +import { AutoSettleSettingsRows } from "./ThreadSettingsSections"; +import { supportsSharedSettingsSync } from "@t3tools/client-runtime/state/shared-settings"; -type SettingsPage = "new-threads" | "source-control" | "agent-behavior" | "maintenance"; +type SettingsPage = "threads" | "source-control" | "worktrees" | "maintenance"; const PAGE_TITLES: Record = { - "new-threads": "New threads", + threads: "Threads", "source-control": "Source control", - "agent-behavior": "Agent behavior", + worktrees: "Worktrees", maintenance: "Maintenance", }; const PAGE_PROJECT_KEYS: Record = { - "new-threads": ["defaultThreadEnvMode", "worktreeSubmodules", "defaultRuntimeMode"], - "source-control": [ - "defaultAutoPull", - "removeAgentCreditsOnMerge", + threads: [ + "defaultThreadEnvMode", + "defaultRuntimeMode", + "responseStreamingMode", + "enableAgentBrowserAccess", + "sidebarAutoSettleOnMerge", + "sidebarAutoSettleAfterDays", + ], + "source-control": ["defaultAutoPull", "removeAgentCreditsOnMerge"], + worktrees: [ "newWorktreesStartFromOrigin", + "worktreeSubmodules", "branchNamingMode", "branchNamePrefix", "branchNameInstructions", ], - "agent-behavior": ["responseStreamingMode", "enableAgentBrowserAccess"], maintenance: ["continueThreadsAfterServerUpdate"], }; @@ -121,16 +129,42 @@ const STREAMING_CHOICES: ReadonlyArray<{ }, ]; -export function SettingsEnvironmentNewThreadsRouteScreen() { - return ; +// Only servers with thread auto-settlement store these, so other targets get the rest of a patch. +const AUTO_SETTLE_SETTING_KEYS: ReadonlySet = new Set([ + "sidebarAutoSettleOnMerge", + "sidebarAutoSettleAfterDays", + "autoResumeLimitedThreads", + "snoozeLimitedThreads", +]); + +function planServerSettingsWrites( + targets: readonly ScopedMobileSettingsTarget[], + projectSelected: boolean, + patch: ServerSettingsPatch, +) { + const capable = targets.filter((target) => supportsSharedSettingsSync(target.environment)); + const others = targets.filter((target) => !supportsSharedSettingsSync(target.environment)); + const othersPatch = Object.fromEntries( + Object.entries(patch).filter(([key]) => !AUTO_SETTLE_SETTING_KEYS.has(key)), + ) as ServerSettingsPatch; + return [ + ...planMobileScopedSettingsPatch(capable, projectSelected, patch), + ...(Object.keys(othersPatch).length > 0 + ? planMobileScopedSettingsPatch(others, projectSelected, othersPatch) + : []), + ]; +} + +export function SettingsThreadsRouteScreen() { + return ; } export function SettingsEnvironmentSourceControlRouteScreen() { return ; } -export function SettingsEnvironmentAgentBehaviorRouteScreen() { - return ; +export function SettingsWorktreesRouteScreen() { + return ; } export function SettingsEnvironmentMaintenanceRouteScreen() { @@ -187,7 +221,7 @@ function ServerSettingsDetail(props: { readonly page: SettingsPage }) { ) ) return; - const writes = planMobileScopedSettingsPatch(targets, projectSelected, patch); + const writes = planServerSettingsWrites(targets, projectSelected, patch); if (writes.length === 0) return; writeInFlight.current = true; setPendingTargets(targets); @@ -278,7 +312,7 @@ function ServerSettingsDetail(props: { readonly page: SettingsPage }) { onClear={clearProjectOverrides} /> ) : null} - {props.page === "new-threads" ? ( + {props.page === "threads" ? ( <> ) : null } > - {SUBMODULE_CHOICES.filter( - (choice) => choice.mode !== null || !projectSelected, - ).map((choice, index) => ( + {RUNTIME_MODE_CHOICES.map((choice, index) => ( 0} - disabled={disabledFor("worktreeSubmodules")} - onPress={() => write({ worktreeSubmodules: choice.mode })} + disabled={disabledFor("defaultRuntimeMode")} + onPress={() => write({ defaultRuntimeMode: choice.mode })} /> ))} ) : null } > - {RUNTIME_MODE_CHOICES.map((choice, index) => ( + {STREAMING_CHOICES.map((choice, index) => ( 0} - disabled={disabledFor("defaultRuntimeMode")} - onPress={() => write({ defaultRuntimeMode: choice.mode })} + disabled={disabledFor("responseStreamingMode")} + onPress={() => write({ responseStreamingMode: choice.mode })} /> ))} + + write({ enableAgentBrowserAccess: value })} + /> + + 0} /> ) : null} {props.page === "source-control" ? ( <> - write({ defaultAutoPull: value })} /> - + + ) : null} + + {props.page === "worktrees" ? ( + <> + write({ newWorktreesStartFromOrigin: value })} /> - - ) : null} - - {props.page === "agent-behavior" ? ( - <> ) : null } > - {STREAMING_CHOICES.map((choice, index) => ( + {SUBMODULE_CHOICES.filter( + (choice) => choice.mode !== null || !projectSelected, + ).map((choice, index) => ( 0} - disabled={disabledFor("responseStreamingMode")} - onPress={() => write({ responseStreamingMode: choice.mode })} + disabled={disabledFor("worktreeSubmodules")} + onPress={() => write({ worktreeSubmodules: choice.mode })} /> ))} - - write({ enableAgentBrowserAccess: value })} - /> - + ) : null} diff --git a/apps/mobile/src/features/settings/SettingsThreadsRouteScreen.tsx b/apps/mobile/src/features/settings/ThreadSettingsSections.tsx similarity index 62% rename from apps/mobile/src/features/settings/SettingsThreadsRouteScreen.tsx rename to apps/mobile/src/features/settings/ThreadSettingsSections.tsx index 81561a4b0376f..7d338258cbe35 100644 --- a/apps/mobile/src/features/settings/SettingsThreadsRouteScreen.tsx +++ b/apps/mobile/src/features/settings/ThreadSettingsSections.tsx @@ -1,11 +1,10 @@ import { Button } from "../../components/ui/Button"; -import { AuthSettingsWriteScope } from "@t3tools/contracts"; -import { readEnvironmentScope, useEnvironmentsWithScope } from "../../state/session"; +import { AuthSettingsWriteScope, type ServerSettingsPatch } from "@t3tools/contracts"; +import { useEnvironmentsWithScope } from "../../state/session"; import { AutoSettleDaysField } from "./components/AutoSettleDaysField"; import { ScreenScrollView as ScrollView } from "../../components/ui/ScreenScrollView"; import { useAtomSet, useAtomValue } from "@effect/atom-react"; import { AsyncResult } from "effect/reactivity"; -import { useRef, useState } from "react"; import { View } from "react-native"; import { useSafeAreaInsets } from "react-native-safe-area-context"; @@ -14,71 +13,58 @@ import { supportsSharedSettingsSync } from "@t3tools/client-runtime/state/shared import { AppText as Text } from "../../components/ui/AppText"; import { mobilePreferencesAtom, updateMobilePreferencesAtom } from "../../state/preferences"; import { SettingsSection } from "./components/SettingsSection"; -import { SettingsProjectOverridesSection } from "./components/SettingsProjectOverridesSection"; import { SettingsSwitchRow } from "./components/SettingsSwitchRow"; import { SettingsScreen } from "./components/SettingsScreen"; -import { - AndroidSettingsEnvironmentFilter, - SettingsEnvironmentFilterHeader, -} from "./components/SettingsEnvironmentFilterHeader"; import { planAutoSettleSettingsSync, type AutoSettleSettings } from "./autoSettleSettingsSync"; import { useSettingsEnvironmentFilter } from "./settings-environment-filter"; -import { useSettingsWriter } from "./useSettingsWriter"; -import { - planMobileScopedSettingsClear, - planMobileScopedSettingsPatch, - resolveMobileSettingsTargets, - uniformMobileSetting, - type ScopedMobileSettingsTarget, -} from "./settings-scoped-server"; +import { resolveMobileSettingsTargets, uniformMobileSetting } from "./settings-scoped-server"; -export function SettingsThreadsRouteScreen() { +export function SettingsLabsRouteScreen() { const insets = useSafeAreaInsets(); return ( - <> - - }> - - - - - - - + + + + + ); } const AUTO_SETTLE_DEFAULT_DAYS = DEFAULT_SERVER_SETTINGS.sidebarAutoSettleAfterDays ?? 3; -function AutoSettleSettingsRows() { +/** + * Usage-limit and auto-settle rows. The Threads page owns their writes, so they share its queue + * with the page's other project overrides, and their project override reset. + */ +export function AutoSettleSettingsRows(props: { + readonly write: (patch: ServerSettingsPatch) => void; + readonly pending: boolean; +}) { const { selectedTargets, projectGroups, selectedProjectKey } = useSettingsEnvironmentFilter(); const selectedProject = projectGroups.find((group) => group.key === selectedProjectKey); const writableEnvironments = useEnvironmentsWithScope(selectedTargets, AuthSettingsWriteScope); const projectSelected = selectedProjectKey !== null; - const [pendingWrites, setPendingWrites] = useState(0); - const writeInFlight = useRef(false); - const [pendingTargets, setPendingTargets] = useState< - readonly ScopedMobileSettingsTarget[] | null - >(null); - const writeSettings = useSettingsWriter(); - const syncEnvironments = selectedTargets.filter(supportsSharedSettingsSync); - const syncTargets = resolveMobileSettingsTargets( - syncEnvironments, - projectSelected ? (selectedProject?.members.map((member) => member.project) ?? []) : null, + const projectMembers = projectSelected + ? (selectedProject?.members.map((member) => member.project) ?? []) + : null; + const displayTargets = resolveMobileSettingsTargets( + selectedTargets.filter(supportsSharedSettingsSync), + projectMembers, ); + // The page saves to all its targets, so any read-only one blocks the save. const canWriteSettings = - syncTargets.length > 0 && - syncTargets.every((target) => writableEnvironments.has(target.environment.environmentId)); - const displayTargets = - pendingWrites > 0 && pendingTargets !== null ? pendingTargets : syncTargets; + displayTargets.length > 0 && + resolveMobileSettingsTargets(selectedTargets, projectMembers).every((target) => + writableEnvironments.has(target.environment.environmentId), + ); const reference = displayTargets[0] ?? null; const referenceSettings = reference?.settings ?? null; @@ -92,26 +78,7 @@ function AutoSettleSettingsRows() { snoozeLimitedThreads?: boolean; cacheExpiryCompactionMinTokens?: number | null; }, - targets = syncTargets, - ) => { - if ( - writeInFlight.current || - !targets.every((target) => - readEnvironmentScope(target.environment.environmentId, AuthSettingsWriteScope), - ) - ) - return; - const writes = planMobileScopedSettingsPatch(targets, projectSelected, patch); - if (writes.length === 0) return; - writeInFlight.current = true; - setPendingTargets(syncTargets); - setPendingWrites((count) => count + 1); - void writeSettings(syncTargets, writes).finally(() => { - writeInFlight.current = false; - setPendingTargets(null); - setPendingWrites((count) => count - 1); - }); - }; + ) => props.write(patch); const { patch: autoSettlePatch, mismatches } = planAutoSettleSettingsSync( { @@ -127,56 +94,16 @@ function AutoSettleSettingsRows() { })), ); - const supportsProjectOverrides = syncTargets.every( + const supportsProjectOverrides = displayTargets.every( (target) => target.environment.serverConfig.environment.capabilities.projectSettingsOverrides === true, ); const disabled = - !canWriteSettings || pendingWrites > 0 || (projectSelected && !supportsProjectOverrides); - const hasProjectOverrides = - projectSelected && - syncTargets.some( - (target) => - target.sources.sidebarAutoSettleOnMerge === "project" || - target.sources.sidebarAutoSettleAfterDays === "project", - ); - const clearProjectOverrides = () => { - if ( - writeInFlight.current || - !syncTargets.every((target) => - readEnvironmentScope(target.environment.environmentId, AuthSettingsWriteScope), - ) - ) - return; - const writes = planMobileScopedSettingsClear(syncTargets, [ - "sidebarAutoSettleOnMerge", - "sidebarAutoSettleAfterDays", - ]); - if (writes.length === 0) return; - writeInFlight.current = true; - setPendingTargets(syncTargets); - setPendingWrites((count) => count + 1); - void writeSettings(syncTargets, writes).finally(() => { - writeInFlight.current = false; - setPendingTargets(null); - setPendingWrites((count) => count - 1); - }); - }; - + !canWriteSettings || props.pending || (projectSelected && !supportsProjectOverrides); const afterDays = referenceSettings.sidebarAutoSettleAfterDays; return ( - {projectSelected ? ( - 0} - disabled={!canWriteSettings} - onClear={clearProjectOverrides} - /> - ) : null} {!projectSelected ? ( - // Turning it on keeps each environment's custom minimum. - value - ? writeToAll( - { cacheExpiryCompactionMinTokens: 150_000 }, - syncTargets.filter( - (target) => target.settings.cacheExpiryCompactionMinTokens === null, - ), - ) - : writeToAll({ cacheExpiryCompactionMinTokens: null }) + // Turning it on reuses a minimum a target already has, or 150k. + writeToAll({ + cacheExpiryCompactionMinTokens: value + ? (displayTargets.find( + (target) => target.settings.cacheExpiryCompactionMinTokens !== null, + )?.settings.cacheExpiryCompactionMinTokens ?? 150_000) + : null, + }) } /> @@ -255,7 +181,7 @@ function AutoSettleSettingsRows() { ) : null} - {pendingWrites === 0 && mismatches.length > 0 ? ( + {!props.pending && mismatches.length > 0 ? ( Auto-settle defaults differ @@ -275,7 +201,7 @@ function AutoSettleSettingsRows() { ); } -function BetaSettingsSection() { +export function WorkingSectionSettings() { const savePreferences = useAtomSet(updateMobilePreferencesAtom); const preferences = useAtomValue(mobilePreferencesAtom); const workingShelfEnabled = @@ -283,7 +209,7 @@ function BetaSettingsSection() { return ( - + { { query: "appear", expected: [["Interface", ["Appearance"]]] }, { query: "KEYBOARD", expected: [["Interface", ["Keyboard"]]] }, { query: "dark mode", expected: [["Interface", ["Appearance"]]] }, - { query: "branch naming", expected: [["Server settings", ["Source control"]]] }, + { query: "agent credits", expected: [["Server settings", ["Source control"]]] }, { query: "server settings", expected: [["Server settings", ["Provider accounts", "Source control"]]], diff --git a/apps/mobile/src/features/settings/settings-search.ts b/apps/mobile/src/features/settings/settings-search.ts index f82f90dfe8333..ed39fc0acfa69 100644 --- a/apps/mobile/src/features/settings/settings-search.ts +++ b/apps/mobile/src/features/settings/settings-search.ts @@ -31,39 +31,57 @@ const SETTINGS_SEARCH_TERMS = { SettingsKeyboard: ["return key", "send message", "new line", "hardware keyboard"], SettingsMicrophone: ["voice", "dictation", "audio input", "bluetooth"], SettingsScheduledTasks: ["automations", "schedule", "cron", "recurring", "webhook"], - SettingsProjectOverview: ["project", "checkouts", "worktrees", "delete project"], - SettingsOrganization: ["project grouping", "group projects", "sidebar"], + SettingsProjectOverview: ["project", "overview", "checkouts", "delete project"], + SettingsOrganization: [ + "project grouping", + "group projects", + "organization", + "sidebar", + "working section", + ], SettingsThreads: [ + "new threads", + "default workspace", + "default permissions", + "access", + "response streaming", + "preview browser", + "browser access", "auto-settle", "settle", "snooze", "usage limits", "auto-resume", - "plan mode", - "working section", + "thread behavior", ], - SettingsFollowUp: ["queue", "steer", "while the agent is running"], + SettingsFollowUp: ["follow-ups", "queue", "steer", "while the agent is running"], SettingsArchive: ["archive", "archived", "restore", "unarchive"], - SettingsProviderAccounts: ["codex", "claude", "cursor", "opencode", "sign in", "login", "auth"], - SettingsEnvironmentNewThreads: [ - "default workspace", - "worktree", - "submodules", - "default permissions", - "access", + SettingsProviderAccounts: [ + "provider accounts", + "codex", + "claude", + "cursor", + "opencode", + "sign in", + "login", + "auth", ], SettingsEnvironmentSourceControl: [ "git", - "branch naming", "pull requests", "co-authors", "agent credits", "default branch", "automatically pull", - "worktrees", + ], + SettingsWorktrees: [ + "worktree", + "branch naming", + "branch prefix", + "submodules", "start from remote", ], - SettingsEnvironmentAgentBehavior: ["response streaming", "preview browser", "browser access"], + SettingsLabs: ["legacy", "plan mode", "beta"], SettingsEnvironmentMaintenance: ["updates", "provider updates", "restart", "manage environments"], SettingsAbout: [ "version", diff --git a/apps/mobile/src/features/threads/NewTaskDraftRouteScreen.tsx b/apps/mobile/src/features/threads/NewTaskDraftRouteScreen.tsx index 059f6ff2b12c3..73a43b7340d74 100644 --- a/apps/mobile/src/features/threads/NewTaskDraftRouteScreen.tsx +++ b/apps/mobile/src/features/threads/NewTaskDraftRouteScreen.tsx @@ -40,9 +40,6 @@ export function NewTaskDraftRouteScreen({ route }: StaticScreenProps )} diff --git a/apps/mobile/src/features/threads/NewTaskDraftScreen.tsx b/apps/mobile/src/features/threads/NewTaskDraftScreen.tsx index 5efbf0a45ccb1..66a041c3f3fc3 100644 --- a/apps/mobile/src/features/threads/NewTaskDraftScreen.tsx +++ b/apps/mobile/src/features/threads/NewTaskDraftScreen.tsx @@ -150,7 +150,6 @@ export function NewTaskDraftScreen(props: { readonly worktreePath?: string | null; readonly cloning?: boolean; }; - readonly pendingTaskId?: string; readonly draftId?: string; readonly incomingShareId?: string; }) { @@ -386,11 +385,11 @@ export function NewTaskDraftScreen(props: { }; }, []); - const { beginEditingPendingTask, cancelEditingPendingTask, editingPendingTask, openDraft } = flow; + const { openDraft } = flow; // Cold launches load drafts and projects separately; wait for hydration and retry while shells load. const attemptedDraftIdRef = useRef(null); useEffect(() => { - if (!props.draftId || props.pendingTaskId) { + if (!props.draftId) { return; } const draftId = props.draftId; @@ -415,34 +414,12 @@ export function NewTaskDraftScreen(props: { return () => { cancelled = true; }; - }, [navigation, openDraft, projects, props.draftId, props.pendingTaskId]); - - const attemptedPendingTaskIdRef = useRef(null); - useEffect(() => { - if (!props.pendingTaskId || editingPendingTask?.messageId === props.pendingTaskId) { - return; - } - if (attemptedPendingTaskIdRef.current === props.pendingTaskId) { - return; - } - attemptedPendingTaskIdRef.current = props.pendingTaskId; - if (!beginEditingPendingTask(props.pendingTaskId)) { - navigation.dispatch(CommonActions.navigate("NewTaskProject")); - } - }, [beginEditingPendingTask, editingPendingTask?.messageId, navigation, props.pendingTaskId]); - - useEffect(() => { - if (!props.pendingTaskId) return; - return () => { - attemptedPendingTaskIdRef.current = null; - cancelEditingPendingTask(); - }; - }, [props.pendingTaskId, cancelEditingPendingTask]); + }, [navigation, openDraft, projects, props.draftId]); const lastInitialProjectRefRef = useRef(props.initialProjectRef); useEffect(() => { - if (props.pendingTaskId || props.draftId) { + if (props.draftId) { return; } if (lastInitialProjectRefRef.current !== props.initialProjectRef) { @@ -516,9 +493,8 @@ export function NewTaskDraftScreen(props: { projects, flow.draftKey, props.initialProjectRef, - // oxlint-disable-next-line react/exhaustive-effect-dependencies -- Opening a draft from a share, pending task, or draft id re-resolves its project. + // oxlint-disable-next-line react/exhaustive-effect-dependencies -- Opening a draft from a share or draft id re-resolves its project. props.incomingShareId, - props.pendingTaskId, props.draftId, navigation, selectedProject, @@ -901,17 +877,7 @@ export function NewTaskDraftScreen(props: { return null; } - const editingPendingTask = flow.editingPendingTask; - - const metadata = editingPendingTask - ? { - threadId: editingPendingTask.threadId, - commandId: editingPendingTask.commandId, - messageId: editingPendingTask.messageId, - createdAt: editingPendingTask.createdAt, - } - : creationMetadata; - const message = flow.buildPendingTaskMessage(metadata, { + const message = flow.buildPendingTaskMessage(creationMetadata, { currentCheckoutBranch: queuesInsteadOfStarting ? null : flow.currentCheckoutBranchName, }); if (!message) { @@ -939,17 +905,13 @@ export function NewTaskDraftScreen(props: { // would otherwise resurrect this draft. abortComposerDraftOperations(draftKey); const draftSnapshot = getComposerDraftSnapshot(draftKey); - if (editingPendingTask) { - flow.finishEditingPendingTask(); - } else { - // The queued message owns the attachments now, so the sweep is deferred - // until the write confirms it. - clearComposerDraftContent(draftKey, { - clearModelSelection: true, - clearWorkspaceSelection: true, - deferAttachmentCleanup: true, - }); - } + // The queued message owns the attachments now, so the sweep is deferred + // until the write confirms it. + clearComposerDraftContent(draftKey, { + clearModelSelection: true, + clearWorkspaceSelection: true, + deferAttachmentCleanup: true, + }); scheduleUnusedComposerAttachmentCleanup(draftSnapshot.attachments); return message.messageId; } @@ -1146,7 +1108,7 @@ export function NewTaskDraftScreen(props: { const thread = draftThreadShell({ environmentId: selectedProject.environmentId, projectId: selectedProject.id, - threadId: ThreadId.make(flow.editingPendingTask?.threadId ?? creationMetadata.threadId), + threadId: ThreadId.make(creationMetadata.threadId), modelSelection: flow.selectedModel, runtimeMode: flow.runtimeMode, interactionMode: flow.interactionMode, diff --git a/apps/mobile/src/features/threads/ThreadRouteScreen.tsx b/apps/mobile/src/features/threads/ThreadRouteScreen.tsx index 0287a6975f7f9..4fe22d6cd5f22 100644 --- a/apps/mobile/src/features/threads/ThreadRouteScreen.tsx +++ b/apps/mobile/src/features/threads/ThreadRouteScreen.tsx @@ -111,11 +111,6 @@ import { import type { ThreadInspectorTarget } from "./thread-inspector-navigation"; import { useSelectWorkspaceDetail } from "../workspace/useSelectWorkspaceDetail"; -interface ThreadInspectorSelection { - readonly routeThreadIdentity: string | null; - readonly mode: ThreadInspectorMode; -} - function InspectorPaneRoleActivation() { useAdaptiveWorkspacePaneRole("inspector"); return null; @@ -435,19 +430,21 @@ function ThreadRouteContent( const threadId = firstRouteParam(params.threadId); const routeThreadIdentity = environmentIdRaw !== null && threadId !== null ? `${environmentIdRaw}:${threadId}` : null; - const [inspectorSelection, setInspectorSelection] = useState( - () => (props.renderInspector ? { routeThreadIdentity, mode: "route" } : null), - ); + // The chosen mode survives thread switches; "route" only applies while the route + // supplies an inspector, which is also the default whenever it does. + const [chosenInspectorMode, setChosenInspectorMode] = useState(null); const previewTarget = props.inspectorPresentation ? undefined : params.inspector; const inspectorMode = (() => { if (previewTarget) return "preview"; - if (inspectorSelection?.routeThreadIdentity === routeThreadIdentity) { - if (inspectorSelection.mode === "files" && selectedThreadCwd === null) { - return null; - } - return inspectorSelection.mode; - } - return null; + const mode = + props.renderInspector === undefined + ? chosenInspectorMode === "route" + ? null + : chosenInspectorMode + : chosenInspectorMode === null || chosenInspectorMode === "route" + ? "route" + : chosenInspectorMode; + return mode === "files" && selectedThreadCwd === null ? null : mode; })(); useEffect(() => { if ( @@ -468,24 +465,6 @@ function ThreadRouteContent( toggleAuxiliaryPane, ]); - useEffect(() => { - // oxlint-disable-next-line react/set-state-in-effect -- Inspector selection follows route ownership but keeps an inspector the user opened. - setInspectorSelection((current) => { - if (props.renderInspector === undefined) { - if (current === null || current.mode === "route") { - return null; - } - return { ...current, routeThreadIdentity }; - } - - if (current === null || current.mode === "route") { - return { routeThreadIdentity, mode: "route" }; - } - - return { ...current, routeThreadIdentity }; - }); - }, [props.renderInspector, routeThreadIdentity]); - const revealPreview = useEffectEvent(() => showAuxiliaryPane("inspector")); useEffect(() => { if (previewTarget) revealPreview(); @@ -552,7 +531,7 @@ function ThreadRouteContent( return; } navigation.setParams({ inspector: undefined }); - setInspectorSelection({ routeThreadIdentity, mode: "git" }); + setChosenInspectorMode("git"); showAuxiliaryPane("inspector"); }; const handleOpenFilesInspector = () => { @@ -567,10 +546,7 @@ function ThreadRouteContent( return; } navigation.setParams({ inspector: undefined }); - setInspectorSelection({ - routeThreadIdentity, - mode: props.renderInspector === undefined ? "files" : "route", - }); + setChosenInspectorMode(props.renderInspector === undefined ? "files" : "route"); showAuxiliaryPane("inspector"); }; const handleToggleInspector = () => { diff --git a/apps/mobile/src/features/threads/new-task-flow-provider.tsx b/apps/mobile/src/features/threads/new-task-flow-provider.tsx index 43017bfc74739..a7417328e6550 100644 --- a/apps/mobile/src/features/threads/new-task-flow-provider.tsx +++ b/apps/mobile/src/features/threads/new-task-flow-provider.tsx @@ -17,7 +17,6 @@ import type { import { CommandId, DEFAULT_PROVIDER_INTERACTION_MODE, - DEFAULT_RUNTIME_MODE, DEFAULT_SERVER_SETTINGS, MessageId, repositoryGroupingKeyOf, @@ -54,43 +53,26 @@ import { useAtomCommand } from "../../state/use-atom-command"; import { appendComposerDraftAttachments, type ComposerDraftInsertion, - clearComposerDraft, composerDraftsAtom, createNewTaskDraft, getComposerDraftSnapshot, - isComposerDraftEmpty, isNewTaskDraftKey, removeComposerDraftAttachment, replaceComposerDraftAttachments, retargetNewTaskDraft, - scheduleUnusedComposerAttachmentCleanup, setComposerDraftText, - setComposerDraftContext, setStickyComposerModelSelection, updateComposerDraftSettings, useComposerDraft, useStickyComposerModelSelection, } from "../../state/use-composer-drafts"; -import { - capturePendingTaskEditorWriteBaseline, - flushPendingTaskEditorWrite, -} from "../../state/pending-task-editor-writes"; import { rememberModelOptions, withRememberedModelOptions, } from "../../state/use-model-option-memory"; import { useBranches, usePaginatedBranches } from "../../state/queries"; import { vcsEnvironment } from "../../state/vcs"; -import { - flattenQueuedThreadMessages, - threadOutboxManager, - type QueuedThreadMessage, -} from "../../state/thread-outbox"; -import { - holdEditingQueuedMessage, - releaseEditingQueuedMessage, - useThreadOutboxMessages, -} from "../../state/use-thread-outbox"; +import { type QueuedThreadMessage } from "../../state/thread-outbox"; import { setPendingConnectionError, useRemoteConnectionStatus, @@ -126,20 +108,6 @@ import { useOlderSettledCount } from "../../state/olderSettledShelf"; type WorkspaceMode = "local" | "worktree"; -function pendingTaskDraftKey(messageId: string): string { - return `pending-task:${messageId}`; -} - -// Track ownership across providers so old unmount flushes cannot drop newer drafts or drain locks. -let activeEditingMessageId: string | null = null; - -function findQueuedPendingTask(messageId: string): QueuedThreadMessage | null { - const message = flattenQueuedThreadMessages( - appAtomRegistry.get(threadOutboxManager.queuedMessagesByThreadKeyAtom), - ).find((candidate) => candidate.messageId === messageId); - return message?.creation !== undefined ? message : null; -} - export function branchBadgeLabel(input: { readonly branch: VcsRef; readonly project: EnvironmentProject | null; @@ -174,7 +142,6 @@ type NewTaskFlowContextValue = { readonly startFromOrigin: boolean; readonly pullRequestReference: string | undefined; readonly draftKey: string | null; - readonly editingPendingTask: QueuedThreadMessage | null; readonly prompt: string; readonly attachments: ReadonlyArray; readonly submitting: boolean; @@ -210,9 +177,6 @@ type NewTaskFlowContextValue = { readonly setWorkspaceMode: (mode: WorkspaceMode) => void; readonly selectBranch: (branch: VcsRef) => void; readonly setStartFromOrigin: (value: boolean) => void; - readonly beginEditingPendingTask: (messageId: string) => boolean; - readonly finishEditingPendingTask: () => void; - readonly cancelEditingPendingTask: () => void; readonly buildPendingTaskMessage: ( metadata: TurnCommandMetadata, options?: { @@ -244,15 +208,13 @@ export function NewTaskFlowProvider( props: React.PropsWithChildren<{ active?: boolean; routeDraftId?: string; - routePendingTaskId?: string; }>, ) { const projects = useProjects(); const threads = useThreadShells(); const { savedConnectionsById } = useSavedRemoteConnections(); const groupingSettings = useMobileProjectGroupingSettings(); - const { enabled: legacyPlanModeEnabled, loaded: planModePreferenceLoaded } = - useLegacyPlanModeState(); + const { enabled: legacyPlanModeEnabled } = useLegacyPlanModeState(); const projectScopes = sortHomeProjectScopes({ scopes: buildHomeProjectScopes({ @@ -277,11 +239,7 @@ export function NewTaskFlowProvider( const [activeDraftKey, setActiveDraftKey] = useState(null); const [submitting, setSubmitting] = useState(false); const [expandedProvider, setExpandedProvider] = useState(null); - const [editingPendingTask, setEditingPendingTask] = useState(null); const pendingLocalBranchSyncDraftKeysRef = useRef(new Set()); - // Mirror edit state synchronously so unmount flush cannot save a session ended this render. - const editingPendingTaskRef = useRef(null); - const editingRevisionRef = useRef(Promise.resolve(0)); const reset = useCallback(() => { setSelectedEnvironmentId(null); @@ -290,15 +248,6 @@ export function NewTaskFlowProvider( setSubmitting(false); setExpandedProvider(null); pendingLocalBranchSyncDraftKeysRef.current.clear(); - const editing = editingPendingTaskRef.current; - editingPendingTaskRef.current = null; - setEditingPendingTask(null); - if (editing) { - if (activeEditingMessageId === editing.messageId) { - activeEditingMessageId = null; - } - releaseEditingQueuedMessage(editing.messageId); - } }, []); const projectsForEnvironment = pipe( @@ -306,34 +255,12 @@ export function NewTaskFlowProvider( Arr.filter((project) => project.environmentId === selectedEnvironmentId), ); - const editingPendingProject = ((): EnvironmentProject | null => { - const creation = editingPendingTask?.creation; - if (!editingPendingTask || !creation) { - return null; - } - return { - environmentId: editingPendingTask.environmentId, - id: creation.projectId, - title: creation.projectTitle ?? "Unknown project", - workspaceRoot: creation.projectCwd ?? "", - repositoryIdentity: null, - defaultModelSelection: editingPendingTask.modelSelection ?? null, - scripts: [], - createdAt: editingPendingTask.createdAt, - updatedAt: editingPendingTask.createdAt, - }; - })(); - const selectedProject = projectsForEnvironment.find( (project) => scopedProjectKey(project.environmentId, project.id) === selectedProjectKey, ) ?? - // Pin queued edits to their original project when its shell is missing; fallback would silently retarget them. - (editingPendingProject !== null && - selectedProjectKey === - scopedProjectKey(editingPendingProject.environmentId, editingPendingProject.id) - ? editingPendingProject - : (projectsForEnvironment[0] ?? null)); + projectsForEnvironment[0] ?? + null; const selectedEnvironmentServerConfig = useEnvironmentServerConfig( selectedProject?.environmentId ?? null, @@ -404,18 +331,9 @@ export function NewTaskFlowProvider( return result; })(); - const selectedProjectDraftKey = editingPendingTask - ? pendingTaskDraftKey(editingPendingTask.messageId) - : selectedProject - ? activeDraftKey - : null; + const selectedProjectDraftKey = selectedProject ? activeDraftKey : null; useEffect(() => { - if ( - props.active === false || - activeDraftKey !== null || - editingPendingTask !== null || - selectedProject === null - ) { + if (props.active === false || activeDraftKey !== null || selectedProject === null) { return; } // oxlint-disable-next-line react/set-state-in-effect -- Creates the persistent draft once the project selection is ready; the key must exist before the composer mounts. @@ -425,19 +343,15 @@ export function NewTaskFlowProvider( projectId: selectedProject.id, }), ); - }, [activeDraftKey, editingPendingTask, selectedProject, props.active]); + }, [activeDraftKey, selectedProject, props.active]); const activePendingKey = props.active === false ? null - : props.routePendingTaskId - ? `pending-task:${props.routePendingTaskId}` - : props.routeDraftId - ? `draft-task:${props.routeDraftId}` - : editingPendingTask - ? `pending-task:${editingPendingTask.messageId}` - : selectedProjectDraftKey - ? `draft-task:${selectedProjectDraftKey}` - : null; + : props.routeDraftId + ? `draft-task:${props.routeDraftId}` + : selectedProjectDraftKey + ? `draft-task:${selectedProjectDraftKey}` + : null; const activeNewTask = React.useMemo( () => (props.active === false ? null : { pendingKey: activePendingKey }), [props.active, activePendingKey], @@ -537,9 +451,7 @@ export function NewTaskFlowProvider( const draftStartFromOrigin = selectedProjectDraft.workspaceSelection?.startFromOrigin; const startFromOrigin = isGitRepo && (draftStartFromOrigin ?? projectSettings.settings.newWorktreesStartFromOrigin); - const defaultRuntimeMode = editingPendingTask - ? (editingPendingTask.runtimeMode ?? DEFAULT_RUNTIME_MODE) - : projectSettings.settings.defaultRuntimeMode; + const defaultRuntimeMode = projectSettings.settings.defaultRuntimeMode; const runtimeMode = selectedProjectDraft.runtimeMode ?? defaultRuntimeMode; // Antigravity keeps unavailable selections so sign-out or a catalog change @@ -687,7 +599,7 @@ export function NewTaskFlowProvider( const target = { environmentId: project.environmentId, projectId: project.id }; if (activeDraftKey !== null && isNewTaskDraftKey(activeDraftKey)) { retargetNewTaskDraft(activeDraftKey, target); - } else if (!editingPendingTaskRef.current) { + } else { setActiveDraftKey(createNewTaskDraft(target)); } }; @@ -914,39 +826,6 @@ export function NewTaskFlowProvider( } }; - const beginEditingPendingTask = (messageId: string): boolean => { - const message = findQueuedPendingTask(messageId); - if (!message?.creation) { - return false; - } - const draftKey = pendingTaskDraftKey(message.messageId); - if (isComposerDraftEmpty(getComposerDraftSnapshot(draftKey))) { - setComposerDraftText(draftKey, message.text); - setComposerDraftContext(draftKey, message.context); - replaceComposerDraftAttachments(draftKey, message.attachments); - updateComposerDraftSettings(draftKey, { - modelSelection: message.modelSelection, - runtimeMode: message.runtimeMode, - interactionMode: message.interactionMode, - workspaceSelection: { - mode: message.creation.workspaceMode, - branch: message.creation.branch, - worktreePath: message.creation.worktreePath, - startFromOrigin: message.creation.startFromOrigin ?? false, - pullRequestReference: message.creation.pullRequestReference, - }, - }); - } - setSelectedEnvironmentId(message.environmentId); - setSelectedProjectKey(scopedProjectKey(message.environmentId, message.creation.projectId)); - activeEditingMessageId = message.messageId; - editingPendingTaskRef.current = message; - editingRevisionRef.current = capturePendingTaskEditorWriteBaseline(message.messageId); - setEditingPendingTask(message); - holdEditingQueuedMessage(message.messageId); - return true; - }; - const buildPendingTaskMessage = ( metadata: TurnCommandMetadata, options?: { readonly currentCheckoutBranch?: string | null }, @@ -980,17 +859,6 @@ export function NewTaskFlowProvider( isGitRepo, }); const mode = workspaceSelection.mode; - // When the selection is the stand-in built from the queued snapshot, - // persist the original (possibly absent) snapshot values — the - // stand-in's placeholder title/workspaceRoot must never be written back - // as if they were real project metadata. - const usingPendingSnapshot = selectedProject === editingPendingProject; - const projectTitle = usingPendingSnapshot - ? editingPendingTask?.creation?.projectTitle - : selectedProject.title; - const projectCwd = usingPendingSnapshot - ? editingPendingTask?.creation?.projectCwd - : selectedProject.workspaceRoot; return { environmentId: selectedProject.environmentId, threadId: ThreadId.make(metadata.threadId), @@ -1002,18 +870,16 @@ export function NewTaskFlowProvider( modelSelection: draftModelSelection, runtimeMode: draft.runtimeMode ?? defaultRuntimeMode, interactionMode: resolvePendingTaskInteractionMode({ - preferenceLoaded: planModePreferenceLoaded, planModeEnabled: legacyPlanModeEnabled, draftInteractionMode: draft.interactionMode, - queuedInteractionMode: editingPendingTask?.interactionMode, provider: selectedEnvironmentServerConfig?.providers.find( (candidate) => candidate.instanceId === draftModelSelection.instanceId, ), }), creation: { projectId: selectedProject.id, - ...(projectTitle !== undefined ? { projectTitle } : {}), - ...(projectCwd !== undefined ? { projectCwd } : {}), + projectTitle: selectedProject.title, + projectCwd: selectedProject.workspaceRoot, workspaceMode: mode, ...(mode === "worktree" && workspaceSelection?.pullRequestReference ? { pullRequestReference: workspaceSelection.pullRequestReference } @@ -1033,93 +899,6 @@ export function NewTaskFlowProvider( }; }; - const finishEditingPendingTask = () => { - const editing = editingPendingTaskRef.current; - editingPendingTaskRef.current = null; - if (editing) { - if (activeEditingMessageId === editing.messageId) { - activeEditingMessageId = null; - } - clearComposerDraft(pendingTaskDraftKey(editing.messageId)); - releaseEditingQueuedMessage(editing.messageId); - scheduleUnusedComposerAttachmentCleanup(editing.attachments); - } - setEditingPendingTask(null); - }; - - // End editing without saving if the queued task disappears; a later flush must not resurrect it. - const queuedMessagesByThreadKey = useThreadOutboxMessages(); - useEffect(() => { - const editing = editingPendingTaskRef.current; - if (!editing) { - return; - } - const stillQueued = flattenQueuedThreadMessages(queuedMessagesByThreadKey).some( - (candidate) => candidate.messageId === editing.messageId, - ); - if (!stillQueued) { - finishEditingPendingTask(); - } - }, [finishEditingPendingTask, queuedMessagesByThreadKey]); - - const editingFlushRef = useRef<(() => void) | null>(null); - useEffect(() => { - editingFlushRef.current = () => { - const editing = editingPendingTaskRef.current; - if (!editing) { - return; - } - editingPendingTaskRef.current = null; - setEditingPendingTask(null); - if (activeEditingMessageId === editing.messageId) { - activeEditingMessageId = null; - } - - const message = buildPendingTaskMessage({ - threadId: editing.threadId, - commandId: editing.commandId, - messageId: editing.messageId, - createdAt: editing.createdAt, - }); - - if (!message) { - // Keep unsendable edits and the drain lock so removed content cannot auto-send from a stale payload. - return; - } - - // Hand off pending saves to reopened editors; CAS still rejects unrelated edits, deletes and deliveries. - void flushPendingTaskEditorWrite({ - message, - baseline: editingRevisionRef.current, - draftKey: pendingTaskDraftKey(editing.messageId), - }) - .then((savedDraftStillCurrent) => { - if (activeEditingMessageId === editing.messageId) { - return; - } - if (!savedDraftStillCurrent) { - return; - } - clearComposerDraft(pendingTaskDraftKey(editing.messageId)); - releaseEditingQueuedMessage(editing.messageId); - scheduleUnusedComposerAttachmentCleanup(editing.attachments); - }) - .catch((error) => { - // Keep the draft and drain lock on failure so stale payloads cannot discard edits; reopening retries. - console.warn("[new-task] failed to save edited pending task", error); - }); - }; - }, [buildPendingTaskMessage]); - const cancelEditingPendingTask = () => { - editingFlushRef.current?.(); - }; - useEffect( - () => () => { - editingFlushRef.current?.(); - }, - [], - ); - const value = { activeNewTask, projectScopes, @@ -1135,7 +914,6 @@ export function NewTaskFlowProvider( startFromOrigin, draftKey: selectedProjectDraftKey, pullRequestReference: selectedProjectDraft.workspaceSelection?.pullRequestReference, - editingPendingTask, prompt, attachments, submitting, @@ -1164,9 +942,6 @@ export function NewTaskFlowProvider( setWorkspaceMode, selectBranch, setStartFromOrigin, - beginEditingPendingTask, - finishEditingPendingTask, - cancelEditingPendingTask, buildPendingTaskMessage, setPrompt, replaceAttachments, diff --git a/apps/mobile/src/features/threads/thread-route-state.ts b/apps/mobile/src/features/threads/thread-route-state.ts index c9a6ab6a3ddba..e237d9bf69937 100644 --- a/apps/mobile/src/features/threads/thread-route-state.ts +++ b/apps/mobile/src/features/threads/thread-route-state.ts @@ -6,7 +6,6 @@ export type NewTaskDraftRouteParams = { readonly worktreePath?: string | null; readonly title?: string | string[]; readonly cloning?: string | string[]; - readonly pendingTaskId?: string | string[]; readonly draftId?: string | string[]; readonly incomingShareId?: string | string[]; }; @@ -32,7 +31,6 @@ export function draftRouteIdentity(draft: NewTaskDraftRouteParams): string { const first = (value: string | string[] | undefined) => (Array.isArray(value) ? value[0] : value); return JSON.stringify([ draft.requestId, - first(draft.pendingTaskId), first(draft.draftId), first(draft.environmentId), first(draft.projectId), diff --git a/apps/mobile/src/features/threads/use-legacy-plan-mode-enabled.ts b/apps/mobile/src/features/threads/use-legacy-plan-mode-enabled.ts index 5f41874588b0a..694a34e632e3f 100644 --- a/apps/mobile/src/features/threads/use-legacy-plan-mode-enabled.ts +++ b/apps/mobile/src/features/threads/use-legacy-plan-mode-enabled.ts @@ -4,7 +4,7 @@ import { AsyncResult } from "effect/reactivity"; import { mobilePreferencesAtom } from "../../state/preferences"; import { resolveLegacyPlanModeEnabled } from "../../state/legacy-plan-mode"; -export function useLegacyPlanModeState(): { readonly enabled: boolean; readonly loaded: boolean } { +export function useLegacyPlanModeState(): { readonly enabled: boolean } { const preferences = useAtomValue(mobilePreferencesAtom); const loaded = AsyncResult.isSuccess(preferences); return { @@ -12,6 +12,5 @@ export function useLegacyPlanModeState(): { readonly enabled: boolean; readonly loaded, preference: loaded ? preferences.value.planModeEnabled : undefined, }), - loaded, }; } diff --git a/apps/mobile/src/features/workspace/AndroidWorkspaceSidebar.android.tsx b/apps/mobile/src/features/workspace/AndroidWorkspaceSidebar.android.tsx index 65fa9d1d37ecc..d0d0796c9b601 100644 --- a/apps/mobile/src/features/workspace/AndroidWorkspaceSidebar.android.tsx +++ b/apps/mobile/src/features/workspace/AndroidWorkspaceSidebar.android.tsx @@ -4,7 +4,6 @@ import { NAVIGATION_TAB_ORDER } from "./navigation-tab-order"; import { useMemo, type ReactNode } from "react"; import { View } from "react-native"; import { ScreenContent } from "../../components/ui/ScreenContent"; -import { PullRequestFilterMenuProvider } from "../pull-requests/PullRequestFilterMenuContext"; import { PullRequestsScreen } from "../pull-requests/PullRequestsScreen"; import { PullRequestToolbar } from "../pull-requests/PullRequestToolbar.android"; import { WorkspaceTabsContext, useWorkspaceTabs } from "./WorkspaceTabsContext"; @@ -30,17 +29,19 @@ export function AndroidWorkspaceSidebar(props: { ) : ( - - - - - ( + + - - - + {list} + + )} + /> ) } diff --git a/apps/mobile/src/features/workspace/WorkspaceRootScreen.android.tsx b/apps/mobile/src/features/workspace/WorkspaceRootScreen.android.tsx index 1173a08e867e9..3f346f69bd48b 100644 --- a/apps/mobile/src/features/workspace/WorkspaceRootScreen.android.tsx +++ b/apps/mobile/src/features/workspace/WorkspaceRootScreen.android.tsx @@ -11,7 +11,6 @@ import { EmptyState } from "../../components/ui/EmptyState"; import { ScreenContent } from "../../components/ui/ScreenContent"; import { useAndroidControlSizing } from "../../components/ui/useAndroidControlSizing"; import { HomeRouteScreen } from "../home/HomeRouteScreen"; -import { PullRequestFilterMenuProvider } from "../pull-requests/PullRequestFilterMenuContext"; import { PullRequestsScreen } from "../pull-requests/PullRequestsScreen"; import { PullRequestToolbar } from "../pull-requests/PullRequestToolbar.android"; import { useAdaptiveWorkspaceLayout } from "../layout/AdaptiveWorkspaceLayout"; @@ -83,12 +82,14 @@ export function WorkspaceRootScreen() { ) : tab !== "pullRequests" ? ( ) : ( - - - - - - + ( + <> + + {list} + + )} + /> ) } /> diff --git a/apps/mobile/src/state/composer-attachment-uploads.test.ts b/apps/mobile/src/state/composer-attachment-uploads.test.ts index fc7a5e47bac53..e549858b00840 100644 --- a/apps/mobile/src/state/composer-attachment-uploads.test.ts +++ b/apps/mobile/src/state/composer-attachment-uploads.test.ts @@ -19,20 +19,9 @@ const native = vi.hoisted(() => ({ remove: Symbol("remove"), transfer: vi.fn<(uri: string, url: string, options: UploadOptions) => Promise<{ status: number }>>(), - effects: [] as Array<() => void | (() => void)>, - queueRef: { - current: null as ReturnType< - typeof import("../lib/composerAttachmentUploadQueue").createComposerAttachmentUploadQueue - > | null, - }, })); vi.mock("react-native", () => ({ Alert: { alert: vi.fn() } })); -vi.mock("react", async (importOriginal) => ({ - ...(await importOriginal()), - useEffect: (effect: () => void | (() => void)) => native.effects.push(effect), - useRef: () => native.queueRef, -})); vi.mock("@effect/atom-react", () => ({ useAtomValue: (atom: Parameters[0]) => appAtomRegistry.get(atom), })); @@ -111,6 +100,8 @@ vi.mock("./entities", () => ({ useServerConfigs: () => new Map([["environment-1", config]]), useThreadShells: () => [], })); +vi.mock("./projects", () => ({ environmentProjects: {} })); +vi.mock("./workspace", () => ({ workspaceConnections: {} })); vi.mock("./server", async () => { const { Atom } = await import("effect/reactivity"); return { serverEnvironment: { configValueAtom: Atom.family(() => Atom.make(null)) } }; @@ -173,14 +164,9 @@ vi.mock("./use-thread-outbox", async () => { dispatchingQueuedMessageIdAtom: Atom.make>({}).pipe(Atom.keepAlive), useThreadOutboxMessages: () => appAtomRegistry.get(threadOutboxManager.queuedMessagesByThreadKeyAtom), - useThreadOutboxShellStatuses: () => new Map(), + threadOutboxShellStatusesAtom: Atom.make(new Map()), }; }); -vi.mock("./use-remote-environment-registry", () => ({ - useRemoteConnectionStatus: () => ({ - connectedEnvironments: [{ environmentId: "environment-1", connectionState: "connected" }], - }), -})); import { composerAttachmentUploadBlockReason, @@ -188,10 +174,12 @@ import { composerAttachmentUploadKey, } from "../lib/composerAttachmentUploadQueue"; import type { DraftComposerAttachment } from "../lib/composerImages"; +import { Atom } from "effect/reactivity"; import { appAtomRegistry } from "./atom-registry"; import { + composerAttachmentUploadRequests, composerAttachmentUploadsAtom, - useComposerAttachmentUploadWorker, + createComposerAttachmentUploadWorker, } from "./composer-attachment-uploads"; import { enqueueThreadOutboxMessage, @@ -200,7 +188,7 @@ import { } from "./thread-outbox"; import type { QueuedThreadMessage } from "./thread-outbox-model"; import * as drafts from "./use-composer-drafts"; -import { prepareQueuedMessageAttachments } from "./use-thread-outbox-drain"; +import { prepareQueuedMessageAttachments } from "./threadOutboxDelivery"; const environmentId = EnvironmentId.make("environment-1"); const draftKey = "environment-1:thread-1"; @@ -217,12 +205,19 @@ const image: DraftComposerAttachment = { }; let disposeWorker: (() => void) | undefined; +const requestsAtom = Atom.make((get) => + composerAttachmentUploadRequests({ + drafts: get(drafts.composerDraftUploadSourcesAtom), + queuedMessagesByThreadKey: get(threadOutboxManager.queuedMessagesByThreadKeyAtom), + connectedEnvironmentIds: new Set([environmentId]), + operableEnvironmentIds: new Set([environmentId]), + serverConfigs: new Map([[environmentId, config]]), + }), +); + function worker() { - native.effects = []; - useComposerAttachmentUploadWorker(); - disposeWorker = native.effects[0]!() ?? undefined; - const queue = native.queueRef.current!; - native.effects[1]!(); + const { queue, dispose } = createComposerAttachmentUploadWorker(requestsAtom); + disposeWorker = dispose; return queue; } diff --git a/apps/mobile/src/state/composer-attachment-uploads.ts b/apps/mobile/src/state/composer-attachment-uploads.ts index 0e543ffe18349..7bf7747fef2c7 100644 --- a/apps/mobile/src/state/composer-attachment-uploads.ts +++ b/apps/mobile/src/state/composer-attachment-uploads.ts @@ -2,11 +2,13 @@ import { settlePromise, squashAtomCommandFailure } from "@t3tools/client-runtime import { useAtomValue } from "@effect/atom-react"; import { AuthOrchestrationOperateScope, type EnvironmentId } from "@t3tools/contracts"; import { Atom, AsyncResult } from "effect/reactivity"; -import { useEffect, useRef } from "react"; import { prepareTurnAttachments } from "../lib/attachmentUpload"; import { retainComposerAttachmentFileForPreview } from "../lib/composerAttachmentPreviewRetention"; -import { isFileBackedComposerAttachment } from "../lib/composerImages"; +import { + isFileBackedComposerAttachment, + type DraftComposerAttachment, +} from "../lib/composerImages"; import { composerAttachmentUploadKey, composerDraftEnvironmentId, @@ -15,19 +17,19 @@ import { type ComposerAttachmentUploadState, } from "../lib/composerAttachmentUploadQueue"; import { appAtomRegistry } from "./atom-registry"; -import { useServerConfigs } from "./entities"; +import { environmentServerConfigsAtom } from "./server"; import { flattenQueuedThreadMessages, threadOutboxManager } from "./thread-outbox"; -import { useThreadOutboxMessages } from "./use-thread-outbox"; import { ComposerDraftPersistenceError, + type ComposerDraft, composerDraftsAtom, composerDraftUploadSourcesAtom, ensureComposerDraftsLoaded, flushComposerDrafts, setComposerDraftAttachmentUpload, } from "./use-composer-drafts"; -import { useRemoteConnectionStatus } from "./use-remote-environment-registry"; -import { readEnvironmentScope, useEnvironmentsWithScope } from "./session"; +import { environmentSession, readEnvironmentScope, sessionHasScope } from "./session"; +import { workspaceConnections } from "./workspace"; export { composerAttachmentUploadBlockReason, @@ -56,91 +58,130 @@ export function retryComposerAttachmentUpload(environmentId: EnvironmentId, atta uploadQueue?.retry(environmentId, attachmentId); } -export function useComposerAttachmentUploadWorker() { - const drafts = useAtomValue(composerDraftUploadSourcesAtom); - const queuedMessages = useThreadOutboxMessages(); - const serverConfigs = useServerConfigs(); - const { connectedEnvironments } = useRemoteConnectionStatus(); - const operableEnvironments = useEnvironmentsWithScope( - connectedEnvironments, - AuthOrchestrationOperateScope, +type ComposerAttachmentUploadRequest = { + readonly environmentId: EnvironmentId; + readonly attachment: DraftComposerAttachment; +}; + +export function composerAttachmentUploadRequests(input: { + readonly drafts: Readonly>>; + readonly queuedMessagesByThreadKey: Parameters[0]; + readonly connectedEnvironmentIds: ReadonlySet; + readonly operableEnvironmentIds: ReadonlySet; + readonly serverConfigs: ReadonlyMap< + EnvironmentId, + Parameters[1] + >; +}): ReadonlyArray { + const queued = flattenQueuedThreadMessages(input.queuedMessagesByThreadKey); + return Object.entries(input.drafts).flatMap(([key, draft]) => { + const environmentId = composerDraftEnvironmentId(key, queued, draft); + if ( + environmentId === null || + !input.connectedEnvironmentIds.has(environmentId) || + !input.operableEnvironmentIds.has(environmentId) + ) + return []; + return draft.attachments + .filter((attachment) => + canUploadComposerAttachment(attachment, input.serverConfigs.get(environmentId)), + ) + .map((attachment) => ({ environmentId, attachment })); + }); +} + +// Each connected environment's session is read here so a granted or revoked +// operate scope re-syncs the queue. +const composerAttachmentUploadRequestsAtom = Atom.make((get) => { + const connected = get(workspaceConnections.environmentsAtom).filter( + (environment) => environment.connectionState === "connected", ); - const queueRef = useRef | null>(null); + const operableEnvironmentIds = new Set(); + for (const { environmentId } of connected) { + if ( + sessionHasScope( + get(environmentSession.sessionStateAtom(environmentId)), + AuthOrchestrationOperateScope, + ) + ) { + operableEnvironmentIds.add(environmentId); + } + } + return composerAttachmentUploadRequests({ + drafts: get(composerDraftUploadSourcesAtom), + queuedMessagesByThreadKey: get(threadOutboxManager.queuedMessagesByThreadKeyAtom), + connectedEnvironmentIds: new Set(connected.map((environment) => environment.environmentId)), + operableEnvironmentIds, + serverConfigs: get(environmentServerConfigsAtom), + }); +}).pipe(Atom.withLabel("mobile:composer-attachment-upload-requests")); - useEffect(() => { - ensureComposerDraftsLoaded(); - const queue = createComposerAttachmentUploadQueue({ - onChange: (states) => appAtomRegistry.set(composerAttachmentUploadsAtom, states), - upload: async ({ environmentId, attachment }, signal, onProgress) => { - const release = isFileBackedComposerAttachment(attachment) - ? retainComposerAttachmentFileForPreview(attachment) - : undefined; - const prepared = await settlePromise(() => - prepareTurnAttachments({ - environmentId, - attachments: [attachment], - supportsImageUploads: true, - signal, - onUploadProgress: (_, progress) => onProgress(progress), - persistUploadedReferences: async ([uploaded]) => { - if (signal.aborted || !uploaded) return "abandon"; - const queued = flattenQueuedThreadMessages( - appAtomRegistry.get(threadOutboxManager.queuedMessagesByThreadKeyAtom), - ); - let retained = false; - for (const [key, draft] of Object.entries(appAtomRegistry.get(composerDraftsAtom))) { - if ( - composerDraftEnvironmentId(key, queued, draft) === environmentId && - draft.attachments.some((candidate) => candidate.id === attachment.id) - ) { - retained = setComposerDraftAttachmentUpload(key, uploaded) || retained; - } +/** + * Uploads draft attachments to their environment as soon as it is connected and + * operable. The queue follows the requests atom for its whole lifetime. + */ +export function createComposerAttachmentUploadWorker( + requestsAtom: Atom.Atom< + ReadonlyArray + > = composerAttachmentUploadRequestsAtom, +) { + ensureComposerDraftsLoaded(); + const queue = createComposerAttachmentUploadQueue({ + onChange: (states) => appAtomRegistry.set(composerAttachmentUploadsAtom, states), + upload: async ({ environmentId, attachment }, signal, onProgress) => { + const release = isFileBackedComposerAttachment(attachment) + ? retainComposerAttachmentFileForPreview(attachment) + : undefined; + const prepared = await settlePromise(() => + prepareTurnAttachments({ + environmentId, + attachments: [attachment], + supportsImageUploads: true, + signal, + onUploadProgress: (_, progress) => onProgress(progress), + persistUploadedReferences: async ([uploaded]) => { + if (signal.aborted || !uploaded) return "abandon"; + const queued = flattenQueuedThreadMessages( + appAtomRegistry.get(threadOutboxManager.queuedMessagesByThreadKeyAtom), + ); + let retained = false; + for (const [key, draft] of Object.entries(appAtomRegistry.get(composerDraftsAtom))) { + if ( + composerDraftEnvironmentId(key, queued, draft) === environmentId && + draft.attachments.some((candidate) => candidate.id === attachment.id) + ) { + retained = setComposerDraftAttachmentUpload(key, uploaded) || retained; } - if (!retained) return "abandon"; - // Draft-save failure only costs re-upload after restart; the outbox saves references independently, so preserve accepted uploads. - await flushComposerDrafts().catch((error: unknown) => { - if (!(error instanceof ComposerDraftPersistenceError)) throw error; - console.warn("[composer-attachments] could not save the uploaded reference", error); - }); - return "persisted"; - }, - }), - ); - release?.(); - if (AsyncResult.isFailure(prepared)) throw squashAtomCommandFailure(prepared); - return prepared.value.status === "ready"; - }, - }); - queueRef.current = queue; - uploadQueue = queue; - return () => { + } + if (!retained) return "abandon"; + // Draft-save failure only costs re-upload after restart; the outbox saves references independently, so preserve accepted uploads. + await flushComposerDrafts().catch((error: unknown) => { + if (!(error instanceof ComposerDraftPersistenceError)) throw error; + console.warn("[composer-attachments] could not save the uploaded reference", error); + }); + return "persisted"; + }, + }), + ); + release?.(); + if (AsyncResult.isFailure(prepared)) throw squashAtomCommandFailure(prepared); + return prepared.value.status === "ready"; + }, + }); + uploadQueue = queue; + const unsubscribe = appAtomRegistry.subscribe(requestsAtom, (requests) => queue.sync(requests), { + immediate: true, + }); + return { + queue, + dispose: () => { + unsubscribe(); queue.dispose(); if (uploadQueue === queue) uploadQueue = null; - queueRef.current = null; - }; - }, []); + }, + }; +} - useEffect(() => { - const queued = flattenQueuedThreadMessages(queuedMessages); - const connected = new Set( - connectedEnvironments - .filter((environment) => environment.connectionState === "connected") - .map((environment) => environment.environmentId), - ); - const requests = Object.entries(drafts).flatMap(([key, draft]) => { - const environmentId = composerDraftEnvironmentId(key, queued, draft); - if ( - environmentId === null || - !connected.has(environmentId) || - !operableEnvironments.has(environmentId) - ) - return []; - return draft.attachments - .filter((attachment) => - canUploadComposerAttachment(attachment, serverConfigs.get(environmentId)), - ) - .map((attachment) => ({ environmentId, attachment })); - }); - queueRef.current?.sync(requests); - }, [connectedEnvironments, drafts, operableEnvironments, queuedMessages, serverConfigs]); +export function installComposerAttachmentUploads(): () => void { + return createComposerAttachmentUploadWorker().dispose; } diff --git a/apps/mobile/src/state/legacy-plan-mode.ts b/apps/mobile/src/state/legacy-plan-mode.ts index d768d4dac351c..f4ab2f8c681c2 100644 --- a/apps/mobile/src/state/legacy-plan-mode.ts +++ b/apps/mobile/src/state/legacy-plan-mode.ts @@ -23,20 +23,12 @@ export function resolveLegacyPlanModeEnabled(input: { } export function resolvePendingTaskInteractionMode(input: { - readonly preferenceLoaded: boolean; readonly planModeEnabled: boolean; readonly draftInteractionMode: ProviderInteractionMode | undefined; - readonly queuedInteractionMode: ProviderInteractionMode | undefined; readonly provider?: InteractionModeProvider | null; }): ProviderInteractionMode { - if (input.provider?.showInteractionModeToggle === false) { + if (input.provider?.showInteractionModeToggle === false || !input.planModeEnabled) { return DEFAULT_PROVIDER_INTERACTION_MODE; } - if (input.planModeEnabled) { - return input.draftInteractionMode ?? DEFAULT_PROVIDER_INTERACTION_MODE; - } - if (!input.preferenceLoaded) { - return input.queuedInteractionMode ?? DEFAULT_PROVIDER_INTERACTION_MODE; - } - return DEFAULT_PROVIDER_INTERACTION_MODE; + return input.draftInteractionMode ?? DEFAULT_PROVIDER_INTERACTION_MODE; } diff --git a/apps/mobile/src/state/pending-task-editor-writes.test.ts b/apps/mobile/src/state/pending-task-editor-writes.test.ts deleted file mode 100644 index 8cdfc006a815e..0000000000000 --- a/apps/mobile/src/state/pending-task-editor-writes.test.ts +++ /dev/null @@ -1,272 +0,0 @@ -import { CommandId, EnvironmentId, MessageId, ThreadId } from "@t3tools/contracts"; -import { beforeEach, describe, expect, it, vi } from "vite-plus/test"; - -import type { QueuedThreadMessage } from "./thread-outbox-model"; - -const harness = vi.hoisted(() => ({ - manager: null as unknown as ReturnType< - typeof import("./thread-outbox-manager").createThreadOutboxManager - >, - writeGates: [] as Array<{ - readonly promise: Promise; - readonly started: (message: QueuedThreadMessage) => void; - }>, -})); - -vi.mock("./thread-outbox", async () => { - const { createThreadOutboxManager } = await import("./thread-outbox-manager"); - const { appAtomRegistry } = await import("./atom-registry"); - harness.manager = createThreadOutboxManager({ - registry: appAtomRegistry, - storage: { - load: async () => ({ messages: [], errors: [] }), - write: async (message) => { - const pending = harness.writeGates.shift(); - if (pending) { - pending.started(message); - await pending.promise; - } - }, - remove: async () => undefined, - }, - }); - const manager = harness.manager; - return { - threadOutboxManager: manager, - flushThreadOutbox: async () => undefined, - threadOutboxRevision: (messageId: QueuedThreadMessage["messageId"]) => - manager.revisionOf(messageId), - updateThreadOutboxMessage: (message: QueuedThreadMessage, expectedRevision?: number) => - manager.update(message, expectedRevision), - }; -}); - -import { appAtomRegistry } from "./atom-registry"; -import { - capturePendingTaskEditorWriteBaseline, - flushPendingTaskEditorWrite, -} from "./pending-task-editor-writes"; -import { - composerDraftsAtom, - getComposerDraftSnapshot, - type ComposerDraft, -} from "./use-composer-drafts"; - -function queuedMessage(messageId: string, text: string): QueuedThreadMessage { - return { - environmentId: EnvironmentId.make("environment-1"), - threadId: ThreadId.make("thread-1"), - messageId: MessageId.make(messageId), - commandId: CommandId.make(`command-${messageId}`), - text, - attachments: [], - createdAt: "2026-08-28T12:00:00.000Z", - }; -} - -function draft(text: string): ComposerDraft { - return { - text, - attachments: [], - runtimeMode: "full-access", - }; -} - -function setDraft(draftKey: string, value: ComposerDraft): void { - appAtomRegistry.set(composerDraftsAtom, { [draftKey]: value }); -} - -function queuedMessageText(messageId: QueuedThreadMessage["messageId"]): string | null { - const messages = Object.values( - appAtomRegistry.get(harness.manager.queuedMessagesByThreadKeyAtom), - ).flat(); - return messages.find((message) => message.messageId === messageId)?.text ?? null; -} - -function blockNextWrite() { - let resolveWrite!: () => void; - let rejectWrite!: (error: Error) => void; - let markStarted!: (message: QueuedThreadMessage) => void; - const promise = new Promise((resolve, reject) => { - resolveWrite = resolve; - rejectWrite = reject; - }); - const started = new Promise((resolve) => { - markStarted = resolve; - }); - harness.writeGates.push({ promise, started: markStarted }); - return { - started, - resolve: resolveWrite, - reject: rejectWrite, - }; -} - -beforeEach(() => { - harness.writeGates.length = 0; - appAtomRegistry.set(harness.manager.queuedMessagesByThreadKeyAtom, {}); - appAtomRegistry.set(composerDraftsAtom, {}); -}); - -describe("pending task editor writes", () => { - it("chains a reopened editor that closes before the previous save finishes", async () => { - const original = queuedMessage("message-close-before-save", "original"); - const firstEdit = queuedMessage("message-close-before-save", "first edit"); - const secondEdit = queuedMessage("message-close-before-save", "second edit"); - const draftKey = "pending-task:message-close-before-save"; - await harness.manager.enqueue(original); - - setDraft(draftKey, draft(firstEdit.text)); - const firstBaseline = capturePendingTaskEditorWriteBaseline(original.messageId); - const firstWriteGate = blockNextWrite(); - const firstSave = flushPendingTaskEditorWrite({ - message: firstEdit, - baseline: firstBaseline, - draftKey, - }); - await firstWriteGate.started; - - const secondBaseline = capturePendingTaskEditorWriteBaseline(original.messageId); - setDraft(draftKey, draft(secondEdit.text)); - const secondWriteGate = blockNextWrite(); - const secondSave = flushPendingTaskEditorWrite({ - message: secondEdit, - baseline: secondBaseline, - draftKey, - }); - - firstWriteGate.resolve(); - await expect(firstSave).resolves.toBe(false); - await expect(secondWriteGate.started).resolves.toMatchObject({ text: secondEdit.text }); - secondWriteGate.resolve(); - - await expect(secondSave).resolves.toBe(true); - expect(queuedMessageText(original.messageId)).toBe(secondEdit.text); - }); - - it("keeps a captured predecessor after that predecessor finishes", async () => { - const original = queuedMessage("message-finished-predecessor", "original"); - const firstEdit = queuedMessage("message-finished-predecessor", "first edit"); - const secondEdit = queuedMessage("message-finished-predecessor", "second edit"); - const draftKey = "pending-task:message-finished-predecessor"; - await harness.manager.enqueue(original); - - setDraft(draftKey, draft(firstEdit.text)); - const firstWriteGate = blockNextWrite(); - const firstSave = flushPendingTaskEditorWrite({ - message: firstEdit, - baseline: capturePendingTaskEditorWriteBaseline(original.messageId), - draftKey, - }); - await firstWriteGate.started; - const secondBaseline = capturePendingTaskEditorWriteBaseline(original.messageId); - - firstWriteGate.resolve(); - await expect(firstSave).resolves.toBe(true); - - setDraft(draftKey, draft(secondEdit.text)); - const secondWriteGate = blockNextWrite(); - const secondSave = flushPendingTaskEditorWrite({ - message: secondEdit, - baseline: secondBaseline, - draftKey, - }); - await secondWriteGate.started; - secondWriteGate.resolve(); - - await expect(secondSave).resolves.toBe(true); - expect(queuedMessageText(original.messageId)).toBe(secondEdit.text); - }); - - it("keeps the handed-off revision when the middle editor write fails", async () => { - const original = queuedMessage("message-middle-failure", "original"); - const firstEdit = queuedMessage("message-middle-failure", "first edit"); - const failedEdit = queuedMessage("message-middle-failure", "failed edit"); - const finalEdit = queuedMessage("message-middle-failure", "final edit"); - const draftKey = "pending-task:message-middle-failure"; - await harness.manager.enqueue(original); - - setDraft(draftKey, draft(firstEdit.text)); - const firstWriteGate = blockNextWrite(); - const firstSave = flushPendingTaskEditorWrite({ - message: firstEdit, - baseline: capturePendingTaskEditorWriteBaseline(original.messageId), - draftKey, - }); - await firstWriteGate.started; - - const failedBaseline = capturePendingTaskEditorWriteBaseline(original.messageId); - setDraft(draftKey, draft(failedEdit.text)); - const failedWriteGate = blockNextWrite(); - const failedSave = flushPendingTaskEditorWrite({ - message: failedEdit, - baseline: failedBaseline, - draftKey, - }); - - const finalBaseline = capturePendingTaskEditorWriteBaseline(original.messageId); - setDraft(draftKey, draft(finalEdit.text)); - const finalWriteGate = blockNextWrite(); - const finalSave = flushPendingTaskEditorWrite({ - message: finalEdit, - baseline: finalBaseline, - draftKey, - }); - - firstWriteGate.resolve(); - await expect(firstSave).resolves.toBe(false); - await failedWriteGate.started; - failedWriteGate.reject(new Error("disk full")); - await expect(failedSave).rejects.toMatchObject({ _tag: "ThreadOutboxManagerError" }); - await finalWriteGate.started; - finalWriteGate.resolve(); - - await expect(finalSave).resolves.toBe(true); - expect(queuedMessageText(original.messageId)).toBe(finalEdit.text); - }); - - it("does not overwrite an unrelated update accepted after capture", async () => { - const original = queuedMessage("message-unrelated-update", "original"); - const editorEdit = queuedMessage("message-unrelated-update", "editor edit"); - const unrelatedEdit = queuedMessage("message-unrelated-update", "unrelated edit"); - const draftKey = "pending-task:message-unrelated-update"; - await harness.manager.enqueue(original); - - const editorBaseline = capturePendingTaskEditorWriteBaseline(original.messageId); - const revision = harness.manager.revisionOf(original.messageId); - await expect(harness.manager.update(unrelatedEdit, revision)).resolves.toBe(true); - setDraft(draftKey, draft(editorEdit.text)); - - await expect( - flushPendingTaskEditorWrite({ - message: editorEdit, - baseline: editorBaseline, - draftKey, - }), - ).resolves.toBe(false); - expect(queuedMessageText(original.messageId)).toBe(unrelatedEdit.text); - }); - - it("does not permit cleanup after a newer editor makes the draft unsendable", async () => { - const original = queuedMessage("message-unsendable-draft", "original"); - const editorEdit = queuedMessage("message-unsendable-draft", "saved edit"); - const draftKey = "pending-task:message-unsendable-draft"; - await harness.manager.enqueue(original); - - setDraft(draftKey, draft(editorEdit.text)); - const writeGate = blockNextWrite(); - const save = flushPendingTaskEditorWrite({ - message: editorEdit, - baseline: capturePendingTaskEditorWriteBaseline(original.messageId), - draftKey, - }); - await writeGate.started; - - setDraft(draftKey, draft("")); - writeGate.resolve(); - - await expect(save).resolves.toBe(false); - expect(getComposerDraftSnapshot(draftKey).text).toBe(""); - expect(queuedMessageText(original.messageId)).toBe(editorEdit.text); - }); -}); diff --git a/apps/mobile/src/state/pending-task-editor-writes.ts b/apps/mobile/src/state/pending-task-editor-writes.ts deleted file mode 100644 index 7fe61c30e4c3c..0000000000000 --- a/apps/mobile/src/state/pending-task-editor-writes.ts +++ /dev/null @@ -1,81 +0,0 @@ -import type { QueuedThreadMessage } from "./thread-outbox"; -import { threadOutboxRevision, updateThreadOutboxMessage } from "./thread-outbox"; -import { getComposerDraftSnapshot, sameComposerDraftState } from "./use-composer-drafts"; - -type PendingTaskEditorWriteResult = - | { - readonly status: "complete"; - readonly updated: boolean; - readonly nextRevision: number; - } - | { - readonly status: "failed"; - readonly error: unknown; - readonly nextRevision: number; - }; - -const pendingWrites = new Map< - QueuedThreadMessage["messageId"], - Promise ->(); - -/** Captures the editor revision and predecessor save; the promise survives clearing its map entry. */ -export function capturePendingTaskEditorWriteBaseline( - messageId: QueuedThreadMessage["messageId"], -): Promise { - const capturedRevision = threadOutboxRevision(messageId); - const predecessor = pendingWrites.get(messageId); - if (!predecessor) { - return Promise.resolve(capturedRevision); - } - return predecessor.then( - ({ nextRevision }) => Math.max(capturedRevision, nextRevision), - () => capturedRevision, - ); -} - -export function flushPendingTaskEditorWrite(input: { - readonly message: QueuedThreadMessage; - readonly baseline: Promise; - readonly draftKey: string; -}): Promise { - const { message } = input; - const draftSnapshot = getComposerDraftSnapshot(input.draftKey); - const write = input.baseline.then( - async (expectedRevision): Promise => { - try { - const updated = await updateThreadOutboxMessage(message, expectedRevision); - return { - status: "complete", - updated, - nextRevision: expectedRevision + (updated ? 1 : 0), - }; - } catch (error) { - // Failed writes do not advance the outbox; hand their expected revision to later editor saves. - return { - status: "failed", - error, - nextRevision: expectedRevision, - }; - } - }, - ); - - pendingWrites.set(message.messageId, write); - const removeWrite = (): void => { - if (pendingWrites.get(message.messageId) === write) { - pendingWrites.delete(message.messageId); - } - }; - void write.then(removeWrite, removeWrite); - - return write.then((result) => { - if (result.status === "failed") { - throw result.error; - } - return ( - result.updated && - sameComposerDraftState(draftSnapshot, getComposerDraftSnapshot(input.draftKey)) - ); - }); -} diff --git a/apps/mobile/src/state/pull-requests.ts b/apps/mobile/src/state/pull-requests.ts index 5d6b5980fa9b0..e803bd0de1f31 100644 --- a/apps/mobile/src/state/pull-requests.ts +++ b/apps/mobile/src/state/pull-requests.ts @@ -4,7 +4,8 @@ import { } from "@t3tools/client-runtime/state/pull-requests"; import type { EnvironmentId, PullRequestDiffStat, PullRequestListInput } from "@t3tools/contracts"; import * as Effect from "effect/Effect"; -import { Atom } from "effect/reactivity"; +import * as Option from "effect/Option"; +import { AsyncResult, Atom } from "effect/reactivity"; import { connectionAtomRuntime } from "../connection/runtime"; import { pullRequestListHead, @@ -28,6 +29,14 @@ export const pullRequestListStatsFamily = Atom.family((_environmentId: string) = ); export const composerPullRequests = createPullRequestEnvironmentAtoms(connectionAtomRuntime, { + // A new head can change which files GitHub still counts as viewed, so the viewed-files read is + // refreshed where the new head lands. The detail atom still holds the previous answer here. + detail: (target, value, registry) => + Effect.sync(() => { + const previous = AsyncResult.value(registry.get(composerPullRequests.detail(target))); + if (Option.isSome(previous) && previous.value.headSha !== value.headSha) + registry.refresh(composerPullRequests.filesViewed(target)); + }), list: (target, value, registry) => target.input.cursors === undefined ? Effect.sync(() => diff --git a/apps/mobile/src/state/session.ts b/apps/mobile/src/state/session.ts index ead11793f6a42..010325dfe722a 100644 --- a/apps/mobile/src/state/session.ts +++ b/apps/mobile/src/state/session.ts @@ -17,7 +17,7 @@ export const environmentSession = createEnvironmentSessionAtoms(connectionAtomRu const EMPTY_SESSION_STATE_ATOM = Atom.make(AsyncResult.initial()); -function sessionHasScope( +export function sessionHasScope( result: AsyncResult.AsyncResult, scope: AuthEnvironmentScope, ): boolean { diff --git a/apps/mobile/src/state/use-thread-outbox-drain.permissions.test.ts b/apps/mobile/src/state/threadOutboxDelivery.permissions.test.ts similarity index 67% rename from apps/mobile/src/state/use-thread-outbox-drain.permissions.test.ts rename to apps/mobile/src/state/threadOutboxDelivery.permissions.test.ts index f199616d43c46..edc80c5007024 100644 --- a/apps/mobile/src/state/use-thread-outbox-drain.permissions.test.ts +++ b/apps/mobile/src/state/threadOutboxDelivery.permissions.test.ts @@ -13,15 +13,21 @@ import { afterEach, beforeEach, describe, expect, it, vi } from "vite-plus/test" import type { QueuedThreadMessage } from "./thread-outbox-model"; const state = vi.hoisted(() => ({ - grantedEnvironments: new Set(), draftText: "Keep this draft separate", cleanups: [] as Array<() => void>, + delivery: null as { + readonly drain: () => void; + readonly dispose: () => void; + } | null, start: vi.fn(), metadata: vi.fn(), runtime: vi.fn(), interaction: vi.fn(), prepare: vi.fn(), checkout: vi.fn(), + modelUnavailable: vi.fn(() => false), + familyMount: vi.fn(() => () => {}), + threadShells: null as unknown as Atom.Writable>, manager: null as unknown as ReturnType< typeof import("./thread-outbox-manager").createThreadOutboxManager >, @@ -34,42 +40,53 @@ const state = vi.hoisted(() => ({ session: null, }, config: { + shellThreadFamilies: false, providers: [{ instanceId: "codex", driver: "codex" }], environment: { capabilities: {} }, }, })); -vi.mock("react", () => ({ - useCallback: (callback: A) => callback, - useEffect: (effect: () => void | (() => void)) => { - const cleanup = effect(); - if (cleanup) state.cleanups.push(cleanup); - }, - useRef: (value: A) => ({ current: value }), - useState: (initial: A) => [initial, vi.fn()], -})); vi.mock("react-native", () => ({ Alert: { alert: vi.fn() } })); -vi.mock("@effect/atom-react", async () => { +vi.mock("@t3tools/client-runtime/state/runtime", async (importOriginal) => ({ + ...(await importOriginal()), + runAtomCommand: (_registry: unknown, command: (input: unknown) => unknown, input: unknown) => + command(input), +})); +vi.mock("./session", async () => { + const { Atom } = await import("effect/reactivity"); const { appAtomRegistry } = await import("./atom-registry"); - return { useAtomValue: (atom: Atom.Atom) => appAtomRegistry.get(atom) }; + // A session's state is reduced to whether it grants the operate scope. + const sessionStateAtom = Atom.family((_id: string) => Atom.make(false).pipe(Atom.keepAlive)); + const sessionHasScope = (granted: boolean, scope: string) => + granted && scope === AuthOrchestrationOperateScope; + return { + environmentSession: { sessionStateAtom }, + sessionHasScope, + readEnvironmentScope: (environmentId: string, scope: string) => + sessionHasScope(appAtomRegistry.get(sessionStateAtom(environmentId)), scope), + }; +}); +vi.mock("./projects", async () => { + const { Atom } = await import("effect/reactivity"); + return { environmentProjects: { projectsAtom: Atom.make([]) } }; +}); +vi.mock("./workspace", async () => { + const { Atom } = await import("effect/reactivity"); + return { + workspaceConnections: { + environmentsAtom: Atom.make([{ environmentId: "secondary", connectionState: "connected" }]), + }, + }; }); -vi.mock("./session", () => ({ - readEnvironmentScope: (environmentId: string, scope: string) => - scope === AuthOrchestrationOperateScope && state.grantedEnvironments.has(environmentId), - useEnvironmentsWithScope: () => state.grantedEnvironments, -})); -vi.mock("./entities", () => ({ - useProjects: () => [], - useThreadShells: () => [state.thread], - useServerConfigs: () => new Map([["secondary", state.config]]), -})); vi.mock("./server", async () => { const { Atom } = await import("effect/reactivity"); return { serverEnvironment: { configValueAtom: Atom.family((_id: string) => Atom.make(state.config)) }, + environmentServerConfigsAtom: Atom.make(new Map([["secondary", state.config]])), }; }); vi.mock("./threads", async () => { - const { Atom } = await import("effect/reactivity"); + const { Atom, AsyncResult } = await import("effect/reactivity"); + state.threadShells = Atom.make>([state.thread]).pipe(Atom.keepAlive); return { threadEnvironment: { startTurn: state.start, @@ -77,21 +94,19 @@ vi.mock("./threads", async () => { setRuntimeMode: state.runtime, setInteractionMode: state.interaction, }, - environmentThreadShells: { threadShellsAtom: Atom.make([state.thread]) }, - environmentThreadDetails: { threadAtom: Atom.family((_key: unknown) => Atom.make(null)) }, + environmentThreadShells: { threadShellsAtom: state.threadShells }, + threadFamilies: { + mount: state.familyMount, + familyAtom: () => Atom.make(AsyncResult.success({})), + refresh: vi.fn(), + }, + environmentThreadDetails: { threadAtom: () => Atom.make(null) }, }; }); -vi.mock("./use-atom-command", () => ({ useAtomCommand: (command: A) => command })); vi.mock("./git", () => ({ gitEnvironment: { preparePullRequestThread: state.checkout } })); -vi.mock("../lib/modelOptions", () => ({ isModelSelectionUnavailable: () => false })); +vi.mock("../lib/modelOptions", () => ({ isModelSelectionUnavailable: state.modelUnavailable })); vi.mock("../lib/uuid", () => ({ uuidv4: () => "uuid", randomHex: () => "abcd" })); vi.mock("../lib/attachmentUpload", () => ({ prepareTurnAttachments: state.prepare })); -vi.mock("./use-remote-environment-registry", () => ({ - setPendingConnectionError: vi.fn(), - useRemoteConnectionStatus: () => ({ - connectedEnvironments: [{ environmentId: "secondary", connectionState: "connected" }], - }), -})); vi.mock("./thread-outbox", async () => { const { createThreadOutboxManager } = await import("./thread-outbox-manager"); const { appAtomRegistry } = await import("./atom-registry"); @@ -118,13 +133,10 @@ vi.mock("./thread-outbox-removal", () => ({ })); vi.mock("./use-thread-outbox", async () => { const { Atom } = await import("effect/reactivity"); - const { appAtomRegistry } = await import("./atom-registry"); - await import("./thread-outbox"); return { editingQueuedMessageIdsAtom: Atom.make({}).pipe(Atom.keepAlive), dispatchingQueuedMessageIdAtom: Atom.make(null).pipe(Atom.keepAlive), - useThreadOutboxMessages: () => appAtomRegistry.get(state.manager.queuedMessagesByThreadKeyAtom), - useThreadOutboxShellStatuses: () => new Map([["secondary", "live"]]), + threadOutboxShellStatusesAtom: Atom.make(new Map([["secondary", "live"]])), }; }); vi.mock("./use-composer-drafts", async () => { @@ -146,8 +158,9 @@ vi.mock("./use-composer-drafts", async () => { }); import { appAtomRegistry } from "./atom-registry"; -import { dispatchingQueuedMessageIdAtom } from "./use-thread-outbox"; -import { useThreadOutboxDrain } from "./use-thread-outbox-drain"; +import { environmentSession } from "./session"; +import { dispatchingQueuedMessageIdAtom, editingQueuedMessageIdsAtom } from "./use-thread-outbox"; +import { createThreadOutboxDelivery } from "./threadOutboxDelivery"; const message = (overrides: Partial = {}): QueuedThreadMessage => ({ environmentId: EnvironmentId.make("secondary"), @@ -162,20 +175,46 @@ const message = (overrides: Partial = {}): QueuedThreadMess const remaining = () => Object.values(appAtomRegistry.get(state.manager.queuedMessagesByThreadKeyAtom)).flat(); +function setOperateGrant(environmentId: string, granted: boolean): void { + // The mocked session atom holds the grant itself (see the ./session mock). + const sessionAtom = environmentSession.sessionStateAtom(EnvironmentId.make(environmentId)); + appAtomRegistry.set(sessionAtom as unknown as Atom.Writable, granted); +} + function runDrain() { const settled = Promise.withResolvers(); const release = appAtomRegistry.subscribe(dispatchingQueuedMessageIdAtom, (id) => { if (id === null) settled.resolve(); }); - useThreadOutboxDrain(); + startDelivery(); return settled.promise.finally(release); } +/** Starts the service once per test; later calls run another drain pass. */ +function startDelivery(): void { + if (state.delivery !== null) { + state.delivery.drain(); + return; + } + const delivery = createThreadOutboxDelivery(); + state.delivery = delivery; + state.cleanups.push(() => { + delivery.dispose(); + state.delivery = null; + }); +} + beforeEach(() => { - state.grantedEnvironments = new Set(["primary"]); + setOperateGrant("primary", true); + setOperateGrant("secondary", false); state.draftText = "Keep this draft separate"; + state.config.shellThreadFamilies = false; + state.modelUnavailable.mockReset().mockReturnValue(false); + state.familyMount.mockReset().mockReturnValue(() => {}); + appAtomRegistry.set(state.threadShells, [state.thread]); appAtomRegistry.set(state.manager.queuedMessagesByThreadKeyAtom, {}); appAtomRegistry.set(dispatchingQueuedMessageIdAtom, null); + appAtomRegistry.set(editingQueuedMessageIdsAtom, {}); for (const command of [ state.start, state.metadata, @@ -214,7 +253,7 @@ describe("queued PR checkout", () => { }; it("waits for the provider's PR checkout and launches in that worktree", async () => { - state.grantedEnvironments.add("secondary"); + setOperateGrant("secondary", true); await state.manager.enqueue(queuedPullRequest()); const started = Promise.withResolvers(); const checkout = @@ -243,7 +282,7 @@ describe("queued PR checkout", () => { }); it("keeps the PR source queued on a transport failure without starting the agent", async () => { - state.grantedEnvironments.add("secondary"); + setOperateGrant("secondary", true); const queued = queuedPullRequest(); await state.manager.enqueue(queued); state.checkout.mockResolvedValueOnce( @@ -255,11 +294,11 @@ describe("queued PR checkout", () => { }); it("stops launch if operation access is revoked while checking out the PR", async () => { - state.grantedEnvironments.add("secondary"); + setOperateGrant("secondary", true); const queued = queuedPullRequest(); await state.manager.enqueue(queued); state.checkout.mockImplementationOnce(async () => { - state.grantedEnvironments.delete("secondary"); + setOperateGrant("secondary", false); return AsyncResult.success(preparedCheckout); }); await runDrain(); @@ -268,7 +307,7 @@ describe("queued PR checkout", () => { }); it("does not launch a stale task edited while the PR checkout was running", async () => { - state.grantedEnvironments.add("secondary"); + setOperateGrant("secondary", true); const queued = queuedPullRequest(); await state.manager.enqueue(queued); const edited = { ...queued, text: "Updated instructions" }; @@ -289,18 +328,63 @@ describe("queued task operation access", () => { it("parks a connected read-only target, then delivers its unchanged queue after a grant", async () => { const queued = message(); await state.manager.enqueue(queued); - useThreadOutboxDrain(); + startDelivery(); expect(state.start).not.toHaveBeenCalled(); expect(state.prepare).not.toHaveBeenCalled(); expect(remaining()).toEqual([queued]); - state.grantedEnvironments.add("secondary"); + setOperateGrant("secondary", true); + await runDrain(); + expect(state.start).toHaveBeenCalledOnce(); + expect(remaining()).toEqual([]); + }); + + it("backs off instead of redelivering at once when a delivery hits a defect", async () => { + setOperateGrant("secondary", true); + const queued = message(); + await state.manager.enqueue(queued); + // Awaited steps catch their own failures, so a defect in the delivery's own code is what + // rejects a delivery. + state.modelUnavailable.mockImplementationOnce(() => { + throw new TypeError("Cannot read properties of undefined"); + }); await runDrain(); + expect(state.modelUnavailable).toHaveBeenCalledOnce(); + expect(state.prepare).not.toHaveBeenCalled(); + expect(state.start).not.toHaveBeenCalled(); + expect(appAtomRegistry.get(dispatchingQueuedMessageIdAtom)).toBeNull(); + expect(remaining()).toEqual([queued]); + }); + + it("starts one delivery when mounting a thread family changes the rows mid-pass", async () => { + setOperateGrant("secondary", true); + state.config.shellThreadFamilies = true; + const subAgentThread = { ...state.thread, id: "sub-agent" }; + // A cached family merges its rows into the shell list as soon as it is mounted. + state.familyMount.mockImplementationOnce(() => { + appAtomRegistry.set(state.threadShells, [state.thread, subAgentThread]); + return () => {}; + }); + const queued = message({ threadId: ThreadId.make("sub-agent") }); + startDelivery(); + appAtomRegistry.set(editingQueuedMessageIdsAtom, { [queued.messageId]: true }); + await state.manager.enqueue(queued); + using confirm = vi.spyOn(state.manager, "confirmQueued"); + const delivered = Promise.withResolvers(); + const release = appAtomRegistry.subscribe(dispatchingQueuedMessageIdAtom, (id) => { + if (id === null) delivered.resolve(); + }); + // Ending the edit wakes the drain through a registry notification, the path on which the + // mount's synchronous row change notifies the drain again mid-pass. + appAtomRegistry.set(editingQueuedMessageIdsAtom, {}); + expect(state.familyMount).toHaveBeenCalledOnce(); + expect(confirm).toHaveBeenCalledOnce(); + await delivered.promise.finally(release); expect(state.start).toHaveBeenCalledOnce(); expect(remaining()).toEqual([]); }); it("stops the remaining settings and turn commands when an earlier update loses access", async () => { - state.grantedEnvironments.add("secondary"); + setOperateGrant("secondary", true); const queued = message({ modelSelection: { instanceId: ProviderInstanceId.make("codex"), model: "different-model" }, runtimeMode: "approval-required", @@ -308,7 +392,7 @@ describe("queued task operation access", () => { }); await state.manager.enqueue(queued); state.runtime.mockImplementationOnce(async () => { - state.grantedEnvironments.delete("secondary"); + setOperateGrant("secondary", false); return AsyncResult.success(undefined); }); await runDrain(); @@ -325,7 +409,7 @@ describe("queued task operation access", () => { ])( "preserves a rejected queue but removes an accepted turn after access loss (new task: $isCreation, accepted: $accepted)", async ({ isCreation, accepted }) => { - state.grantedEnvironments.add("secondary"); + setOperateGrant("secondary", true); const queued = message( isCreation ? { @@ -350,7 +434,7 @@ describe("queued task operation access", () => { }); const drained = runDrain(); await started.promise; - state.grantedEnvironments.delete("secondary"); + setOperateGrant("secondary", false); delivery.resolve( accepted ? AsyncResult.success(undefined) @@ -361,7 +445,7 @@ describe("queued task operation access", () => { expect(remaining()).toEqual(accepted ? [] : [queued]); expect(state.draftText).toBe("Keep this draft separate"); if (!accepted) { - state.grantedEnvironments.add("secondary"); + setOperateGrant("secondary", true); await runDrain(); expect(state.start).toHaveBeenCalledTimes(2); expect(remaining()).toEqual([]); @@ -378,7 +462,7 @@ describe("queued task operation access", () => { ])( "keeps the message queued after upload revocation (new task: $isCreation, upload fails: $uploadFails)", async ({ isCreation, uploadFails }) => { - state.grantedEnvironments.add("secondary"); + setOperateGrant("secondary", true); const queued = message( isCreation ? { @@ -396,7 +480,7 @@ describe("queued task operation access", () => { ); await state.manager.enqueue(queued); state.prepare.mockImplementationOnce(async ({ attachments }) => { - state.grantedEnvironments.delete("secondary"); + setOperateGrant("secondary", false); if (uploadFails) throw new Error("This connection cannot upload attachments."); return { status: "ready", diff --git a/apps/mobile/src/state/use-thread-outbox-drain.test.ts b/apps/mobile/src/state/threadOutboxDelivery.test.ts similarity index 93% rename from apps/mobile/src/state/use-thread-outbox-drain.test.ts rename to apps/mobile/src/state/threadOutboxDelivery.test.ts index c4968d3e33e89..901ffaa9e8291 100644 --- a/apps/mobile/src/state/use-thread-outbox-drain.test.ts +++ b/apps/mobile/src/state/threadOutboxDelivery.test.ts @@ -13,6 +13,9 @@ import type { PreparedTurnAttachments } from "../lib/attachmentUpload"; const harness = vi.hoisted(() => ({ canOperate: true, + threadProjection: null as unknown as import("effect/reactivity").Atom.Writable<{ + readonly projection: { readonly messages: ReadonlyArray<{ readonly id: string }> }; + } | null>, manager: null as unknown as ReturnType< typeof import("./thread-outbox-manager").createThreadOutboxManager >, @@ -76,11 +79,9 @@ vi.mock("../lib/attachmentUpload", () => ({ prepareTurnAttachments: harness.prepareTurnAttachments, })); -vi.mock("./entities", () => ({ - useProjects: () => [], - useServerConfigs: () => new Map(), - useThreadShells: () => [], -})); +vi.mock("./projects", () => ({ environmentProjects: {} })); + +vi.mock("./workspace", () => ({ workspaceConnections: {} })); vi.mock("./server", async () => { const { Atom } = await import("effect/reactivity"); @@ -91,34 +92,30 @@ vi.mock("./git", () => ({ gitEnvironment: {} })); vi.mock("./threads", async () => { const { Atom } = await import("effect/reactivity"); + harness.threadProjection = Atom.make<{ + readonly projection: { readonly messages: ReadonlyArray<{ readonly id: string }> }; + } | null>(null).pipe(Atom.keepAlive); return { threadEnvironment: {}, - environmentThreadDetails: { threadAtom: Atom.family((_key: unknown) => Atom.make(null)) }, + environmentThreadDetails: { threadAtom: () => harness.threadProjection }, }; }); -vi.mock("./use-atom-command", () => ({ - useAtomCommand: () => async () => undefined, -})); - vi.mock("./session", () => ({ + environmentSession: {}, readEnvironmentScope: () => harness.canOperate, - useEnvironmentsWithScope: () => new Set(), + sessionHasScope: () => harness.canOperate, })); vi.mock("./use-thread-outbox", async () => { const { Atom } = await import("effect/reactivity"); return { editingQueuedMessageIdsAtom: Atom.make>({}).pipe(Atom.keepAlive), - useThreadOutboxMessages: () => ({}), - useThreadOutboxShellStatuses: () => new Map(), + dispatchingQueuedMessageIdAtom: Atom.make(null).pipe(Atom.keepAlive), + threadOutboxShellStatusesAtom: Atom.make(new Map()), }; }); -vi.mock("./use-remote-environment-registry", () => ({ - useRemoteConnectionStatus: () => ({ connectedEnvironments: [] }), -})); - vi.mock("./thread-outbox", async () => { const { createThreadOutboxManager } = await import("./thread-outbox-manager"); const { appAtomRegistry } = await import("./atom-registry"); @@ -154,7 +151,7 @@ import { recoverEditedCreationAfterDelivery, removeAcknowledgedExistingThreadMessage, restoreRejectedQueuedMessage, -} from "./use-thread-outbox-drain"; +} from "./threadOutboxDelivery"; function queuedMessage(input: { readonly messageId: string; @@ -207,6 +204,7 @@ function remainingMessages(): ReadonlyArray { beforeEach(() => { appAtomRegistry.set(acknowledgedThreadMessagesAtom, []); + appAtomRegistry.set(harness.threadProjection, null); harness.canOperate = true; harness.draftFile.setDocument({ schemaVersion: 1, drafts: {} }); }); @@ -332,6 +330,28 @@ describe("thread outbox attachment preparation", () => { }); describe("thread outbox drain delivery cleanup", () => { + it("drops echoed acknowledged rows at the next delivery without subscribing to the thread", async () => { + const first = queuedMessage({ messageId: "awaiting-echo", text: "Delivered" }); + const second = queuedMessage({ messageId: "next-delivery", text: "Also delivered" }); + await harness.manager.enqueue(first); + await harness.manager.enqueue(second); + + await expect( + completeQueuedMessageDelivery(first, harness.manager.revisionOf(first.messageId)), + ).resolves.toBe("removed"); + expect(appAtomRegistry.get(acknowledgedThreadMessagesAtom)).toEqual([first]); + + appAtomRegistry.set(harness.threadProjection, { + projection: { messages: [{ id: "unrelated" }, { id: first.messageId }] }, + }); + expect(appAtomRegistry.get(acknowledgedThreadMessagesAtom)).toEqual([first]); + + await expect( + completeQueuedMessageDelivery(second, harness.manager.revisionOf(second.messageId)), + ).resolves.toBe("removed"); + expect(appAtomRegistry.get(acknowledgedThreadMessagesAtom)).toEqual([second]); + }); + it("removes an acknowledged outbox item even when the sign-out archive write fails", async () => { const message = queuedMessage({ messageId: "archive-write-failure", text: "Delivered" }); await harness.manager.enqueue(message); diff --git a/apps/mobile/src/state/use-thread-outbox-drain.ts b/apps/mobile/src/state/threadOutboxDelivery.ts similarity index 55% rename from apps/mobile/src/state/use-thread-outbox-drain.ts rename to apps/mobile/src/state/threadOutboxDelivery.ts index 49a94b394c7bf..89c6f13358952 100644 --- a/apps/mobile/src/state/use-thread-outbox-drain.ts +++ b/apps/mobile/src/state/threadOutboxDelivery.ts @@ -1,12 +1,15 @@ import { sourceControlClients } from "@t3tools/client-runtime/source-control-clients"; import * as Dialog from "../components/ui/Dialog"; -import { useAtomValue } from "@effect/atom-react"; import { threadRuntimeIsActive, type EnvironmentProject, type EnvironmentThreadShell, } from "@t3tools/client-runtime/state/shell"; -import type { AtomCommandResult } from "@t3tools/client-runtime/state/runtime"; +import { + type AtomCommand, + type AtomCommandResult, + runAtomCommand, +} from "@t3tools/client-runtime/state/runtime"; import { threadFamilyRead, type ThreadFamilyRead } from "@t3tools/client-runtime/state/threads"; import { deriveThreadTitleSeed } from "@t3tools/client-runtime/operations"; import { @@ -15,12 +18,12 @@ import { DEFAULT_PROVIDER_INTERACTION_MODE, DEFAULT_RUNTIME_MODE, PROVIDER_SEND_TURN_MAX_ATTACHMENTS, + type EnvironmentId, type MessageId, } from "@t3tools/contracts"; import { buildTemporaryWorktreeBranchName } from "@t3tools/shared/git"; import * as Cause from "effect/Cause"; -import { AsyncResult } from "effect/reactivity"; -import { useCallback, useEffect, useRef, useState } from "react"; +import { AsyncResult, Atom } from "effect/reactivity"; import { createDebugLogger } from "../lib/debugLog"; import { scopedThreadKey } from "../lib/scopedEntities"; @@ -38,15 +41,15 @@ import { } from "./acknowledged-thread-messages"; import { appAtomRegistry } from "./atom-registry"; import { restoredNewTaskDraftKey } from "./new-task-draft-key"; -import { useProjects, useServerConfigs, useThreadShells } from "./entities"; import { clearPendingThreadCreationOutcome, pendingThreadCreationOutcomesAtom, recordPendingThreadCreationOutcome, } from "./pending-thread-creation"; -import { serverEnvironment } from "./server"; +import { environmentProjects } from "./projects"; +import { environmentServerConfigsAtom, serverEnvironment } from "./server"; import { gitEnvironment } from "./git"; -import { readEnvironmentScope, useEnvironmentsWithScope } from "./session"; +import { environmentSession, readEnvironmentScope, sessionHasScope } from "./session"; import { confirmThreadOutboxMessageQueued, threadOutboxManager, @@ -81,15 +84,13 @@ import { updateComposerDraftSettings, waitForComposerDraftsLoaded, } from "./use-composer-drafts"; -import { useAtomCommand } from "./use-atom-command"; import { dispatchingQueuedMessageIdAtom, editingQueuedMessageIdsAtom, - useThreadOutboxMessages, - useThreadOutboxShellStatuses, + threadOutboxShellStatusesAtom, } from "./use-thread-outbox"; import { clearThreadComposerError, setThreadComposerError } from "./thread-composer-error"; -import { useRemoteConnectionStatus } from "./use-remote-environment-registry"; +import { workspaceConnections } from "./workspace"; const threadOutboxDebug = createDebugLogger("thread-outbox"); @@ -571,459 +572,308 @@ async function preserveUploadedAttachmentsForEditor( } } -export function useThreadOutboxDrain(): void { - const startTurn = useAtomCommand(threadEnvironment.startTurn, { reportFailure: false }); - const preparePullRequest = useAtomCommand(gitEnvironment.preparePullRequestThread, { - reportFailure: false, - }); - const setThreadRuntimeMode = useAtomCommand(threadEnvironment.setRuntimeMode, { - reportFailure: false, - }); - const setThreadInteractionMode = useAtomCommand(threadEnvironment.setInteractionMode, { - reportFailure: false, - }); - const dispatchingQueuedMessageId = useAtomValue(dispatchingQueuedMessageIdAtom); - const editingQueuedMessageIds = useAtomValue(editingQueuedMessageIdsAtom); - const queuedMessagesByThreadKey = useThreadOutboxMessages(); - const shellStatuses = useThreadOutboxShellStatuses(); - const threads = useThreadShells(); - const creationOutcomes = useAtomValue(pendingThreadCreationOutcomesAtom); - const projects = useProjects(); - const serverConfigs = useServerConfigs(); - const { connectedEnvironments } = useRemoteConnectionStatus(); - const operableEnvironments = useEnvironmentsWithScope( +// Everything a drain pass decides from. Each queued environment's session is +// read here so a granted or revoked operate scope re-runs the drain. +const deliveryInputsAtom = Atom.make((get) => { + const connectedEnvironments = get(workspaceConnections.environmentsAtom); + const operableEnvironments = new Set(); + for (const { environmentId } of connectedEnvironments) { + if ( + sessionHasScope( + get(environmentSession.sessionStateAtom(environmentId)), + AuthOrchestrationOperateScope, + ) + ) { + operableEnvironments.add(environmentId); + } + } + return { + dispatchingQueuedMessageId: get(dispatchingQueuedMessageIdAtom), + editingQueuedMessageIds: get(editingQueuedMessageIdsAtom), + queuedMessagesByThreadKey: get(threadOutboxManager.queuedMessagesByThreadKeyAtom), + shellStatuses: get(threadOutboxShellStatusesAtom), + threads: get(environmentThreadShells.threadShellsAtom), + projects: get(environmentProjects.projectsAtom), + serverConfigs: get(environmentServerConfigsAtom), connectedEnvironments, - AuthOrchestrationOperateScope, - ); - const [retryTick, setRetryTick] = useState(0); - const retryAttemptRef = useRef(new Map()); - const retryNotBeforeRef = useRef(new Map()); - const retryTimersRef = useRef(new Map>()); - const acknowledgedExistingThreadMessageIdsRef = useRef(new Set()); - // Targets the shell may have left out hold their thread family until they leave the queue, so - // the row stays readable through dispatch. - const familyMountsRef = useRef(new Map void>()); - useEffect( - () => () => { - for (const release of familyMountsRef.current.values()) release(); - familyMountsRef.current.clear(); - }, - [], - ); - const blockedRecoverySubscriptionsRef = useRef( - new Map< - MessageId, - { readonly message: QueuedThreadMessage; readonly unsubscribe: () => void } - >(), - ); + operableEnvironments, + }; +}).pipe(Atom.withLabel("mobile:thread-outbox:delivery-inputs")); - const scheduleQueuedMessageRetry = useCallback((messageId: MessageId) => { - const retryAttempt = (retryAttemptRef.current.get(messageId) ?? 0) + 1; - retryAttemptRef.current.set(messageId, retryAttempt); - const retryDelayMs = threadOutboxRetryDelayMs(retryAttempt); - retryNotBeforeRef.current.set(messageId, Date.now() + retryDelayMs); - const pendingTimer = retryTimersRef.current.get(messageId); - if (pendingTimer !== undefined) { - clearTimeout(pendingTimer); - } - const retryTimer = setTimeout(() => { - retryTimersRef.current.delete(messageId); - setRetryTick((current) => current + 1); - }, retryDelayMs); - retryTimersRef.current.set(messageId, retryTimer); - }, []); +// Read through the shell atom, not once: the shell often lands before the +// outcome is recorded, and that entry must still be collected when it does. +const settledCreationOutcomeKeysAtom = Atom.make((get): ReadonlyArray => { + const outcomes = get(pendingThreadCreationOutcomesAtom); + const threads = get(environmentThreadShells.threadShellsAtom); + return Object.entries(outcomes).flatMap(([threadKey, outcome]) => + outcome.kind === "delivered" && + threads.some( + (thread) => + scopedThreadKey(thread.environmentId, thread.id) === threadKey && + (thread.latestRun !== null || + thread.runtime?.status === "failed" || + thread.runtime?.status === "cancelled" || + thread.runtime?.status === "interrupted"), + ) + ? [threadKey] + : [], + ); +}).pipe(Atom.withLabel("mobile:thread-outbox:settled-creation-outcomes")); - const restoreQueuedMessage = useCallback( - async (queuedMessage: QueuedThreadMessage, message: string): Promise => { - const result = await restoreRejectedQueuedMessage(queuedMessage, message); - if (result !== "blocked") { - return result !== "retry"; - } +const runDeliveryCommand = ( + command: AtomCommand, + input: W, +): Promise> => + runAtomCommand(appAtomRegistry, command, input, { reportFailure: false }); - if (!blockedRecoverySubscriptionsRef.current.has(queuedMessage.messageId)) { - const draftKey = recoveryDraftKey(queuedMessage); - const editorDraftKey = queuedMessage.creation - ? `pending-task:${queuedMessage.messageId}` - : null; - const currentDrafts = appAtomRegistry.get(composerDraftsAtom); - const blockedAttachments = currentDrafts[draftKey]?.attachments; - const editorAttachments = - editorDraftKey === null ? undefined : currentDrafts[editorDraftKey]?.attachments; - const unsubscribe = appAtomRegistry.subscribe(composerDraftsAtom, (drafts) => { - if ( - drafts[draftKey]?.attachments === blockedAttachments && - (editorDraftKey === null || drafts[editorDraftKey]?.attachments === editorAttachments) - ) { - return; - } - const active = blockedRecoverySubscriptionsRef.current.get(queuedMessage.messageId); - if (!active) { - return; - } - blockedRecoverySubscriptionsRef.current.delete(queuedMessage.messageId); - active.unsubscribe(); - setRetryTick((current) => current + 1); - }); - blockedRecoverySubscriptionsRef.current.set(queuedMessage.messageId, { - message: queuedMessage, - unsubscribe, - }); - } - return true; +function reportCommandFailure( + queuedMessage: QueuedThreadMessage, + commandResult: AtomCommandResult, + stage: ThreadOutboxCommandStage, +): { readonly action: "retry" | "restore"; readonly message: string } | null { + if (!AsyncResult.isFailure(commandResult)) { + return null; + } + const error = Cause.squash(commandResult.cause); + const action = logThreadOutboxDeliveryFailure({ + stage, + error, + interrupted: Cause.hasInterruptsOnly(commandResult.cause), + context: { + environmentId: queuedMessage.environmentId, + threadId: queuedMessage.threadId, + messageId: queuedMessage.messageId, + cause: commandResult.cause, }, - [], - ); + }); + return { + action, + message: error instanceof Error ? error.message : "The message could not be sent.", + }; +} - useEffect(() => { - let mounted = true; - const load = async () => { - if ((await threadOutboxManager.load()) || !mounted) return; - Dialog.alert( - "Some queued messages could not be loaded", - "Unreadable records and attachment files are still saved. Other messages can still be sent.", - [ - { text: "Dismiss", style: "cancel" }, - { text: "Retry", onPress: () => void load() }, - ], - ); - }; - void load(); - return () => { - mounted = false; - for (const timer of retryTimersRef.current.values()) { - clearTimeout(timer); - } - retryTimersRef.current.clear(); - for (const blocked of blockedRecoverySubscriptionsRef.current.values()) { - blocked.unsubscribe(); - } - blockedRecoverySubscriptionsRef.current.clear(); - }; - }, []); +interface ThreadOutboxRetry { + readonly attempt: number; + readonly notBefore: number; + readonly timer: ReturnType; +} - const makeDeliveryHelpers = useCallback((queuedMessage: QueuedThreadMessage) => { - const reportFailure = ( - commandResult: AtomCommandResult, - stage: ThreadOutboxCommandStage, - ): { readonly action: "retry" | "restore"; readonly message: string } | null => { - if (!AsyncResult.isFailure(commandResult)) { - return null; - } - const error = Cause.squash(commandResult.cause); - const action = logThreadOutboxDeliveryFailure({ - stage, - error, - interrupted: Cause.hasInterruptsOnly(commandResult.cause), - context: { - environmentId: queuedMessage.environmentId, - threadId: queuedMessage.threadId, - messageId: queuedMessage.messageId, - cause: commandResult.cause, - }, - }); - return { - action, - message: error instanceof Error ? error.message : "The message could not be sent.", - }; - }; - return { reportFailure }; - }, []); +/** + * Delivers queued thread messages one at a time. A drain pass runs whenever its inputs + * change (outbox, locks, shells, projects, configs, connections, scopes) and when a retry + * backoff expires. `dispatchingQueuedMessageIdAtom` is the single in-flight slot; clearing + * it re-runs the drain for the next message. + */ +export function createThreadOutboxDelivery(): { + readonly drain: () => void; + readonly dispose: () => void; +} { + let disposed = false; + const retries = new Map(); + // Existing-thread turns the server accepted but whose outbox removal has + // not landed; the next pass retries only the removal, never the send. + const acknowledgedExistingThreadMessageIds = new Set(); + // Targets the shell may have left out hold their thread family until they leave the queue, so + // the row stays readable through dispatch. + const familyMounts = new Map void>(); + const blockedRecoveries = new Map< + MessageId, + { readonly message: QueuedThreadMessage; readonly unsubscribe: () => void } + >(); - const sendQueuedMessage = useCallback( - async (queuedMessage: QueuedThreadMessage, thread: EnvironmentThreadShell) => { - const hasAccess = () => - readEnvironmentScope(queuedMessage.environmentId, AuthOrchestrationOperateScope); - if (!hasAccess()) return true; - const serverConfig = appAtomRegistry.get( - serverEnvironment.configValueAtom(queuedMessage.environmentId), - ); - if (!serverConfig) return false; - const settings = resolveQueuedThreadSettings(queuedMessage, thread, serverConfig.providers); - if (isModelSelectionUnavailable(serverConfig, settings.modelSelection, thread.projectId)) { - const { title, detail } = describeUnavailableModelSelection( - serverConfig, - settings.modelSelection, - thread.projectId, - ); - return restoreQueuedMessage(queuedMessage, `${title}. ${detail}`); - } - const { reportFailure } = makeDeliveryHelpers(queuedMessage); + const retryNotBefore = (messageId: MessageId): number => retries.get(messageId)?.notBefore ?? 0; - if (settings.runtimeMode !== thread.runtimeMode) { - if (!hasAccess()) return true; - const runtimeResult = await setThreadRuntimeMode({ - environmentId: queuedMessage.environmentId, - input: { - commandId: settingsCommandId(queuedMessage, "runtime-mode"), - threadId: queuedMessage.threadId, - runtimeMode: settings.runtimeMode, - createdAt: queuedMessage.createdAt, - }, - }); - if (AsyncResult.isFailure(runtimeResult)) { - reportFailure(runtimeResult, "settings-sync"); - return false; - } - } + const scheduleRetry = (messageId: MessageId): void => { + if (disposed) return; + const previous = retries.get(messageId); + if (previous !== undefined) clearTimeout(previous.timer); + const attempt = (previous?.attempt ?? 0) + 1; + const delayMs = threadOutboxRetryDelayMs(attempt); + retries.set(messageId, { + attempt, + notBefore: Date.now() + delayMs, + timer: setTimeout(drain, delayMs), + }); + }; - if (settings.interactionMode !== thread.interactionMode) { - if (!hasAccess()) return true; - const interactionResult = await setThreadInteractionMode({ - environmentId: queuedMessage.environmentId, - input: { - commandId: settingsCommandId(queuedMessage, "interaction-mode"), - threadId: queuedMessage.threadId, - interactionMode: settings.interactionMode, - createdAt: queuedMessage.createdAt, - }, - }); - if (AsyncResult.isFailure(interactionResult)) { - reportFailure(interactionResult, "settings-sync"); - return false; - } - } + const clearRetry = (messageId: MessageId): void => { + const retry = retries.get(messageId); + if (retry === undefined) return; + clearTimeout(retry.timer); + retries.delete(messageId); + }; - let prepared: PreparedTurnAttachments; - let persistedMessage: QueuedThreadMessage; - let deliveryRevision: number; - if (!hasAccess()) return true; - try { - const preparedResult = await prepareQueuedMessageAttachments( - queuedMessage, - serverConfig.environment.capabilities.attachmentUploads === true, - ); - if (preparedResult.status === "abandoned") { - return true; - } - prepared = preparedResult.prepared; - persistedMessage = preparedResult.persistedMessage; - deliveryRevision = preparedResult.deliveryRevision; - if (appAtomRegistry.get(editingQueuedMessageIdsAtom)[queuedMessage.messageId]) { - await preserveUploadedAttachmentsForEditor( - queuedMessage, - preparedResult.persistedMessage, - ); - return true; - } - } catch (error) { - if (!hasAccess()) return true; - logThreadOutboxUploadFailure(queuedMessage, error); - if (!shouldRetryThreadOutboxDelivery(error)) { - return restoreQueuedMessage( - queuedMessage, - error instanceof Error ? error.message : "An attachment could not upload.", - ); - } - return false; - } - if (!isQueuedMessagePayloadCurrent(persistedMessage, deliveryRevision)) { - return true; + // A delivery that throws backs off like any failure. Releasing the slot + // without a retry would re-run the drain straight into the same message. + const settle = (messageId: MessageId, delivery: Promise): void => { + void delivery + .then( + (sent) => (sent ? clearRetry(messageId) : scheduleRetry(messageId)), + (error: unknown) => { + console.warn("[thread-outbox] queued message delivery threw", { messageId, error }); + scheduleRetry(messageId); + }, + ) + .finally(() => finishDispatchingQueuedMessage(messageId)); + }; + + // An over-cap draft blocks recovery until the user changes its attachments; + // parking on the draft avoids hammering the restore with backoff retries. + const restoreQueuedMessage = async ( + queuedMessage: QueuedThreadMessage, + message: string, + ): Promise => { + const result = await restoreRejectedQueuedMessage(queuedMessage, message); + if (result !== "blocked") { + return result !== "retry"; + } + if (disposed || blockedRecoveries.has(queuedMessage.messageId)) { + return true; + } + const draftKey = recoveryDraftKey(queuedMessage); + const editorDraftKey = queuedMessage.creation + ? `pending-task:${queuedMessage.messageId}` + : null; + const currentDrafts = appAtomRegistry.get(composerDraftsAtom); + const blockedAttachments = currentDrafts[draftKey]?.attachments; + const editorAttachments = + editorDraftKey === null ? undefined : currentDrafts[editorDraftKey]?.attachments; + const unsubscribe = appAtomRegistry.subscribe(composerDraftsAtom, (drafts) => { + if ( + drafts[draftKey]?.attachments === blockedAttachments && + (editorDraftKey === null || drafts[editorDraftKey]?.attachments === editorAttachments) + ) { + return; } - const currentConfig = appAtomRegistry.get( - serverEnvironment.configValueAtom(queuedMessage.environmentId), - ); - if (!currentConfig) return false; - if (isModelSelectionUnavailable(currentConfig, settings.modelSelection, thread.projectId)) { - const { title, detail } = describeUnavailableModelSelection( - currentConfig, - settings.modelSelection, - thread.projectId, - ); - return restoreQueuedMessage(persistedMessage, `${title}. ${detail}`); + const active = blockedRecoveries.get(queuedMessage.messageId); + if (!active) { + return; } - const sendSettings = resolveQueuedThreadSettings( - queuedMessage, - settings, - currentConfig.providers, + blockedRecoveries.delete(queuedMessage.messageId); + active.unsubscribe(); + drain(); + }); + blockedRecoveries.set(queuedMessage.messageId, { message: queuedMessage, unsubscribe }); + return true; + }; + + const sendQueuedMessage = async ( + queuedMessage: QueuedThreadMessage, + thread: EnvironmentThreadShell, + ): Promise => { + const hasAccess = () => + readEnvironmentScope(queuedMessage.environmentId, AuthOrchestrationOperateScope); + if (!hasAccess()) return true; + const serverConfig = appAtomRegistry.get( + serverEnvironment.configValueAtom(queuedMessage.environmentId), + ); + if (!serverConfig) return false; + const settings = resolveQueuedThreadSettings(queuedMessage, thread, serverConfig.providers); + if (isModelSelectionUnavailable(serverConfig, settings.modelSelection, thread.projectId)) { + const { title, detail } = describeUnavailableModelSelection( + serverConfig, + settings.modelSelection, + thread.projectId, ); + return restoreQueuedMessage(queuedMessage, `${title}. ${detail}`); + } + + if (settings.runtimeMode !== thread.runtimeMode) { if (!hasAccess()) return true; - const deliveryResult = await startTurn({ + const runtimeResult = await runDeliveryCommand(threadEnvironment.setRuntimeMode, { environmentId: queuedMessage.environmentId, input: { - commandId: queuedMessage.commandId, - creationSource: "mobile", + commandId: settingsCommandId(queuedMessage, "runtime-mode"), threadId: queuedMessage.threadId, - message: { - messageId: queuedMessage.messageId, - role: "user", - ...serializeComposerMessageForServer( - queuedMessage.text, - uploadedComposerContext( - queuedMessage.context, - queuedMessage.attachments, - prepared.attachments, - ), - currentConfig.environment.capabilities.inlineMessageContext === true, - ), - attachments: prepared.attachments, - }, - modelSelection: sendSettings.modelSelection, - titleSeed: deriveThreadTitleSeed({ - text: queuedMessage.text, - attachments: queuedMessage.attachments, - }), - runtimeMode: sendSettings.runtimeMode, - interactionMode: sendSettings.interactionMode, + runtimeMode: settings.runtimeMode, createdAt: queuedMessage.createdAt, - dispatchMode: queuedMessage.dispatchMode ?? "start", }, }); - if (AsyncResult.isFailure(deliveryResult) && !hasAccess()) return true; - const failure = reportFailure(deliveryResult, "start-turn"); - if (failure?.action === "retry") { + if (AsyncResult.isFailure(runtimeResult)) { + reportCommandFailure(queuedMessage, runtimeResult, "settings-sync"); return false; } - if (failure?.action === "restore") { - return restoreQueuedMessage(persistedMessage, failure.message); - } - acknowledgedExistingThreadMessageIdsRef.current.add(persistedMessage.messageId); - const delivered = - (await completeQueuedMessageDelivery(persistedMessage, deliveryRevision)) === "removed"; - if (delivered) { - acknowledgedExistingThreadMessageIdsRef.current.delete(persistedMessage.messageId); - } - return delivered; - }, - [ - makeDeliveryHelpers, - setThreadInteractionMode, - setThreadRuntimeMode, - startTurn, - restoreQueuedMessage, - ], - ); + } - const sendQueuedCreation = useCallback( - async ( - queuedMessage: QueuedThreadMessage, - creation: QueuedThreadCreation, - projectCwd: string, - ) => { - const hasAccess = () => - readEnvironmentScope(queuedMessage.environmentId, AuthOrchestrationOperateScope); + if (settings.interactionMode !== thread.interactionMode) { if (!hasAccess()) return true; - const modelSelection = queuedMessage.modelSelection; - if (modelSelection === undefined) { + const interactionResult = await runDeliveryCommand(threadEnvironment.setInteractionMode, { + environmentId: queuedMessage.environmentId, + input: { + commandId: settingsCommandId(queuedMessage, "interaction-mode"), + threadId: queuedMessage.threadId, + interactionMode: settings.interactionMode, + createdAt: queuedMessage.createdAt, + }, + }); + if (AsyncResult.isFailure(interactionResult)) { + reportCommandFailure(queuedMessage, interactionResult, "settings-sync"); return false; } - const serverConfig = appAtomRegistry.get( - serverEnvironment.configValueAtom(queuedMessage.environmentId), - ); - if (!serverConfig) return false; - const settings = resolveQueuedThreadSettings( + } + + let prepared: PreparedTurnAttachments; + let persistedMessage: QueuedThreadMessage; + let deliveryRevision: number; + if (!hasAccess()) return true; + try { + const preparedResult = await prepareQueuedMessageAttachments( queuedMessage, - { - modelSelection, - runtimeMode: DEFAULT_RUNTIME_MODE, - interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE, - }, - serverConfig.providers, + serverConfig.environment.capabilities.attachmentUploads === true, ); - if (isModelSelectionUnavailable(serverConfig, settings.modelSelection, creation.projectId)) { - const { title, detail } = describeUnavailableModelSelection( - serverConfig, - settings.modelSelection, - creation.projectId, - ); - return restoreQueuedMessage(queuedMessage, `${title}. ${detail}`); - } - let prepared: PreparedTurnAttachments; - let persistedMessage: QueuedThreadMessage; - let deliveryRevision: number; - try { - const preparedResult = await prepareQueuedMessageAttachments( - queuedMessage, - serverConfig.environment.capabilities.attachmentUploads === true, - ); - if (preparedResult.status === "abandoned") { - return true; - } - prepared = preparedResult.prepared; - persistedMessage = preparedResult.persistedMessage; - deliveryRevision = preparedResult.deliveryRevision; - if (appAtomRegistry.get(editingQueuedMessageIdsAtom)[queuedMessage.messageId]) { - await preserveUploadedAttachmentsForEditor( - queuedMessage, - preparedResult.persistedMessage, - ); - return true; - } - } catch (error) { - if (!hasAccess()) return true; - logThreadOutboxUploadFailure(queuedMessage, error); - if (!shouldRetryThreadOutboxDelivery(error)) { - return restoreQueuedMessage( - queuedMessage, - error instanceof Error ? error.message : "An attachment could not upload.", - ); - } - return false; + if (preparedResult.status === "abandoned") { + return true; } - if (!isQueuedMessagePayloadCurrent(persistedMessage, deliveryRevision)) { + prepared = preparedResult.prepared; + persistedMessage = preparedResult.persistedMessage; + deliveryRevision = preparedResult.deliveryRevision; + if (appAtomRegistry.get(editingQueuedMessageIdsAtom)[queuedMessage.messageId]) { + await preserveUploadedAttachmentsForEditor(queuedMessage, preparedResult.persistedMessage); return true; } - const currentConfig = appAtomRegistry.get( - serverEnvironment.configValueAtom(queuedMessage.environmentId), - ); - if (!currentConfig) return false; - if (isModelSelectionUnavailable(currentConfig, settings.modelSelection, creation.projectId)) { - const { title, detail } = describeUnavailableModelSelection( - currentConfig, - settings.modelSelection, - creation.projectId, + } catch (error) { + if (!hasAccess()) return true; + logThreadOutboxUploadFailure(queuedMessage, error); + if (!shouldRetryThreadOutboxDelivery(error)) { + return restoreQueuedMessage( + queuedMessage, + error instanceof Error ? error.message : "An attachment could not upload.", ); - return restoreQueuedMessage(persistedMessage, `${title}. ${detail}`); } - const sendSettings = resolveQueuedThreadSettings( - queuedMessage, - settings, - currentConfig.providers, + return false; + } + if (!isQueuedMessagePayloadCurrent(persistedMessage, deliveryRevision)) { + return true; + } + const currentConfig = appAtomRegistry.get( + serverEnvironment.configValueAtom(queuedMessage.environmentId), + ); + if (!currentConfig) return false; + if (isModelSelectionUnavailable(currentConfig, settings.modelSelection, thread.projectId)) { + const { title, detail } = describeUnavailableModelSelection( + currentConfig, + settings.modelSelection, + thread.projectId, ); - if (!hasAccess()) return true; - const { reportFailure } = makeDeliveryHelpers(queuedMessage); - let workspace = creation; - if (creation.pullRequestReference) { - const checkout = await preparePullRequest({ - environmentId: queuedMessage.environmentId, - input: { cwd: projectCwd, reference: creation.pullRequestReference, mode: "worktree" }, - }); - if (!isQueuedMessagePayloadCurrent(persistedMessage, deliveryRevision) || !hasAccess()) - return true; - const failure = reportFailure(checkout, "start-turn"); - if (failure?.action === "retry") return false; - if (failure?.action === "restore") - return restoreQueuedMessage(persistedMessage, failure.message); - if (!AsyncResult.isSuccess(checkout)) return false; - if (!checkout.value.worktreePath || !checkout.value.isOnPullRequestHead) { - const { shortLabel } = ( - sourceControlClients.findByChangeRequestUrl(creation.pullRequestReference) ?? - sourceControlClients.get(undefined) - ).changeRequest; - return restoreQueuedMessage( - persistedMessage, - `The ${shortLabel} worktree has local changes and could not update to the ${shortLabel} head. Resolve them before trying again.`, - ); - } - workspace = { - ...creation, - workspaceMode: "local", - branch: checkout.value.branch, - worktreePath: checkout.value.worktreePath, - startFromOrigin: false, - }; - } - const deliveryResult = await startTurn({ - environmentId: queuedMessage.environmentId, - input: buildProjectThreadStartTurnInput({ - projectId: creation.projectId, - projectCwd, - threadId: queuedMessage.threadId, - commandId: queuedMessage.commandId, + return restoreQueuedMessage(persistedMessage, `${title}. ${detail}`); + } + const sendSettings = resolveQueuedThreadSettings( + queuedMessage, + settings, + currentConfig.providers, + ); + if (!hasAccess()) return true; + const deliveryResult = await runDeliveryCommand(threadEnvironment.startTurn, { + environmentId: queuedMessage.environmentId, + input: { + commandId: queuedMessage.commandId, + creationSource: "mobile", + threadId: queuedMessage.threadId, + message: { messageId: queuedMessage.messageId, - createdAt: queuedMessage.createdAt, - titleText: queuedMessage.text, + role: "user", ...serializeComposerMessageForServer( - queuedMessage.text.trim(), + queuedMessage.text, uploadedComposerContext( queuedMessage.context, queuedMessage.attachments, @@ -1031,58 +881,235 @@ export function useThreadOutboxDrain(): void { ), currentConfig.environment.capabilities.inlineMessageContext === true, ), - uploadedAttachments: prepared.attachments, - modelSelection: sendSettings.modelSelection, - runtimeMode: sendSettings.runtimeMode, - interactionMode: sendSettings.interactionMode, - workspaceMode: workspace.workspaceMode, - branch: workspace.branch, - worktreePath: workspace.worktreePath, - startFromOrigin: workspace.startFromOrigin ?? false, - worktreeBranchName: buildTemporaryWorktreeBranchName(randomHex), + attachments: prepared.attachments, + }, + modelSelection: sendSettings.modelSelection, + titleSeed: deriveThreadTitleSeed({ + text: queuedMessage.text, + attachments: queuedMessage.attachments, }), - }); - if (AsyncResult.isFailure(deliveryResult) && !hasAccess()) return true; - const failure = reportFailure(deliveryResult, "start-turn"); - if (failure?.action === "retry") { - return false; + runtimeMode: sendSettings.runtimeMode, + interactionMode: sendSettings.interactionMode, + createdAt: queuedMessage.createdAt, + dispatchMode: queuedMessage.dispatchMode ?? "start", + }, + }); + if (AsyncResult.isFailure(deliveryResult) && !hasAccess()) return true; + const failure = reportCommandFailure(queuedMessage, deliveryResult, "start-turn"); + if (failure?.action === "retry") { + return false; + } + if (failure?.action === "restore") { + return restoreQueuedMessage(persistedMessage, failure.message); + } + acknowledgedExistingThreadMessageIds.add(persistedMessage.messageId); + const delivered = + (await completeQueuedMessageDelivery(persistedMessage, deliveryRevision)) === "removed"; + if (delivered) { + acknowledgedExistingThreadMessageIds.delete(persistedMessage.messageId); + } + return delivered; + }; + + const sendQueuedCreation = async ( + queuedMessage: QueuedThreadMessage, + creation: QueuedThreadCreation, + projectCwd: string, + ): Promise => { + const hasAccess = () => + readEnvironmentScope(queuedMessage.environmentId, AuthOrchestrationOperateScope); + if (!hasAccess()) return true; + const modelSelection = queuedMessage.modelSelection; + if (modelSelection === undefined) { + return false; + } + const serverConfig = appAtomRegistry.get( + serverEnvironment.configValueAtom(queuedMessage.environmentId), + ); + if (!serverConfig) return false; + const settings = resolveQueuedThreadSettings( + queuedMessage, + { + modelSelection, + runtimeMode: DEFAULT_RUNTIME_MODE, + interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE, + }, + serverConfig.providers, + ); + if (isModelSelectionUnavailable(serverConfig, settings.modelSelection, creation.projectId)) { + const { title, detail } = describeUnavailableModelSelection( + serverConfig, + settings.modelSelection, + creation.projectId, + ); + return restoreQueuedMessage(queuedMessage, `${title}. ${detail}`); + } + let prepared: PreparedTurnAttachments; + let persistedMessage: QueuedThreadMessage; + let deliveryRevision: number; + try { + const preparedResult = await prepareQueuedMessageAttachments( + queuedMessage, + serverConfig.environment.capabilities.attachmentUploads === true, + ); + if (preparedResult.status === "abandoned") { + return true; } - if (failure?.action === "restore") { + prepared = preparedResult.prepared; + persistedMessage = preparedResult.persistedMessage; + deliveryRevision = preparedResult.deliveryRevision; + if (appAtomRegistry.get(editingQueuedMessageIdsAtom)[queuedMessage.messageId]) { + await preserveUploadedAttachmentsForEditor(queuedMessage, preparedResult.persistedMessage); + return true; + } + } catch (error) { + if (!hasAccess()) return true; + logThreadOutboxUploadFailure(queuedMessage, error); + if (!shouldRetryThreadOutboxDelivery(error)) { + return restoreQueuedMessage( + queuedMessage, + error instanceof Error ? error.message : "An attachment could not upload.", + ); + } + return false; + } + if (!isQueuedMessagePayloadCurrent(persistedMessage, deliveryRevision)) { + return true; + } + const currentConfig = appAtomRegistry.get( + serverEnvironment.configValueAtom(queuedMessage.environmentId), + ); + if (!currentConfig) return false; + if (isModelSelectionUnavailable(currentConfig, settings.modelSelection, creation.projectId)) { + const { title, detail } = describeUnavailableModelSelection( + currentConfig, + settings.modelSelection, + creation.projectId, + ); + return restoreQueuedMessage(persistedMessage, `${title}. ${detail}`); + } + const sendSettings = resolveQueuedThreadSettings( + queuedMessage, + settings, + currentConfig.providers, + ); + if (!hasAccess()) return true; + let workspace = creation; + if (creation.pullRequestReference) { + const checkout = await runDeliveryCommand(gitEnvironment.preparePullRequestThread, { + environmentId: queuedMessage.environmentId, + input: { cwd: projectCwd, reference: creation.pullRequestReference, mode: "worktree" }, + }); + if (!isQueuedMessagePayloadCurrent(persistedMessage, deliveryRevision) || !hasAccess()) + return true; + const failure = reportCommandFailure(queuedMessage, checkout, "start-turn"); + if (failure?.action === "retry") return false; + if (failure?.action === "restore") return restoreQueuedMessage(persistedMessage, failure.message); + if (!AsyncResult.isSuccess(checkout)) return false; + if (!checkout.value.worktreePath || !checkout.value.isOnPullRequestHead) { + const { shortLabel } = ( + sourceControlClients.findByChangeRequestUrl(creation.pullRequestReference) ?? + sourceControlClients.get(undefined) + ).changeRequest; + return restoreQueuedMessage( + persistedMessage, + `The ${shortLabel} worktree has local changes and could not update to the ${shortLabel} head. Resolve them before trying again.`, + ); } - recordPendingThreadCreationOutcome({ kind: "delivered", message: persistedMessage }); - const outcome = await completeQueuedMessageDelivery(persistedMessage, deliveryRevision); - if (outcome === "edited") { - if (appAtomRegistry.get(editingQueuedMessageIdsAtom)[queuedMessage.messageId]) { - return true; - } - return recoverEditedCreationAfterDelivery(persistedMessage); + workspace = { + ...creation, + workspaceMode: "local", + branch: checkout.value.branch, + worktreePath: checkout.value.worktreePath, + startFromOrigin: false, + }; + } + const deliveryResult = await runDeliveryCommand(threadEnvironment.startTurn, { + environmentId: queuedMessage.environmentId, + input: buildProjectThreadStartTurnInput({ + projectId: creation.projectId, + projectCwd, + threadId: queuedMessage.threadId, + commandId: queuedMessage.commandId, + messageId: queuedMessage.messageId, + createdAt: queuedMessage.createdAt, + titleText: queuedMessage.text, + ...serializeComposerMessageForServer( + queuedMessage.text.trim(), + uploadedComposerContext( + queuedMessage.context, + queuedMessage.attachments, + prepared.attachments, + ), + currentConfig.environment.capabilities.inlineMessageContext === true, + ), + uploadedAttachments: prepared.attachments, + modelSelection: sendSettings.modelSelection, + runtimeMode: sendSettings.runtimeMode, + interactionMode: sendSettings.interactionMode, + workspaceMode: workspace.workspaceMode, + branch: workspace.branch, + worktreePath: workspace.worktreePath, + startFromOrigin: workspace.startFromOrigin ?? false, + worktreeBranchName: buildTemporaryWorktreeBranchName(randomHex), + }), + }); + if (AsyncResult.isFailure(deliveryResult) && !hasAccess()) return true; + const failure = reportCommandFailure(queuedMessage, deliveryResult, "start-turn"); + if (failure?.action === "retry") { + return false; + } + if (failure?.action === "restore") { + return restoreQueuedMessage(persistedMessage, failure.message); + } + recordPendingThreadCreationOutcome({ kind: "delivered", message: persistedMessage }); + const outcome = await completeQueuedMessageDelivery(persistedMessage, deliveryRevision); + if (outcome === "edited") { + if (appAtomRegistry.get(editingQueuedMessageIdsAtom)[queuedMessage.messageId]) { + return true; } - return outcome === "removed"; - }, - [makeDeliveryHelpers, preparePullRequest, restoreQueuedMessage, startTurn], - ); + return recoverEditedCreationAfterDelivery(persistedMessage); + } + return outcome === "removed"; + }; - // Subscribe to outcomes; they may arrive after the last shell update, leaving read-once entries uncollected. - useEffect(() => { - for (const [threadKey, outcome] of Object.entries(creationOutcomes)) { - if ( - outcome.kind === "delivered" && - threads.some( - (thread) => - scopedThreadKey(thread.environmentId, thread.id) === threadKey && - (thread.latestRun !== null || - thread.runtime?.status === "failed" || - thread.runtime?.status === "cancelled" || - thread.runtime?.status === "interrupted"), - ) - ) { - clearPendingThreadCreationOutcome(threadKey); - } + // A pass writes atoms the pass reads (family mounts, the dispatch slot), and the registry + // notifies subscribers synchronously, so drain() can be called from inside a pass. That call + // only asks for another pass; a nested pass would decide from inputs the outer one is still + // acting on and could start a second delivery. + let draining = false; + let drainRequested = false; + function drain(): void { + if (disposed) return; + if (draining) { + drainRequested = true; + return; + } + draining = true; + try { + do { + if (disposed) return; + drainRequested = false; + drainPass(); + } while (drainRequested); + } finally { + draining = false; } - }, [creationOutcomes, threads]); + } - useEffect(() => { + function drainPass(): void { + const { + dispatchingQueuedMessageId, + editingQueuedMessageIds, + queuedMessagesByThreadKey, + shellStatuses, + threads, + projects, + serverConfigs, + connectedEnvironments, + operableEnvironments, + } = appAtomRegistry.get(deliveryInputsAtom); if (dispatchingQueuedMessageId !== null) { return; } @@ -1092,15 +1119,15 @@ export function useThreadOutboxDrain(): void { .flat() .map((message) => message.messageId), ); - for (const messageId of acknowledgedExistingThreadMessageIdsRef.current) { + for (const messageId of acknowledgedExistingThreadMessageIds) { if (!queuedMessageIds.has(messageId)) { - acknowledgedExistingThreadMessageIdsRef.current.delete(messageId); + acknowledgedExistingThreadMessageIds.delete(messageId); } } - for (const [messageId, release] of familyMountsRef.current) { + for (const [messageId, release] of familyMounts) { if (!queuedMessageIds.has(messageId)) { release(); - familyMountsRef.current.delete(messageId); + familyMounts.delete(messageId); } } @@ -1109,48 +1136,36 @@ export function useThreadOutboxDrain(): void { if (!nextQueuedMessage) { continue; } + const messageId = nextQueuedMessage.messageId; if ( nextQueuedMessage.creation === undefined && - acknowledgedExistingThreadMessageIdsRef.current.has(nextQueuedMessage.messageId) + acknowledgedExistingThreadMessageIds.has(messageId) ) { - if ((retryNotBeforeRef.current.get(nextQueuedMessage.messageId) ?? 0) > Date.now()) { + if (retryNotBefore(messageId) > Date.now()) { continue; } - beginDispatchingQueuedMessage(nextQueuedMessage.messageId); - void removeAcknowledgedExistingThreadMessage( - nextQueuedMessage, - acknowledgedExistingThreadMessageIdsRef.current, - ) - .then((removed) => { - if (!removed) { - scheduleQueuedMessageRetry(nextQueuedMessage.messageId); - return; - } - retryAttemptRef.current.delete(nextQueuedMessage.messageId); - retryNotBeforeRef.current.delete(nextQueuedMessage.messageId); - const pendingTimer = retryTimersRef.current.get(nextQueuedMessage.messageId); - if (pendingTimer !== undefined) { - clearTimeout(pendingTimer); - retryTimersRef.current.delete(nextQueuedMessage.messageId); - } - }) - .finally(() => finishDispatchingQueuedMessage(nextQueuedMessage.messageId)); + beginDispatchingQueuedMessage(messageId); + settle( + messageId, + removeAcknowledgedExistingThreadMessage( + nextQueuedMessage, + acknowledgedExistingThreadMessageIds, + ), + ); return; } - if (editingQueuedMessageIds[nextQueuedMessage.messageId]) { + if (editingQueuedMessageIds[messageId]) { continue; } - const blockedRecovery = blockedRecoverySubscriptionsRef.current.get( - nextQueuedMessage.messageId, - ); + const blockedRecovery = blockedRecoveries.get(messageId); if (blockedRecovery) { if (blockedRecovery.message === nextQueuedMessage) { continue; } - blockedRecoverySubscriptionsRef.current.delete(nextQueuedMessage.messageId); + blockedRecoveries.delete(messageId); blockedRecovery.unsubscribe(); } - if ((retryNotBeforeRef.current.get(nextQueuedMessage.messageId) ?? 0) > Date.now()) { + if (retryNotBefore(messageId) > Date.now()) { continue; } @@ -1173,8 +1188,8 @@ export function useThreadOutboxDrain(): void { ) { // The family keeps the row readable through dispatch once it loads; the current shell // generation's read decides whether the thread is gone. - if (!familyMountsRef.current.has(nextQueuedMessage.messageId)) { - familyMountsRef.current.set( + if (!familyMounts.has(nextQueuedMessage.messageId)) { + familyMounts.set( nextQueuedMessage.messageId, threadFamilies.mount( appAtomRegistry, @@ -1189,8 +1204,8 @@ export function useThreadOutboxDrain(): void { ), ); if (familyRead === "settled") { - // The rows from this render can lag the family that just settled; decide from the - // merged rows as they are now. + // The rows read at the start of this pass can lag the family that just settled; + // decide from the merged rows as they are now. thread = findThread( appAtomRegistry.get(environmentThreadShells.threadShellsAtom), nextQueuedMessage, @@ -1218,7 +1233,7 @@ export function useThreadOutboxDrain(): void { familyRead !== "settled" ) { // An empty family read changes no merged row, so nothing else would wake the drain. - scheduleQueuedMessageRetry(nextQueuedMessage.messageId); + scheduleRetry(messageId); continue; } if (deliveryAction === "send" && !operableEnvironments.has(nextQueuedMessage.environmentId)) { @@ -1240,28 +1255,20 @@ export function useThreadOutboxDrain(): void { continue; } if (dispatchStep.step === "retry") { - scheduleQueuedMessageRetry(nextQueuedMessage.messageId); + scheduleRetry(messageId); continue; } if (dispatchStep.step === "restore") { const attachmentError = dispatchStep.reason; - beginDispatchingQueuedMessage(nextQueuedMessage.messageId); - void confirmThreadOutboxMessageQueued(nextQueuedMessage) - .then((queued) => { - if ( - !queued || - appAtomRegistry.get(editingQueuedMessageIdsAtom)[nextQueuedMessage.messageId] - ) { - return true; - } - return restoreQueuedMessage(nextQueuedMessage, attachmentError); - }) - .then((restored) => { - if (!restored) { - scheduleQueuedMessageRetry(nextQueuedMessage.messageId); - } - }) - .finally(() => finishDispatchingQueuedMessage(nextQueuedMessage.messageId)); + beginDispatchingQueuedMessage(messageId); + settle( + messageId, + confirmThreadOutboxMessageQueued(nextQueuedMessage).then((queued) => + !queued || appAtomRegistry.get(editingQueuedMessageIdsAtom)[messageId] + ? true + : restoreQueuedMessage(nextQueuedMessage, attachmentError), + ), + ); return; } const creationProjectCwd = @@ -1279,7 +1286,7 @@ export function useThreadOutboxDrain(): void { } } - beginDispatchingQueuedMessage(nextQueuedMessage.messageId); + beginDispatchingQueuedMessage(messageId); const removeQueuedMessage = (warning: string) => removeThreadOutboxMessage(nextQueuedMessage).then( () => true, @@ -1287,7 +1294,7 @@ export function useThreadOutboxDrain(): void { console.warn(warning, { environmentId: nextQueuedMessage.environmentId, threadId: nextQueuedMessage.threadId, - messageId: nextQueuedMessage.messageId, + messageId, error, }); return false; @@ -1299,7 +1306,7 @@ export function useThreadOutboxDrain(): void { return true; } // Re-check editor ownership after confirmation; return true to defer without failure backoff. - if (appAtomRegistry.get(editingQueuedMessageIdsAtom)[nextQueuedMessage.messageId]) { + if (appAtomRegistry.get(editingQueuedMessageIdsAtom)[messageId]) { return true; } if (deliveryAction === "send") { @@ -1307,13 +1314,12 @@ export function useThreadOutboxDrain(): void { appAtomRegistry.get(environmentThreadShells.threadShellsAtom), nextQueuedMessage, ); - const liveThreadBusy = threadRuntimeIsActive(liveThread?.runtime); const liveDeliveryAction = resolveThreadOutboxDeliveryAction({ isCreation: creation !== undefined, threadExists: liveThread !== undefined, shellStatus, environmentConnected: environment?.connectionState === "connected", - threadBusy: liveThreadBusy, + threadBusy: threadRuntimeIsActive(liveThread?.runtime), }); if (liveDeliveryAction !== "send") { return true; @@ -1332,41 +1338,57 @@ export function useThreadOutboxDrain(): void { ? sendQueuedMessage(nextQueuedMessage, thread) : Promise.resolve(false); }); - void delivery - .then((sent) => { - if (sent) { - retryAttemptRef.current.delete(nextQueuedMessage.messageId); - retryNotBeforeRef.current.delete(nextQueuedMessage.messageId); - const pendingTimer = retryTimersRef.current.get(nextQueuedMessage.messageId); - if (pendingTimer !== undefined) { - clearTimeout(pendingTimer); - retryTimersRef.current.delete(nextQueuedMessage.messageId); - } - return; - } - - scheduleQueuedMessageRetry(nextQueuedMessage.messageId); - }) - .finally(() => { - finishDispatchingQueuedMessage(nextQueuedMessage.messageId); - }); + settle(messageId, delivery); return; } - }, [ - connectedEnvironments, - dispatchingQueuedMessageId, - editingQueuedMessageIds, - operableEnvironments, - projects, - queuedMessagesByThreadKey, - // oxlint-disable-next-line react/exhaustive-effect-dependencies -- retryTick re-runs the drain when a retry timer fires. - retryTick, - restoreQueuedMessage, - scheduleQueuedMessageRetry, - sendQueuedCreation, - sendQueuedMessage, - serverConfigs, - shellStatuses, - threads, - ]); + } + + const stopDraining = appAtomRegistry.subscribe(deliveryInputsAtom, drain, { immediate: true }); + const stopCollectingOutcomes = appAtomRegistry.subscribe( + settledCreationOutcomeKeysAtom, + (threadKeys) => { + for (const threadKey of threadKeys) clearPendingThreadCreationOutcome(threadKey); + }, + { immediate: true }, + ); + + return { + drain, + dispose: () => { + disposed = true; + stopDraining(); + stopCollectingOutcomes(); + for (const retry of retries.values()) clearTimeout(retry.timer); + retries.clear(); + for (const blocked of blockedRecoveries.values()) blocked.unsubscribe(); + blockedRecoveries.clear(); + for (const release of familyMounts.values()) release(); + familyMounts.clear(); + }, + }; +} + +function loadThreadOutbox(isActive: () => boolean): void { + void threadOutboxManager.load().then((loaded) => { + if (loaded || !isActive()) return; + Dialog.alert( + "Some queued messages could not be loaded", + "Unreadable records and attachment files are still saved. Other messages can still be sent.", + [ + { text: "Dismiss", style: "cancel" }, + { text: "Retry", onPress: () => loadThreadOutbox(isActive) }, + ], + ); + }); +} + +/** App-lifetime: loads the persisted outbox and delivers queued messages. */ +export function installThreadOutboxDelivery(): () => void { + let active = true; + loadThreadOutbox(() => active); + const delivery = createThreadOutboxDelivery(); + return () => { + active = false; + delivery.dispose(); + }; } diff --git a/apps/mobile/src/state/use-thread-outbox.ts b/apps/mobile/src/state/use-thread-outbox.ts index 8339472a99617..a1128cbd08b30 100644 --- a/apps/mobile/src/state/use-thread-outbox.ts +++ b/apps/mobile/src/state/use-thread-outbox.ts @@ -7,7 +7,7 @@ import { appAtomRegistry } from "./atom-registry"; import { environmentShell } from "./shell"; import { threadOutboxManager } from "./thread-outbox"; -const threadOutboxShellStatusesAtom = Atom.make( +export const threadOutboxShellStatusesAtom = Atom.make( (get): ReadonlyMap => { const statuses = new Map(); for (const queue of Object.values(get(threadOutboxManager.queuedMessagesByThreadKeyAtom))) { @@ -68,7 +68,3 @@ export const queuedThreadKeysAtom = Atom.make((get): ReadonlySet => { export function useQueuedThreadKeys(): ReadonlySet { return useAtomValue(queuedThreadKeysAtom); } - -export function useThreadOutboxShellStatuses() { - return useAtomValue(threadOutboxShellStatusesAtom); -} diff --git a/apps/web/src/appInit.tsx b/apps/web/src/appInit.tsx index fe0cc4ceda4cb..0be6d822c86a6 100644 --- a/apps/web/src/appInit.tsx +++ b/apps/web/src/appInit.tsx @@ -23,7 +23,7 @@ import { startGuideRunNotifications } from "./components/pullRequest/guide/PullR import { APP_BASE_NAME, APP_DISPLAY_NAME, APP_STAGE_LABEL } from "./branding"; import { resolveServerBackedAppDisplayName } from "./branding.logic"; import { isElectron } from "./env"; -import { useComposerDraftStore } from "./composerDraftStore"; +import { subscribeDraftThreadPromotion, useComposerDraftStore } from "./composerDraftStore"; import { startDefaultThemeAdoption } from "./hooks/useDefaultTheme"; import { startEnvironmentThemeRepaint } from "./hooks/useEnvironmentTheme"; import { @@ -44,6 +44,7 @@ import { appAtomRegistry } from "./rpc/atomRegistry"; import { primaryServerConfigAtom } from "./state/server"; import { installChatRouteCommands } from "./shortcuts/chatRouteCommands"; import { registerOpenFavoriteEditorCommand } from "./components/chat/OpenInPickerShortcut"; +import { environmentThreadShells } from "./state/threads"; import { resolveThreadRouteTarget } from "./threadRoutes"; /** Writes appearance settings onto the document, touching only the groups that changed. */ @@ -173,6 +174,12 @@ export function startAppServices(): AppRouter { installChatRouteCommands(router); registerOpenFavoriteEditorCommand(); startThreadOverlayRetention(router); + // Drafts promote as their server threads arrive, wherever the user is. + subscribeDraftThreadPromotion({ + registry: appAtomRegistry, + threadShellAtom: environmentThreadShells.quietThreadShellAtom, + threadRefsAtom: environmentThreadShells.threadRefsAtom, + }); startMainAppLocationTracking(router); startBackgroundThreadAnnouncements(appAtomRegistry, router); startThreadVisitedMigration(appAtomRegistry); diff --git a/apps/web/src/components/ChatView.logic.test.ts b/apps/web/src/components/ChatView.logic.test.ts index 426818dba7a24..969a5d2e24cc5 100644 --- a/apps/web/src/components/ChatView.logic.test.ts +++ b/apps/web/src/components/ChatView.logic.test.ts @@ -52,7 +52,6 @@ import { deriveComposerSendState, deriveLockedProvider, hasServerAcknowledgedLocalDispatch, - resolveDraftPromotionNavigationTarget, waitForRevertedMessage, } from "./ChatView.logic"; @@ -105,51 +104,6 @@ const readySession = { updatedAt: "2026-03-29T00:00:10.000Z", }; -describe("resolveDraftPromotionNavigationTarget", () => { - const serverThreadRef = { environmentId, threadId }; - const preparingRun = { - ...completedTurn, - status: "preparing" as const, - startedAt: null, - completedAt: null, - }; - - it("stays on the draft until the server owns the send", () => { - expect( - resolveDraftPromotionNavigationTarget({ - serverThreadRef, - serverThread: makeThread({ latestRun: preparingRun }), - backgroundSubmissionPending: false, - }), - ).toBeNull(); - expect( - resolveDraftPromotionNavigationTarget({ - serverThreadRef, - serverThread: makeThread(), - backgroundSubmissionPending: false, - }), - ).toBeNull(); - }); - - it("promotes a persisted send while its worktree is still preparing", () => { - const serverThread = makeThread({ latestRun: preparingRun, latestUserMessageAt: now }); - expect( - resolveDraftPromotionNavigationTarget({ - serverThreadRef, - serverThread, - backgroundSubmissionPending: false, - }), - ).toBe(serverThreadRef); - expect( - resolveDraftPromotionNavigationTarget({ - serverThreadRef, - serverThread, - backgroundSubmissionPending: true, - }), - ).toBeNull(); - }); -}); - describe("deriveComposerSendState", () => { it("keeps text sendable while excluding expired terminal pills", () => { const state = deriveComposerSendState({ diff --git a/apps/web/src/components/ChatView.logic.ts b/apps/web/src/components/ChatView.logic.ts index e14d296cdd071..b3594ed28ef72 100644 --- a/apps/web/src/components/ChatView.logic.ts +++ b/apps/web/src/components/ChatView.logic.ts @@ -449,24 +449,6 @@ export function resolveThreadSwitchTimeline(input: return { entries: input.nextEntries, displayThreadKey: input.activeThreadKey }; } -export function resolveDraftPromotionNavigationTarget(input: { - serverThreadRef: ScopedThreadRef | null; - serverThread: Pick | null | undefined; - backgroundSubmissionPending: boolean; -}): ScopedThreadRef | null { - if (input.backgroundSubmissionPending) { - return null; - } - const latestRun = input.serverThread?.latestRun ?? null; - const runStarted = latestRun?.startedAt != null; - const startupStopped = - latestRun?.status === "failed" || - latestRun?.status === "interrupted" || - latestRun?.status === "cancelled"; - const messagePersisted = input.serverThread?.latestUserMessageAt != null; - return runStarted || startupStopped || messagePersisted ? input.serverThreadRef : null; -} - export function startNewThreadForProject( projectRef: ScopedProjectRef | null, handleNewThread: (projectRef: ScopedProjectRef) => Promise, @@ -948,7 +930,7 @@ export function recallCheckoutIsRepo( : sessionCheckoutIsRepo.get(checkoutIsRepoKey(environmentId, cwd)); } -export function threadHasStarted(thread: Thread | null | undefined): boolean { +function threadHasStarted(thread: Thread | null | undefined): boolean { return Boolean(thread && (thread.latestRun !== null || thread.itemCount > 0 || thread.runtime)); } diff --git a/apps/web/src/components/ChatView.tsx b/apps/web/src/components/ChatView.tsx index 6d608595848ee..8bf2ab68558ca 100644 --- a/apps/web/src/components/ChatView.tsx +++ b/apps/web/src/components/ChatView.tsx @@ -86,7 +86,10 @@ import { resolveWorkflowOpening, workflowOpeningParentThreadId, } from "@t3tools/client-runtime/state/subagentRuntime"; -import { threadSupportsProviderHandoff } from "@t3tools/client-runtime/state/thread-workflows"; +import { + getUserQueuedThreadRuns, + threadSupportsProviderHandoff, +} from "@t3tools/client-runtime/state/thread-workflows"; import { resolvePendingHandoff } from "@t3tools/client-runtime/handoff"; import { HandoffRow } from "./chat/V2LifecycleRow"; import { @@ -126,8 +129,6 @@ import { useActiveThreadRef } from "../hooks/useActiveThreadRef"; import { composerRequiresModifier } from "../composer-logic"; import { derivePhase, - deriveActivePlanState, - selectComposerTasksPlan, deriveActiveWorkStartedAt, deriveCanInterruptRunningThread, findLatestProposedPlan, @@ -352,6 +353,8 @@ import { ChatTerminalDrawers } from "./chat/ChatTerminalDrawers"; import { ChatRightPanel } from "./chat/ChatRightPanel"; import { useDraftEnvironmentRouting } from "./chat/useDraftEnvironmentRouting"; import { branchMismatchBannerItem } from "./chat/ThreadActivityBanners"; +import { ThreadNow } from "./chat/ThreadNow"; +import { useDelayedStatus } from "../hooks/useDelayedStatus"; import { useTimelineFollow } from "./chat/useTimelineFollow"; import { type EnvironmentUnavailableState, @@ -512,6 +515,8 @@ export default function ChatView(props: ChatViewProps) { status: threadStatus, }); const threadDetailLoading = threadSyncPhase === "loading"; + // Held back briefly, so a quick sync does not flash a status line at the end of the timeline. + const delayedThreadSyncPhase = useDelayedStatus(routeThreadKey, threadSyncPhase); const activeProviderThread = serverProjection?.providerThreads.find( (thread) => thread.id === serverProjection.thread.activeProviderThreadId, ); @@ -989,30 +994,6 @@ export default function ChatView(props: ChatViewProps) { ); const latestRunSettled = isLatestRunSettled(activeLatestRun, activeRuntime); - const activePlan = deriveActivePlanState(serverProjection, activeActivityRun?.runId); - const activeActivityRunSettled = isLatestRunSettled(activeActivityRun, activeRuntime); - const composerTasksPlan = selectComposerTasksPlan( - serverProjection, - activePlan, - activeActivityRun?.runId ?? null, - activeActivityRunSettled, - ); - const activeComposerTasksProgress = (() => { - if (!composerTasksPlan) return null; - const live = !activeActivityRunSettled && composerTasksPlan.runId === activeActivityRun?.runId; - const totalSteps = composerTasksPlan.steps.length; - if (totalSteps === 0) return null; - const completedSteps = composerTasksPlan.steps.filter( - (step) => step.status === "completed", - ).length; - const step = - composerTasksPlan.steps.find((candidate) => candidate.status === "inProgress")?.step ?? - composerTasksPlan.steps.find((candidate) => candidate.status === "pending")?.step ?? - composerTasksPlan.steps.at(-1)!.step; - return { step, completedSteps, totalSteps, live }; - })(); - const activeComposerTaskSteps = - activeComposerTasksProgress && composerTasksPlan ? composerTasksPlan.steps : null; const activeThreadEnvironmentId = activeThread?.environmentId; const activeThreadProjectId = activeThread?.projectId; const activeProjectRef = @@ -2007,6 +1988,7 @@ export default function ChatView(props: ChatViewProps) { onTimelineAnchorReadyStable, onTimelineAnchorSizeChangedStable, onToolOutputCollapsedAtEndStable, + onTimelineFooterGrowStable, onIsAtEndChangeStable, anchorNewTurn, attachTimelineViewport, @@ -2185,22 +2167,11 @@ export default function ChatView(props: ChatViewProps) { modelStrip.offsetHeight + Number.parseFloat(getComputedStyle(modelStrip).marginTop), ) : 0; - const noticeStack = composerOverlayElement?.querySelector( - '[data-composer-banner-stack="true"]', - ); - const expandedNoticesHeight = noticeStack - ? Math.max( - 0, - noticeStack.getBoundingClientRect().height - - Number.parseFloat(getComputedStyle(noticeStack).minHeight), - ) - : 0; const nextInset = resolveComposerTimelineInset({ currentInset: composerTimelineInsetRef.current, overlayHeight: height, isResting, restingOnlyHeight, - expandedNoticesHeight, }); if (composerTimelineInsetRef.current !== nextInset) { composerTimelineInsetRef.current = nextInset; @@ -2226,9 +2197,8 @@ export default function ChatView(props: ChatViewProps) { const mainSurface = composerOverlayElement?.querySelector( '[data-chat-composer-main-surface="true"]', ); - const button = composerOverlayElement?.parentElement?.querySelector( - 'button[aria-label="Scroll to end"]', - ); + const button = + composerOverlayElement?.parentElement?.querySelector("[data-scroll-to-end]"); const clearance = composerOverlayElement && mainSurface && button ? resolveScrollToEndClearance({ @@ -2383,9 +2353,9 @@ export default function ChatView(props: ChatViewProps) { const { acknowledgeActiveThreadWoke, activeBranchMismatchKey, - backgroundWorkBanner, - childInputBanner, - goalBanner, + backgroundWorkNow, + childInputNow, + goalNow, handleSwitchCheckoutToThread, handleSwitchCheckoutToThreadStable, isRestoringThreadBranch, @@ -2550,9 +2520,6 @@ export default function ChatView(props: ChatViewProps) { : null; const composerBannerItems = (() => { const limitRecoveryItems = limitRecoveryBanner === null ? [] : [limitRecoveryBanner]; - const backgroundWorkItems = [childInputBanner, goalBanner, backgroundWorkBanner].filter( - (item) => item !== null, - ); const usageLimitsItems = usageLimitsBanner === null ? [] : [usageLimitsBanner]; const projectCloneItems = projectCloneBannerItem === null ? [] : [projectCloneBannerItem]; if (!localCheckoutBranchMismatch || !showBranchMismatchBanner || !activeBranchMismatchKey) { @@ -2562,7 +2529,6 @@ export default function ChatView(props: ChatViewProps) { ...usageLimitsItems, ...projectCloneItems, ...systemComposerBannerItems, - ...backgroundWorkItems, ]; } return [ @@ -2571,7 +2537,6 @@ export default function ChatView(props: ChatViewProps) { ...usageLimitsItems, ...projectCloneItems, ...systemComposerBannerItems, - ...backgroundWorkItems, branchMismatchBannerItem({ mismatchKey: activeBranchMismatchKey, mismatch: localCheckoutBranchMismatch, @@ -2979,6 +2944,66 @@ export default function ChatView(props: ChatViewProps) { openExpandedImagePreview(routeThreadKey, preview); }; const onExpandTimelineImageStable = useStableCallback(onExpandTimelineImage); + const shownThreadSyncPhase = activeEnvironmentUnavailable ? null : delayedThreadSyncPhase; + const hasThreadNow = + childInputNow !== null || + backgroundWorkNow !== null || + goalNow !== null || + shownThreadSyncPhase !== null; + const queuedRunCount = serverProjection ? getUserQueuedThreadRuns(serverProjection).length : 0; + // The queue control is mounted for every server thread but joins the footer only while it shows + // something, by its own rule: an optimistic message stops counting once the server has it. + const hasQueuedTurns = + queuedRunCount > 0 || + optimisticUserMessages.some( + (message) => + message.inputIntent === "queued_turn" && + !serverProjection?.messages.some((committed) => committed.id === message.id), + ); + const scrollToEndSummary = + [ + childInputNow === null ? null : "Subagent waiting", + queuedRunCount === 0 ? null : `${queuedRunCount} queued`, + ] + .filter((part) => part !== null) + .join(" · ") || null; + // The end of the timeline holds the thread's present and next turns: what it is doing now, + // its lifecycle status, guest messages awaiting you, then your queued messages. + const timelineFooter = + pendingHandoff === null && + !hasThreadNow && + threadStatusLine === null && + pendingGuestMessageCount === 0 && + !hasQueuedTurns ? null : ( + <> + {pendingHandoff === null ? null : ( +
+ +
+ )} + + {threadStatusLine} + {pendingGuestMessageCount > 0 && isServerThread && activeThread ? ( + + ) : null} + {hasQueuedTurns ? queuedRunsControl : null} + + ); const pendingSidebarFileDrops = useSidebarPendingFileDropStore((state) => state.pending); const consumePendingFileDrop = useSidebarPendingFileDropStore( @@ -3265,33 +3290,7 @@ export default function ChatView(props: ChatViewProps) { : {})} {...(onOpenWorktreeSetupTerminal ? { onOpenWorktreeSetupTerminal } : {})} isPreparingWorktree={!paintOnlyDisplayedTimeline && isPreparingWorktree} - footer={ - paintOnlyDisplayedTimeline || - (pendingHandoff === null && - pendingGuestMessageCount === 0 && - threadStatusLine === null) ? null : ( - <> - {pendingHandoff === null ? null : ( -
- -
- )} - {pendingGuestMessageCount > 0 && isServerThread && activeThread ? ( - - ) : null} - {threadStatusLine} - - ) - } + footer={paintOnlyDisplayedTimeline ? null : timelineFooter} listRef={legendListRef} runs={paintOnlyDisplayedTimeline ? [] : (serverProjection?.runs ?? [])} latestRun={paintOnlyDisplayedTimeline ? null : activeActivityRun} @@ -3367,6 +3366,7 @@ export default function ChatView(props: ChatViewProps) { onContentOverflowChange={setTimelineOverflows} onToolOutputCollapsedAtEnd={onToolOutputCollapsedAtEndStable} onViewportAttach={attachTimelineViewport} + onFooterGrow={onTimelineFooterGrowStable} hideEmptyPlaceholder={isDraftHeroState || threadDetailLoading} emptyPlaceholderInset={composerReservedHeight} topFadeEnabled={!hasTimelineTopBanner} @@ -3378,6 +3378,7 @@ export default function ChatView(props: ChatViewProps) { {showScrollToBottom && !isThreadFindActive && ( { composerRef.current?.restoreAfterTimelineReachedEnd(); scrollToEnd(true); @@ -3521,7 +3522,6 @@ export default function ChatView(props: ChatViewProps) { : projectCloneSendBlockReason } isPreparingWorktree={isPreparingWorktree && !sendQueuesBehindSetup} - queuedRunsControl={queuedRunsControl} bannerItems={composerBannerItems} resumeCompactionTokens={resumeCompactionTokens} keepFullHistory={keepFullHistory} @@ -3559,8 +3559,6 @@ export default function ChatView(props: ChatViewProps) { activeThreadModelSelection={activeThread?.modelSelection} activeProjectId={activeProject?.id ?? null} activeContextWindow={activeContextWindow} - activeTasksProgress={activeComposerTasksProgress} - activeTaskSteps={activeComposerTaskSteps} compactThreadUnavailable={compactThreadUnavailable} compactDisabled={compactDisabled} compactDisabledReason={compactDisabledReason} diff --git a/apps/web/src/components/ThreadRouteView.tsx b/apps/web/src/components/ThreadRouteView.tsx index d798eb884312e..30ee70d0dd637 100644 --- a/apps/web/src/components/ThreadRouteView.tsx +++ b/apps/web/src/components/ThreadRouteView.tsx @@ -1,21 +1,13 @@ import { scopedThreadKey } from "@t3tools/client-runtime/environment"; -import type { ScopedThreadRef } from "@t3tools/contracts"; -import { useNavigate } from "@tanstack/react-router"; +import { Navigate, useNavigate } from "@tanstack/react-router"; import { useEffect, useState } from "react"; import ChatView from "./ChatView"; import { BackgroundThreadContext } from "./chat/backgroundThread"; -import { resolveDraftPromotionNavigationTarget, threadHasStarted } from "./ChatView.logic"; -import { waitForDraftHeroTransition } from "./chat/draftHeroTransition"; import { SidebarInset } from "./ui/sidebar"; -import { - finalizePromotedDraftThreadByRef, - markPromotedDraftThreadByRef, - useBackgroundDraftSubmissionPending, - useComposerDraftStore, -} from "../composerDraftStore"; +import { useComposerDraftStore } from "../composerDraftStore"; import { useSidebarPendingFileDropStore } from "../sidebarPendingFileDropStore"; -import { useEnvironmentThreadRefs, useThreadRefs, useQuietThreadShell } from "../state/entities"; +import { useEnvironmentThreadRefs, useQuietThreadShell } from "../state/entities"; import { useEnvironmentShellStatus } from "../state/shell"; import { useEnvironmentThread } from "../state/threads"; import { @@ -26,7 +18,9 @@ import { } from "../threadRoutes"; /** - * Render in the shared layout to retain ChatView across route swaps; plain server threads remain unkeyed. + * Unkeyed so navigating between server threads reuses one ChatView. Rendered by the `_chat` + * layout, since an element only survives a route swap when the same parent renders it. Draft + * promotion runs in the draft store; this only follows the redirect it leaves behind. * `background` keeps the thread mounted, inert and in place under Settings or Usage. */ export function ThreadRouteView({ @@ -41,53 +35,36 @@ export function ThreadRouteView({ const draftSession = useComposerDraftStore((store) => draftId === null ? null : store.getDraftSession(draftId), ); - const threadRefs = useThreadRefs(); - // Promotion can begin before the server creates the reserved thread. - const inferredThreadRef = draftSession - ? (threadRefs.find( - (ref) => - ref.environmentId === draftSession.environmentId && - ref.threadId === draftSession.threadId, - ) ?? null) - : null; - const serverThreadRef: ScopedThreadRef | null = - target.kind === "server" ? target.threadRef : inferredThreadRef; - const serverThread = useQuietThreadShell(serverThreadRef); - const backgroundSubmissionPending = useBackgroundDraftSubmissionPending( - target.kind === "draft" ? serverThreadRef : null, + const draftRedirect = useComposerDraftStore((store) => + draftId === null ? null : store.getPromotedDraftRedirect(draftId), ); - const canonicalThreadRef = - target.kind === "draft" - ? resolveDraftPromotionNavigationTarget({ - serverThreadRef, - serverThread, - backgroundSubmissionPending, - }) - : null; - + const serverThreadRef = target.kind === "server" ? target.threadRef : null; + const serverThreadShell = useQuietThreadShell(serverThreadRef); const shellStatus = useEnvironmentShellStatus(serverThreadRef?.environmentId ?? null); - const serverThreadShell = serverThread; const environmentThreadRefs = useEnvironmentThreadRefs(serverThreadRef?.environmentId ?? null); const bootstrapComplete = isThreadRouteSnapshotAuthoritative(shellStatus); const draftThread = useComposerDraftStore((store) => serverThreadRef ? store.getDraftThreadByRef(serverThreadRef) : null, ); - const promotedDraftId = useComposerDraftStore((store) => - target.kind === "server" ? store.getDraftIdByRef(target.threadRef) : null, + // Reached from the sidebar before finalize, the thread still has its draft. + const serverThreadDraftId = useComposerDraftStore((store) => + serverThreadRef ? store.getDraftIdByRef(serverThreadRef) : null, ); - // Latch the key through promotion because the draft record disappears after the route swap. - const [chatViewKey, setChatViewKey] = useState<{ threadKey: string; key: string } | null>(null); - const serverThreadKey = target.kind === "server" ? scopedThreadKey(target.threadRef) : null; - const nextChatViewKey = - serverThreadKey === null - ? null - : chatViewKey?.threadKey === serverThreadKey - ? chatViewKey - : promotedDraftId - ? { threadKey: serverThreadKey, key: promotedDraftId } + // The ChatView that carried a draft keeps its key through the redirect to its thread, and only + // until the route leaves that thread, so later visits reuse the shared unkeyed ChatView. + const [handoffKey, setHandoffKey] = useState<{ threadKey: string; key: string } | null>(null); + const nextHandoffKey = + draftId !== null && draftSession === null && draftRedirect + ? handoffKey?.key === draftId + ? handoffKey + : { threadKey: scopedThreadKey(draftRedirect), key: draftId } + : serverThreadRef && handoffKey?.threadKey === scopedThreadKey(serverThreadRef) + ? handoffKey + : serverThreadRef && serverThreadDraftId + ? { threadKey: scopedThreadKey(serverThreadRef), key: serverThreadDraftId } : null; - if (nextChatViewKey !== chatViewKey) { - setChatViewKey(nextChatViewKey); + if (nextHandoffKey !== handoffKey) { + setHandoffKey(nextHandoffKey); } const environmentHasDraftThreads = useComposerDraftStore((store) => serverThreadRef ? store.hasDraftThreadsInEnvironment(serverThreadRef.environmentId) : false, @@ -110,43 +87,8 @@ export function ThreadRouteView({ unlistedThreadDetail, draftThreadExists: draftThread !== null, }); - const serverThreadStarted = threadHasStarted(serverThreadShell); const environmentHasAnyThreads = environmentThreadRefs.length > 0 || environmentHasDraftThreads; - useEffect(() => { - if (!inferredThreadRef || draftSession?.promotedTo) { - return; - } - markPromotedDraftThreadByRef(inferredThreadRef); - }, [draftSession?.promotedTo, inferredThreadRef]); - - useEffect(() => { - if (!canonicalThreadRef || background) { - return; - } - let cancelled = false; - void waitForDraftHeroTransition().then(() => { - if (cancelled) { - return; - } - void navigate({ - to: "/$environmentId/$threadId", - params: buildThreadRouteParams(canonicalThreadRef), - replace: true, - }); - }); - return () => { - cancelled = true; - }; - }, [background, canonicalThreadRef, navigate]); - - useEffect(() => { - if (background || target.kind !== "draft" || draftSession || canonicalThreadRef) { - return; - } - void navigate({ to: "/", replace: true }); - }, [background, canonicalThreadRef, draftSession, navigate, target.kind]); - useEffect(() => { if (target.kind !== "server" || !bootstrapComplete) { return; @@ -160,14 +102,8 @@ export function ThreadRouteView({ } }, [background, bootstrapComplete, environmentHasAnyThreads, navigate, renderState, target]); - useEffect(() => { - if (target.kind !== "server" || !serverThreadStarted || !draftThread) { - return; - } - finalizePromotedDraftThreadByRef(target.threadRef); - }, [draftThread, serverThreadStarted, target]); - let view: React.ReactNode = null; + let redirect: React.ReactNode = null; if (target.kind === "draft") { if (draftSession) { view = ( @@ -180,11 +116,30 @@ export function ThreadRouteView({ forceExpandedMobileComposer /> ); + } else if (draftRedirect) { + // Same slot and key as the server route renders, so the swap keeps this instance. + view = ( + + ); + redirect = ( + + ); + } else { + redirect = ; } } else if (renderState === "ready" || (renderState === "loading" && serverThreadShell !== null)) { view = ( {view} + {background ? null : redirect} ); } diff --git a/apps/web/src/components/chat/ChatComposer.tsx b/apps/web/src/components/chat/ChatComposer.tsx index caae00048fc9e..d7b46eea0abc0 100644 --- a/apps/web/src/components/chat/ChatComposer.tsx +++ b/apps/web/src/components/chat/ChatComposer.tsx @@ -48,7 +48,6 @@ import { createModelSelection, normalizeModelSlug } from "@t3tools/shared/model" import { USAGE_LIMITS_COMMAND } from "@t3tools/shared/usageLimits"; import { memo, - type ReactNode, useEffect, useEffectEvent, useId, @@ -105,14 +104,6 @@ import { useComposerTriggerState } from "./useComposerTriggerState"; import { useComposerMenuItems } from "./useComposerMenuItems"; import { useComposerFocusState } from "./useComposerFocusState"; import { useComposerMultilinePrompt } from "./useComposerMultilinePrompt"; -import { - ComposerTasksBadge, - ComposerTasksContent, - ComposerTasksDrawer, - type ComposerTaskStep, - type ComposerTasksProgress, -} from "./ComposerTasksBadge"; -import { ComposerActivityRow } from "./ComposerActivityStatus"; import { reconcileAttachmentContextReferences, useRetainedContextPayloads, @@ -120,11 +111,7 @@ import { import type { ThreadSyncPhase } from "../../threadSync"; import { ComposerBanner } from "./ComposerBanner"; import { ComposerSurface } from "./ComposerSurface"; -import { - ComposerBannerStack, - type ComposerBannerStackContent, - type ComposerBannerStackItem, -} from "./ComposerBannerStack"; +import { ComposerBannerStack, type ComposerBannerStackItem } from "./ComposerBannerStack"; import { attachmentsToReleaseOnUploadCapabilityLoss, composerOtherFilesForPresentation, @@ -274,7 +261,6 @@ import { resolveProviderSkillsForCwd, resolveProviderSlashCommandsForCwd, } from "@t3tools/client-runtime/providerSkills"; -import { useDelayedStatus } from "../../hooks/useDelayedStatus"; import { useMediaQuery } from "../../hooks/useMediaQuery"; import { useSoftwareKeyboardOpen } from "../../hooks/useSoftwareKeyboardOpen"; import { useStableCallback } from "../../hooks/useStableCallback"; @@ -435,8 +421,6 @@ export interface ChatComposerProps { showPlanFollowUpPrompt: boolean; activeProposedPlan: LatestProposedPlanState | null; - activeTasksProgress: ComposerTasksProgress | null; - activeTaskSteps: readonly ComposerTaskStep[] | null; threadSyncPhase: ThreadSyncPhase | null; runtimeMode: RuntimeMode; @@ -481,7 +465,6 @@ export interface ChatComposerProps { onPageScrollKeyUp: (key: string) => void; onPageScrollRelease: () => void; - queuedRunsControl?: ReactNode; editingQueuedAttachments: ReadonlyArray<{ readonly attachment: ContractChatAttachment; readonly url: string | null; @@ -663,9 +646,6 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps) const activePendingProgress = holdingUserInput ? null : incomingPendingProgress; const activePendingIsResponding = !holdingUserInput && incomingPendingIsResponding; const isLiteralPendingAnswer = activePendingProgress?.activeQuestion?.initialAnswer !== undefined; - const shownSyncPhase = useDelayedStatus(composerDraftTargetKey, props.threadSyncPhase); - const activeTasksProgress = shownSyncPhase === null ? props.activeTasksProgress : null; - const activeTaskSteps = shownSyncPhase === null ? props.activeTaskSteps : null; const isEditingQueuedMessage = editingQueuedAttachments !== null; const composerDraft = useComposerThreadDraft(composerDraftTarget); const composerDraftTargetKeyRef = useRef(""); @@ -1097,7 +1077,6 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps) const [composerMenuAnchor, setComposerMenuAnchor] = useState(null); const [hasWrappedPrompt, observeWrappedPrompt] = useComposerMultilinePrompt(); const hasMultilinePrompt = prompt.includes("\n") || hasWrappedPrompt; - const [isTasksDrawerOpen, setIsTasksDrawerOpen] = useState(false); // A pending question stays expanded: its card moves into the banner dock, // so collapsing would leave the surface empty and squashed beneath it. const isComposerCollapsedMobile = @@ -2309,28 +2288,8 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps) importContextRecords, expandMobileComposer: expandMobileComposerStable, }); - const toggleTasksDrawer = () => { - setIsTasksDrawerOpen((open) => !open); - }; - const toggleTasksDrawerStable = useStableCallback(toggleTasksDrawer); - const hasBannerItems = props.bannerItems.length > 0; const hasBlockingComposerTopDrawer = activePendingApproval !== null || pendingUserInputs.length > 0; - const showInlineTasksBadge = - activeTasksProgress !== null && - activeTaskSteps !== null && - !isTasksDrawerOpen && - !hasBlockingComposerTopDrawer && - (hasBannerItems || showComposerTopDrawer || isComposerCollapsedMobile); - const inlineTasksBadge = showInlineTasksBadge ? ( - - ) : null; const hasImageAttachmentAttention = standaloneComposerImages.some((image) => { const upload = uploadsByImageId[image.id]; const failedInCurrentEnvironment = @@ -2341,7 +2300,6 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps) }); const composerHasExpandedChrome = showComposerTopDrawer || - isTasksDrawerOpen || composerMenuOpen || isStashMenuOpen || isDragOverComposer || @@ -2421,8 +2379,7 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps) canTrackComposerScrollGesture && settings.composerCollapseOnScroll && !hasMultilinePrompt && - !composerHasExpandedChrome && - !showInlineTasksBadge; + !composerHasExpandedChrome; const composerScrollCollapseEligible = canScrollCollapseComposer && !isComposerResting; useLayoutEffect(() => { composerScrollCollapseEligibleRef.current = composerScrollCollapseEligible; @@ -2586,48 +2543,14 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps) getModelDisabledReason={getModelDisabledReason} /> ); - const showTasksTab = - !hasBannerItems && - !showComposerTopDrawer && - !isTasksDrawerOpen && - !isComposerCollapsedMobile && - activeTasksProgress !== null && - activeTaskSteps !== null && - activeTasksProgress.totalSteps > 0; - const activityStackContent = hasBannerItems ? ( - shownSyncPhase ? ( - - ) : !hasBlockingComposerTopDrawer && activeTasksProgress && activeTaskSteps ? ( - - ) : null - ) : null; - const activityStackItem: ComposerBannerStackContent | null = activityStackContent - ? { - id: "composer-activity", - variant: "default", - priority: "activity", - content: activityStackContent, - } - : null; - const bannerStackItems = activityStackItem - ? [activityStackItem, ...props.bannerItems] + // An open approval or question owns the space above the composer. Only a machine problem, + // which is why an answer could not go through, stays beside it. + const shelfItems = hasBlockingComposerTopDrawer + ? props.bannerItems.filter( + (item) => + item.group === "environment" && (item.variant === "error" || item.variant === "warning"), + ) : props.bannerItems; - const [tasksDrawerThreadId, setTasksDrawerThreadId] = useState(activeThreadId); - if ( - isTasksDrawerOpen && - (activeTasksProgress === null || - activeTaskSteps === null || - hasBlockingComposerTopDrawer || - tasksDrawerThreadId !== activeThreadId) - ) { - setIsTasksDrawerOpen(false); - } - if (tasksDrawerThreadId !== activeThreadId) setTasksDrawerThreadId(activeThreadId); const insertComposerText = ( text: string, @@ -3478,20 +3401,8 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps) : null} - - {!activityStackItem && (shownSyncPhase || inlineTasksBadge) ? ( - - - {shownSyncPhase ? : inlineTasksBadge} - - - ) : null} - {showComposerTopDrawer && (!isTasksDrawerOpen || hasBlockingComposerTopDrawer) ? ( + + {showComposerTopDrawer ? ( ) : null} - {!activityStackItem && - isTasksDrawerOpen && - !hasBlockingComposerTopDrawer && - activeTasksProgress && - activeTaskSteps ? ( - - ) : null} - {showTasksTab ? ( - - - - ) : null} - - - - - - {threadSyncLabel(phase)} - - - - ); -} diff --git a/apps/web/src/components/chat/ComposerBanner.tsx b/apps/web/src/components/chat/ComposerBanner.tsx index be7e268ccb48d..ef07497171ee2 100644 --- a/apps/web/src/components/chat/ComposerBanner.tsx +++ b/apps/web/src/components/chat/ComposerBanner.tsx @@ -34,26 +34,22 @@ const variantColors: Record = { }; function Surface({ - placement = "attached", variant = "default", className, ...props }: ComponentProps<"div"> & { - placement?: "attached" | "floating"; variant?: ComposerBannerVariant; }) { return (
= { - default: "border-(--chat-composer-attached-outline)", - error: "border-destructive/24", - info: "border-(--chat-composer-attached-outline)", - success: "border-(--chat-composer-attached-outline)", - warning: "border-warning/24", -}; - -function Peek({ - className, - variant = "default", - ...props -}: ComponentProps<"button"> & { variant?: ComposerBannerVariant }) { - return ( - - ) : null} - - - {isEditing ? Editing queued message: : null} - {item.pending ? ( - - ) : null} - {item.thumbnails.length > 0 ? ( - - {item.thumbnails.map((thumbnail) => ( + {thumbnail.url ? ( + {thumbnail.name} + ) : ( - {thumbnail.url ? ( - {thumbnail.name} - ) : ( - - )} - - ))} + aria-label={thumbnail.name} + className="block size-full bg-muted/60" + /> + )} - ) : null} + ))} + + ) : null} + {/* In full, like a sent turn: a queued message is read before it is sent. */} + {previewText ? ( +

{item.guestName === undefined ? null : ( - {item.guestName} + {item.guestName} )} + {previewText} +

+ ) : null} +
+
+ {items.length > 1 && canReorder && rowRunId !== null && rowServerIndex !== null ? ( + + ) : items.length > 1 ? ( + {position + 1} + ) : null} + {item.pending ? ( + + + Saving + + ) : null} + {isEditing ? ( + <> + Editing in the composer + + + ) : ( + <> - }> - {previewText} + {/* The span keeps the tooltip, and its reason, on a disabled button. */} + }> + - - {previewText} + + {props.editBlockedReason ?? + `Edit in the composer${item.serverIndex === queued.length - 1 && props.editShortcutLabel ? ` (${props.editShortcutLabel})` : ""}`} - - - {isEditing ? ( - - ) : ( - <> - - {/* The span keeps the tooltip, and its reason, on a disabled button. */} - }> - - - - {props.editBlockedReason ?? - `Edit in the composer${item.serverIndex === queued.length - 1 && props.editShortcutLabel ? ` (${props.editShortcutLabel})` : ""}`} - - - - }> - - - - {`${workflow?.canSendNow ? "Start a turn with this message" : "Send as a steer instead"}${item.serverIndex === 0 && props.steerShortcutLabel ? ` (${props.steerShortcutLabel})` : ""}`} - - - - { - if (item.runId !== null) void remove(item.runId); - }} - /> + + }> + + + + {`${workflow?.canSendNow ? "Start a turn with this message" : "Send as a steer instead"}${item.serverIndex === 0 && props.steerShortcutLabel ? ` (${props.steerShortcutLabel})` : ""}`} + + + + { + if (item.runId !== null) void remove(item.runId); + }} /> - Remove from queue - - - )} - - - ); - })} - - - - + } + > + + + Remove from queue + + + )} +
+ + ); + })} + + {collapsible ? ( +
+ event.preventDefault()} + onClick={() => setShowAll((value) => !value)} + > + {showAll ? "Show fewer" : `Show all ${items.length} queued`} + + +
+ ) : null} + ); } diff --git a/apps/web/src/components/chat/ThreadActivityBanners.tsx b/apps/web/src/components/chat/ThreadActivityBanners.tsx index 39a60ed27ce3e..e132587a75951 100644 --- a/apps/web/src/components/chat/ThreadActivityBanners.tsx +++ b/apps/web/src/components/chat/ThreadActivityBanners.tsx @@ -15,21 +15,25 @@ import { cn } from "~/lib/utils"; import { Button, InlineButton } from "../ui/button"; import { Tooltip, TooltipPopup, TooltipTrigger } from "../ui/tooltip"; import type { ComposerBannerStackItem } from "./ComposerBannerStack"; +import type { ThreadNowItem } from "./ThreadNow"; /** Subagents waiting on the user, unless the parent is itself waiting on them. */ -export function childInputBannerItem(input: { +export function childInputNowItem(input: { readonly childThreadInputs: ReadonlyArray; readonly parentAwaitingUser: boolean; readonly onOpenThread: (threadId: ThreadId) => void; -}): ComposerBannerStackItem | null { +}): ThreadNowItem | null { const { childThreadInputs, onOpenThread } = input; const first = childThreadInputs[0]; if (!first || input.parentAwaitingUser) return null; return { id: `child-input:${first.id}`, - variant: "info", - priority: "activity", - icon: first.hasPendingApprovals ? : , + // The only line at the end of the timeline that needs you gets the info color. + icon: first.hasPendingApprovals ? ( + + ) : ( + + ), title: childThreadInputsTitle(childThreadInputs), description: childThreadInputs.map((child, index) => ( @@ -43,25 +47,24 @@ export function childInputBannerItem(input: { )), actions: ( - + ), }; } -export function goalBannerItem(input: { +/** The thread's goal, for the end of the timeline. */ +export function goalNowItem(input: { readonly threadId: ThreadId; readonly goal: OrchestrationV2ProviderGoal; readonly isWorking: boolean; readonly onSendCommand: (text: string, failureMessage: string) => Promise; -}): ComposerBannerStackItem { +}): ThreadNowItem { const { isWorking, onSendCommand } = input; const presentation = presentProviderGoal(input.goal, isWorking); return { id: `goal:${input.threadId}`, - variant: "default", - priority: "activity", icon: , title: presentation.usage === null @@ -72,46 +75,45 @@ export function goalBannerItem(input: { actions: ( <> {presentation.canResume && !isWorking ? ( - + <> + void onSendCommand("/goal resume", "Failed to resume goal.")} + > + Resume + + · + ) : null} - + ), }; } -export function backgroundWorkBannerItem(input: { +/** Background commands and subagents, for the end of the timeline. */ +export function backgroundWorkNowItem(input: { readonly threadId: ThreadId; readonly tasks: ReadonlyArray; readonly stopDisabled: boolean; readonly stopping: boolean; readonly onStop: () => Promise; readonly onOpenThread: (threadId: ThreadId) => void; -}): ComposerBannerStackItem | null { +}): ThreadNowItem | null { const { onOpenThread } = input; const presentation = presentPendingBackgroundWork(input.tasks); if (presentation === null) return null; return { id: `background-work:${input.threadId}`, - variant: "default", - priority: "activity", icon: ( = 3} - onPress={() => changeZoom(Math.min(3, scale + 0.25))} + disabled={scale >= PDF_MAX_ZOOM} + onPress={() => changeZoom(stepPdfZoom(scale, 1))} > diff --git a/apps/web/src/components/files/pdfLayout.test.ts b/apps/web/src/components/files/pdfLayout.test.ts new file mode 100644 index 0000000000000..5a57be1de95c0 --- /dev/null +++ b/apps/web/src/components/files/pdfLayout.test.ts @@ -0,0 +1,144 @@ +import { describe, expect, it } from "vite-plus/test"; +import { + currentPdfPage, + pdfFindIncludes, + pdfFindMatchRuns, + pdfPageOffsets, + pdfPageScrollTop, + pdfPageText, + pdfPageWidth, + stepPdfZoom, + visiblePdfPages, +} from "./pdfLayout"; + +describe("pdfPageWidth", () => { + it("fits the page to the viewport minus its gutters until a zoom is chosen", () => { + expect(pdfPageWidth(500, 612, null)).toEqual({ width: 468, scale: 468 / 612 }); + expect(pdfPageWidth(500, 612, 1.5)).toEqual({ width: 918, scale: 1.5 }); + }); + + it("never collapses below one pixel in a tiny viewport", () => { + expect(pdfPageWidth(10, 612, null).width).toBe(1); + }); +}); + +describe("stepPdfZoom", () => { + it("steps by a quarter and clamps to 25%..300%", () => { + expect(stepPdfZoom(1, 1)).toBe(1.25); + expect(stepPdfZoom(1, -1)).toBe(0.75); + expect(stepPdfZoom(2.9, 1)).toBe(3); + expect(stepPdfZoom(0.3, -1)).toBe(0.25); + }); + + it("starts from the fit-width scale when no zoom is set", () => { + const { scale } = pdfPageWidth(500, 612, null); + expect(stepPdfZoom(scale, 1)).toBeCloseTo(468 / 612 + 0.25); + }); +}); + +describe("mixed-height page layout", () => { + // A short banner page, a letter page, then a page half as tall as it is wide. + const ratios = [140 / 612, 792 / 612, 306 / 612]; + const width = 612; + const offsets = pdfPageOffsets(ratios, width); + + it("stacks pages with a gap before, between, and after them", () => { + expect(offsets).toEqual([16, 172, 980, 1302]); + }); + + it("reports the page whose bottom is past the top gutter as current", () => { + expect(currentPdfPage(offsets, 3, 0)).toBe(0); + expect(currentPdfPage(offsets, 3, 154)).toBe(0); + expect(currentPdfPage(offsets, 3, 155)).toBe(1); + expect(currentPdfPage(offsets, 3, 962)).toBe(1); + expect(currentPdfPage(offsets, 3, 964)).toBe(2); + }); + + it("jumps to each page so that page becomes current", () => { + for (const index of [0, 1, 2]) + expect(currentPdfPage(offsets, 3, pdfPageScrollTop(offsets, index))).toBe(index); + expect(pdfPageScrollTop(offsets, 7)).toBe(0); + }); + + it("mounts pages within a viewport above and two below", () => { + const indexes = (scrollTop: number, height: number) => + visiblePdfPages(ratios, offsets, scrollTop, height).map((page) => page.index); + expect(indexes(0, 100)).toEqual([0, 1]); + expect(indexes(1100, 100)).toEqual([2]); + expect(indexes(1100, 900)).toEqual([1, 2]); + expect(visiblePdfPages(ratios, offsets, 0, 100)[0]).toEqual({ index: 0, ratio: ratios[0] }); + }); + + it("scales offsets with the page width when zoomed", () => { + expect(pdfPageOffsets(ratios, width * 2)).toEqual([16, 312, 1912, 2540]); + }); +}); + +describe("pdfPageText", () => { + it("joins text items, adds line ends, and skips marked content", () => { + expect( + pdfPageText([ + { str: "Quarter", hasEOL: false }, + { type: "beginMarkedContent" }, + { str: "ly outlook", hasEOL: true }, + { str: "Next", hasEOL: false }, + ]), + ).toBe("Quarterly outlook\nNext"); + }); +}); + +describe("pdfFindMatchRuns", () => { + it("highlights every run a match spans when a word is split across spans", () => { + expect(pdfFindMatchRuns(["Quarter", "ly outlook", " for Q3"], "quarterly OUTLOOK")).toEqual([ + true, + true, + false, + ]); + }); + + it("highlights each separate match", () => { + expect(pdfFindMatchRuns(["risk", " and ", "budget", " ", "Risk"], "risk")).toEqual([ + true, + false, + false, + false, + true, + ]); + }); + + it("matches a space in the query across a line end", () => { + expect( + pdfFindMatchRuns(["Q3 quarterly", "\n", "outlook", " ahead"], "quarterly outlook"), + ).toEqual([true, true, true, false]); + }); + + it("matches a word hyphenated across a line end", () => { + expect(pdfFindMatchRuns(["the quar-", "\n", "terly report"], "quarterly")).toEqual([ + true, + false, + true, + ]); + }); + + it("drops a line-end hyphen after a letter outside the BMP", () => { + expect(pdfFindMatchRuns(["\u{10400}-", "\n", "\u{10401}"], "\u{10400}\u{10401}")).toEqual([ + true, + false, + true, + ]); + }); + + it("finds the same pages the highlights do", () => { + const page = "Q3 quarterly\noutlook ahead, the quar-\nterly report"; + expect(pdfFindIncludes(page, "Quarterly OUTLOOK")).toBe(true); + expect(pdfFindIncludes(page, "quarterly report")).toBe(true); + expect(pdfFindIncludes(page, "bud-get")).toBe(false); + expect(pdfFindIncludes(page, " ")).toBe(false); + }); + + it("highlights nothing for a blank or missing query", () => { + expect(pdfFindMatchRuns(["a b", "c"], " ")).toEqual([false, false]); + expect(pdfFindMatchRuns(["a b", "c"], "")).toEqual([false, false]); + expect(pdfFindMatchRuns(["a b", "c"], "zzz")).toEqual([false, false]); + }); +}); diff --git a/apps/web/src/components/files/pdfLayout.ts b/apps/web/src/components/files/pdfLayout.ts new file mode 100644 index 0000000000000..451af886fb67b --- /dev/null +++ b/apps/web/src/components/files/pdfLayout.ts @@ -0,0 +1,120 @@ +const PDF_PAGE_GAP = 16; +export const PDF_MIN_ZOOM = 0.25; +export const PDF_MAX_ZOOM = 3; +const PDF_ZOOM_STEP = 0.25; + +export function pdfPageWidth(viewportWidth: number, pageWidth: number, zoom: number | null) { + const fitWidth = Math.max(1, viewportWidth - 2 * PDF_PAGE_GAP); + return { + scale: zoom ?? fitWidth / pageWidth, + width: zoom === null ? fitWidth : pageWidth * zoom, + }; +} + +export function stepPdfZoom(scale: number, direction: 1 | -1) { + return direction > 0 + ? Math.min(PDF_MAX_ZOOM, scale + PDF_ZOOM_STEP) + : Math.max(PDF_MIN_ZOOM, scale - PDF_ZOOM_STEP); +} + +/** Top offset of each page plus the end of the last one; ratios are height / width. */ +export function pdfPageOffsets(ratios: readonly number[], width: number) { + const result = [PDF_PAGE_GAP]; + for (const ratio of ratios) + result.push(result[result.length - 1]! + width * ratio + PDF_PAGE_GAP); + return result; +} + +export function currentPdfPage(offsets: readonly number[], pageCount: number, scrollTop: number) { + for (let index = 0; index < pageCount; index++) + if (offsets[index + 1]! > scrollTop + PDF_PAGE_GAP + 1) return index; + return 0; +} + +/** Pages within one viewport above and two below the visible area stay mounted. */ +export function visiblePdfPages( + ratios: readonly number[], + offsets: readonly number[], + scrollTop: number, + viewportHeight: number, +) { + return ratios.flatMap((ratio, index) => + offsets[index + 1]! >= scrollTop - viewportHeight && + offsets[index]! <= scrollTop + viewportHeight * 2 + ? [{ index, ratio }] + : [], + ); +} + +export function pdfPageScrollTop(offsets: readonly number[], index: number) { + return Math.max(0, (offsets[index] ?? PDF_PAGE_GAP) - PDF_PAGE_GAP); +} + +export function pdfPageText( + items: readonly ({ str: string; hasEOL: boolean } | { type: string })[], +) { + return items.map((item) => ("str" in item ? item.str + (item.hasEOL ? "\n" : "") : "")).join(""); +} + +/** + * Lowercased search text with each whitespace run, line ends included, read as one space, and a + * hyphen that ends a line between letters dropped, as pdf.js's own find does. `owner` maps each + * character back to the run it came from. + */ +function pdfFindText(runs: readonly string[]) { + const chars = runs.flatMap((run, index) => + Array.from(run.toLowerCase(), (char) => ({ char, run: index })), + ); + let text = ""; + let last = ""; + const owner: number[] = []; + for (let index = 0; index < chars.length; index++) { + const { char, run } = chars[index]!; + if (/\s/.test(char)) { + if (!text.endsWith(" ")) { + text += " "; + last = " "; + owner.push(run); + } + } else if ( + char === "-" && + chars[index + 1]?.char === "\n" && + /\p{L}/u.test(last) && + /\p{L}/u.test(chars[index + 2]?.char ?? "") + ) { + index++; + } else { + text += char; + last = char; + for (let unit = 0; unit < char.length; unit++) owner.push(run); + } + } + return { text, owner }; +} + +/** Whether a page's text holds the query, under the same rules as `pdfFindMatchRuns`, without + * mapping characters back to runs: the page scan checks every page on each query. */ +export function pdfFindIncludes(text: string, query: string) { + const needle = query.toLowerCase().replace(/\s+/g, " "); + if (!needle.trim()) return false; + return text + .toLowerCase() + .replace(/(\p{L})-\n(?=\p{L})/gu, "$1") + .replace(/\s+/g, " ") + .includes(needle); +} + +/** Which text runs hold part of a case-insensitive match, when pdf.js splits words across spans. */ +export function pdfFindMatchRuns(runs: readonly string[], query: string) { + const { text, owner } = pdfFindText(runs); + const needle = query.toLowerCase().replace(/\s+/g, " "); + const hits = runs.map(() => false); + if (!needle.trim()) return hits; + for ( + let match = text.indexOf(needle); + match !== -1; + match = text.indexOf(needle, match + needle.length) + ) + for (let index = match; index < match + needle.length; index++) hits[owner[index]!] = true; + return hits; +} diff --git a/apps/web/src/components/guest/GuestPage.tsx b/apps/web/src/components/guest/GuestPage.tsx index f8268d9fe492e..2314fab42d18f 100644 --- a/apps/web/src/components/guest/GuestPage.tsx +++ b/apps/web/src/components/guest/GuestPage.tsx @@ -488,7 +488,11 @@ function GuestThread({ } /> {follow.showScrollToBottom ? ( - follow.scrollToEnd(true)} /> + follow.scrollToEnd(true)} + /> ) : null}
diff --git a/apps/web/src/composerDraftStore.test.ts b/apps/web/src/composerDraftStore.test.ts index 238cd8663510e..250c7790e0795 100644 --- a/apps/web/src/composerDraftStore.test.ts +++ b/apps/web/src/composerDraftStore.test.ts @@ -26,12 +26,14 @@ import { ProviderDriverKind, ProviderInstanceId, PROVIDER_SEND_TURN_MAX_ATTACHMENTS, + RunId, ThreadId, type OrchestrationV2ThreadShell, type OrchestrationV2ShellSnapshot, type ModelSelection, type PreviewAnnotationPayload, type ProviderOptionSelection, + type ScopedThreadRef, } from "@t3tools/contracts"; import { createModelSelection } from "@t3tools/shared/model"; @@ -81,7 +83,9 @@ import { clearBackgroundDraftSubmissionByRef, finalizePromotedDraftThreadByRef, markPromotedDraftThreadByRef, + resolveDraftPromotionNavigationTarget, restoreFailedDraftThread, + subscribeDraftThreadPromotion, type ComposerFileAttachment, type ComposerImageAttachment, composerFileNeedsReattach, @@ -89,6 +93,7 @@ import { useComposerDraftStore, DraftId, } from "./composerDraftStore"; +import { waitForDraftHeroTransition } from "./components/chat/draftHeroTransition"; import { insertInlineContextReference } from "./lib/composerContextReferences"; import { terminalContextReference, threadContextRecord } from "./lib/composerContextRecords"; import { @@ -164,6 +169,8 @@ function resetComposerDraftStore() { draftsByThreadKey: {}, draftThreadsByThreadKey: {}, logicalProjectDraftThreadKeyByLogicalProjectKey: {}, + backgroundSubmissionThreadKeys: {}, + promotedDraftRedirects: {}, stickyModelSelectionByProvider: {}, stickyOptionsByModelByProvider: {}, stickyActiveProvider: null, @@ -1306,6 +1313,162 @@ function modelReconciliationHarness( }; } +type PromotionShell = NonNullable< + Parameters[0]["serverThread"] +>; + +function draftPromotionHarness() { + const tasks: Array<() => void> = []; + const registry = AtomRegistry.make({ + scheduleTask: (task) => { + tasks.push(task); + return () => {}; + }, + }); + onTestFinished(() => registry.dispose()); + const flush = () => { + for (let task = tasks.shift(); task !== undefined; task = tasks.shift()) task(); + }; + const threadRefsAtom = Atom.make>([]); + const shellAtoms = new Map>(); + const shellAtom = (ref: ScopedThreadRef) => { + const key = scopedThreadKey(ref); + let atom = shellAtoms.get(key); + if (!atom) { + atom = Atom.make(null); + shellAtoms.set(key, atom); + } + return atom; + }; + onTestFinished( + subscribeDraftThreadPromotion({ registry, threadRefsAtom, threadShellAtom: shellAtom }), + ); + flush(); + return { + flush, + arrive(ref: ScopedThreadRef, shell: PromotionShell | null = null) { + registry.set(shellAtom(ref), shell); + registry.set(threadRefsAtom, [...registry.get(threadRefsAtom), ref]); + flush(); + }, + updateShell(ref: ScopedThreadRef, shell: PromotionShell) { + registry.set(shellAtom(ref), shell); + flush(); + }, + }; +} + +describe("composerDraftStore draft promotion", () => { + const projectRef = scopeProjectRef(TEST_ENVIRONMENT_ID, ProjectId.make("project-promotion")); + const draftId = DraftId.make("draft-promotion"); + const threadId = ThreadId.make("thread-promotion"); + const threadRef = scopeThreadRef(TEST_ENVIRONMENT_ID, threadId); + const preparingRun = { + runId: RunId.make("run-promotion"), + status: "preparing" as const, + requestedAt: "2026-03-29T00:00:00.000Z", + startedAt: null, + completedAt: null, + assistantMessageId: null, + }; + + beforeEach(resetComposerDraftStore); + + it("stays on the draft until the server owns the send", () => { + expect( + resolveDraftPromotionNavigationTarget({ + serverThreadRef: threadRef, + serverThread: { latestRun: preparingRun, latestUserMessageAt: null }, + backgroundSubmissionPending: false, + }), + ).toBeNull(); + expect( + resolveDraftPromotionNavigationTarget({ + serverThreadRef: threadRef, + serverThread: { latestRun: null, latestUserMessageAt: null }, + backgroundSubmissionPending: false, + }), + ).toBeNull(); + const persisted = { latestRun: preparingRun, latestUserMessageAt: "2026-03-29T00:00:00.000Z" }; + expect( + resolveDraftPromotionNavigationTarget({ + serverThreadRef: threadRef, + serverThread: persisted, + backgroundSubmissionPending: false, + }), + ).toBe(threadRef); + expect( + resolveDraftPromotionNavigationTarget({ + serverThreadRef: threadRef, + serverThread: persisted, + backgroundSubmissionPending: true, + }), + ).toBeNull(); + }); + + it("marks a draft promoting when its reserved thread arrives, then finalizes into it", async () => { + const h = draftPromotionHarness(); + const store = useComposerDraftStore.getState(); + store.setProjectDraftThreadId(projectRef, draftId, { threadId }); + store.setPrompt(draftId, "typed during setup"); + h.flush(); + expect(store.getDraftSession(draftId)?.promotedTo).toBeNull(); + + h.arrive(threadRef, { latestRun: preparingRun, latestUserMessageAt: null }); + expect(useComposerDraftStore.getState().getDraftSession(draftId)?.promotedTo).toEqual( + threadRef, + ); + + h.updateShell(threadRef, { + latestRun: preparingRun, + latestUserMessageAt: "2026-03-29T00:00:00.000Z", + }); + await waitForDraftHeroTransition(); + + const state = useComposerDraftStore.getState(); + expect(state.getDraftSession(draftId)).toBeNull(); + expect(state.getPromotedDraftRedirect(draftId)).toEqual(threadRef); + expect(draftFor(threadId, TEST_ENVIRONMENT_ID)?.prompt).toBe("typed during setup"); + }); + + it("holds a background submission on its draft until the send settles", async () => { + const h = draftPromotionHarness(); + const store = useComposerDraftStore.getState(); + store.setProjectDraftThreadId(projectRef, draftId, { threadId }); + beginBackgroundDraftSubmissionByRef(threadRef); + h.arrive(threadRef, { + latestRun: preparingRun, + latestUserMessageAt: "2026-03-29T00:00:00.000Z", + }); + await waitForDraftHeroTransition(); + expect(useComposerDraftStore.getState().getDraftSession(draftId)?.promotedTo).toEqual( + threadRef, + ); + + clearBackgroundDraftSubmissionByRef(threadRef); + h.flush(); + await waitForDraftHeroTransition(); + expect(useComposerDraftStore.getState().getDraftSession(draftId)).toBeNull(); + }); + + it("does not finalize a draft whose send failed and was restored", async () => { + const h = draftPromotionHarness(); + const store = useComposerDraftStore.getState(); + store.setProjectDraftThreadId(projectRef, draftId, { threadId }); + const sent = useComposerDraftStore.getState().getDraftSession(draftId)!; + h.arrive(threadRef, { + latestRun: { ...preparingRun, status: "failed" as const }, + latestUserMessageAt: null, + }); + restoreFailedDraftThread(draftId, sent, ThreadId.make("retry-thread")); + h.flush(); + await waitForDraftHeroTransition(); + expect(useComposerDraftStore.getState().getDraftSession(draftId)?.threadId).toBe( + "retry-thread", + ); + }); +}); + describe("composerDraftStore modelSelection", () => { const threadId = ThreadId.make("thread-model-options"); const threadRef = scopeThreadRef(TEST_ENVIRONMENT_ID, threadId); diff --git a/apps/web/src/composerDraftStore.ts b/apps/web/src/composerDraftStore.ts index 59188ac8d7958..6ce4d4fd4cce7 100644 --- a/apps/web/src/composerDraftStore.ts +++ b/apps/web/src/composerDraftStore.ts @@ -49,6 +49,7 @@ import type { EnvironmentShellState, EnvironmentThreadShell, } from "@t3tools/client-runtime/state/shell"; +import { waitForDraftHeroTransition } from "./components/chat/draftHeroTransition"; import { getLocalStorageItem } from "./hooks/useLocalStorage"; import { readThreadPreviewState } from "./previewStateStore"; import { resolveAppModelSelection, resolveAppModelSelectionForInstance } from "./modelSelection"; @@ -416,6 +417,11 @@ interface ComposerDraftStoreState { draftThreadsByThreadKey: Record; logicalProjectDraftThreadKeyByLogicalProjectKey: Record; backgroundSubmissionThreadKeys: Record; + /** + * Where each finalized draft went, so `/draft/` keeps leading to its thread (Back, an + * "Open draft" toast) after the draft is gone. In memory only, one small entry per sent draft. + */ + promotedDraftRedirects: Record; rewindingThreadKeys: ReadonlySet; stickyModelSelectionByProvider: Partial>; stickyOptionsByModelByProvider: Partial< @@ -430,6 +436,7 @@ interface ComposerDraftStoreState { getDraftSession: (draftId: DraftId) => DraftSessionState | null; getDraftSessionByRef: (threadRef: ScopedThreadRef) => DraftSessionState | null; getDraftIdByRef: (threadRef: ScopedThreadRef) => DraftId | null; + getPromotedDraftRedirect: (draftId: DraftId) => ScopedThreadRef | null; getDraftThreadByRef: (threadRef: ScopedThreadRef) => DraftThreadState | null; getDraftThread: (threadRef: ComposerThreadTarget) => DraftThreadState | null; listDraftThreadKeys: () => string[]; @@ -2393,6 +2400,7 @@ const composerDraftStore = create()( draftThreadsByThreadKey: {}, logicalProjectDraftThreadKeyByLogicalProjectKey: {}, backgroundSubmissionThreadKeys: {}, + promotedDraftRedirects: {}, rewindingThreadKeys: new Set(), stickyModelSelectionByProvider: {}, stickyOptionsByModelByProvider: {}, @@ -2472,6 +2480,7 @@ const composerDraftStore = create()( } return null; }, + getPromotedDraftRedirect: (draftId) => get().promotedDraftRedirects[draftId] ?? null, getDraftThread: (threadRef) => { if (typeof threadRef === "string") { return get().getDraftSession(DraftId.make(threadRef)); @@ -2758,10 +2767,16 @@ const composerDraftStore = create()( } set((state) => { const existing = state.draftThreadsByThreadKey[threadKey]; - if (!existing || !isDraftThreadPromoting(existing)) { + if (!existing?.promotedTo) { return state; } - return removeDraftThreadReferences(state, threadKey, existing.promotedTo ?? undefined); + return { + ...removeDraftThreadReferences(state, threadKey, existing.promotedTo), + promotedDraftRedirects: { + ...state.promotedDraftRedirects, + [threadKey]: existing.promotedTo, + }, + }; }); }, clearDraftThread: (threadRef) => { @@ -4204,13 +4219,6 @@ export function clearBackgroundDraftSubmissionByRef(threadRef: ScopedThreadRef): }); } -export function useBackgroundDraftSubmissionPending(threadRef: ScopedThreadRef | null): boolean { - const threadKey = threadRef ? scopedThreadKey(threadRef) : null; - return useComposerDraftStore( - (state) => threadKey !== null && state.backgroundSubmissionThreadKeys[threadKey] === true, - ); -} - export function clearComposerDraftsEnvironment(environmentId: EnvironmentId): void { useComposerDraftStore.setState((state) => { const removedThreadKeys = new Set(); @@ -4260,12 +4268,18 @@ export function clearComposerDraftsEnvironment(environmentId: EnvironmentId): vo ([threadKey]) => parseScopedThreadKey(threadKey)?.environmentId !== environmentId, ), ) as Record; + const nextPromotedDraftRedirects = Object.fromEntries( + Object.entries(state.promotedDraftRedirects).filter( + ([, promotedTo]) => promotedTo.environmentId !== environmentId, + ), + ) as Record; return { draftsByThreadKey: nextDrafts, draftThreadsByThreadKey: nextDraftThreads, logicalProjectDraftThreadKeyByLogicalProjectKey: nextLogicalMappings, backgroundSubmissionThreadKeys: nextBackgroundSubmissionThreadKeys, + promotedDraftRedirects: nextPromotedDraftRedirects, rewindingThreadKeys: new Set( [...state.rewindingThreadKeys].filter( (threadKey) => parseScopedThreadKey(threadKey)?.environmentId !== environmentId, @@ -4351,3 +4365,107 @@ export function finalizePromotedDraftThreadByRef(threadRef: ScopedThreadRef): vo } clearBackgroundDraftSubmissionByRef(threadRef); } + +type DraftPromotionShell = Pick; + +/** The server owns a draft's send once its message persisted or its run started or stopped. */ +export function resolveDraftPromotionNavigationTarget(input: { + serverThreadRef: ScopedThreadRef | null; + serverThread: DraftPromotionShell | null | undefined; + backgroundSubmissionPending: boolean; +}): ScopedThreadRef | null { + if (input.backgroundSubmissionPending) { + return null; + } + const latestRun = input.serverThread?.latestRun ?? null; + const runStarted = latestRun?.startedAt != null; + const startupStopped = + latestRun?.status === "failed" || + latestRun?.status === "interrupted" || + latestRun?.status === "cancelled"; + const messagePersisted = input.serverThread?.latestUserMessageAt != null; + return runStarted || startupStopped || messagePersisted ? input.serverThreadRef : null; +} + +/** + * Drives every draft through promotion as server shells arrive: a draft whose reserved thread + * appears on the server becomes promoting, and once the server owns its send (and any hero + * transition has played) it finalizes into that thread. The draft route follows the redirect + * that finalization records, so no route has to watch for these milestones. + */ +export function subscribeDraftThreadPromotion(input: { + readonly registry: AtomRegistry.AtomRegistry; + readonly threadRefsAtom: Atom.Atom>; + readonly threadShellAtom: (ref: ScopedThreadRef) => Atom.Atom; +}): () => void { + // Only the promotion slices: prompt edits replace the store state on every keystroke. + const promotionSlices = (state: ComposerDraftStoreState) => ({ + draftThreadsByThreadKey: state.draftThreadsByThreadKey, + backgroundSubmissionThreadKeys: state.backgroundSubmissionThreadKeys, + }); + const draftsAtom = Atom.make(promotionSlices(composerDraftStore.getState())); + const unsubscribeDrafts = composerDraftStore.subscribe((state, previous) => { + if ( + state.draftThreadsByThreadKey === previous.draftThreadsByThreadKey && + state.backgroundSubmissionThreadKeys === previous.backgroundSubmissionThreadKeys + ) { + return; + } + input.registry.set(draftsAtom, promotionSlices(state)); + }); + const threadKeysAtom = Atom.map( + input.threadRefsAtom, + (refs) => new Set(refs.map(scopedThreadKey)), + ); + const milestonesAtom = Atom.make((get) => { + const state = get(draftsAtom); + const threadKeys = get(threadKeysAtom); + const arrived: Array = []; + const owned: Array = []; + for (const [draftId, draftThread] of Object.entries(state.draftThreadsByThreadKey)) { + const ref = + draftThread.promotedTo ?? scopeThreadRef(draftThread.environmentId, draftThread.threadId); + const threadKey = scopedThreadKey(ref); + if (!threadKeys.has(threadKey)) continue; + if (!draftThread.promotedTo) { + arrived.push([DraftId.make(draftId), ref]); + continue; + } + const target = resolveDraftPromotionNavigationTarget({ + serverThreadRef: ref, + serverThread: get(input.threadShellAtom(ref)), + backgroundSubmissionPending: state.backgroundSubmissionThreadKeys[threadKey] === true, + }); + if (target) owned.push([DraftId.make(draftId), target]); + } + return { arrived, owned }; + }); + let disposed = false; + const finalizing = new Set(); + const unsubscribeMilestones = input.registry.subscribe( + milestonesAtom, + ({ arrived, owned }) => { + const store = composerDraftStore.getState(); + for (const [draftId, ref] of arrived) { + store.markDraftThreadPromoting(draftId, ref); + } + for (const [draftId, ref] of owned) { + if (finalizing.has(draftId)) continue; + finalizing.add(draftId); + void waitForDraftHeroTransition().then(() => { + finalizing.delete(draftId); + if (disposed) return; + const current = composerDraftStore.getState().draftThreadsByThreadKey[draftId]; + if (!current || !scopedThreadRefsEqual(current.promotedTo, ref)) return; + finalizePromotedDraftThreadByRef(ref); + }); + } + }, + { immediate: true }, + ); + return () => { + disposed = true; + unsubscribeMilestones(); + unsubscribeDrafts(); + }; +} diff --git a/apps/web/src/performance.bench.ts b/apps/web/src/performance.bench.ts index a8a4b54c6572c..4536c7a3122d4 100644 --- a/apps/web/src/performance.bench.ts +++ b/apps/web/src/performance.bench.ts @@ -1,4 +1,4 @@ -import { NodeId, PlanId, ProjectId, RunId } from "@t3tools/contracts"; +import { ProjectId } from "@t3tools/contracts"; import { getLatestThreadForProject, sortActiveThreadsByOrderKey, @@ -8,11 +8,7 @@ import { import { formatHourShort, formatRelativeHourShort } from "@t3tools/shared/usageFormat"; import { describe, test } from "vite-plus/test"; -import { makeThreadProjectionFixture } from "./test-fixtures"; -import { deriveActivePlanState } from "./session-logic"; - const projectId = ProjectId.make("benchmark-project"); -const runId = RunId.make("benchmark-run"); const start = Date.parse("2026-08-11T00:00:00.000Z"); const threads = Array.from({ length: 1_000 }, (_, index) => { const timestamp = new Date(start + ((index * 997) % 1_000) * 60_000).toISOString(); @@ -26,19 +22,6 @@ const threads = Array.from({ length: 1_000 }, (_, index) => { unsettledAt: null, }; }); -const baseProjection = makeThreadProjectionFixture(); -const projection = { - ...baseProjection, - plans: Array.from({ length: 5 }, (_, index) => ({ - id: PlanId.make(`plan-${index}`), - runId, - threadId: baseProjection.thread.id, - nodeId: NodeId.make("bench-node"), - status: "active" as const, - kind: "todo_list" as const, - steps: [{ id: "check", text: "Run checks", status: "running" as const }], - })), -}; const hours = Array.from({ length: 24 }, (_, index) => new Date(start + index * 3_600_000).toISOString(), ); @@ -65,11 +48,6 @@ describe("client performance", () => { getLatestThreadForProject(threads, projectId, "updated_at"); }).run(); }); - test("derive current plan from 5 normalized plans", async ({ bench }) => { - await bench("derive", () => { - deriveActivePlanState(projection, runId); - }).run(); - }); test("format 24 hourly usage labels and tooltips", async ({ bench }) => { await bench("format", () => { hours.map((hour) => [ diff --git a/apps/web/src/session-logic.test.ts b/apps/web/src/session-logic.test.ts index de8b3373e44b2..fd10c96aa1b24 100644 --- a/apps/web/src/session-logic.test.ts +++ b/apps/web/src/session-logic.test.ts @@ -5,7 +5,6 @@ import { CheckpointScopeId, NodeId, PlanId, - ProviderDriverKind, ProviderInstanceId, ProviderThreadId, RunAttemptId, @@ -24,14 +23,12 @@ import * as DateTime from "effect/DateTime"; import { describe, expect, it } from "vite-plus/test"; import { - deriveActivePlanState, deriveCanInterruptRunningThread, deriveTimelineEntriesFromVisibleTurnItems, deriveTimelineEntriesFromVisibleTurnItemsWithState, deriveRevertTurnCountByUserMessageId, derivePhase, isLatestRunSettled, - selectComposerTasksPlan, selectHandoffImageResources, selectMessageImageResources, createMessageAttachmentPreviewProjector, @@ -465,7 +462,7 @@ describe("V2 session presentation", () => { ...base("item-todo", 4), type: "todo_list" as const, planId: PlanId.make("plan-visible"), - explanation: "Keep task detail in the Tasks panel", + explanation: "Show task updates where the agent wrote them", steps: [ { id: "step-1", text: "First", status: "completed" as const }, { id: "step-2", text: "Second", status: "pending" as const }, @@ -526,6 +523,7 @@ describe("V2 session presentation", () => { ["event", requestItem.id], ["work", commandItem.id], ["event", resultItem.id], + ["work", todoItem.id], ["work", errorItem.id], ["work", threadCreatedItem.id], ]); @@ -545,7 +543,7 @@ describe("V2 session presentation", () => { expect(commandEntry.entry.command).toBe(commandItem.input); expect(commandEntry.entry.detail).toBeUndefined(); } - const errorEntry = entries[4]; + const errorEntry = entries[5]; expect(errorEntry?.kind).toBe("work"); if (errorEntry?.kind === "work") { expect(errorEntry.entry.projectedItem).toBe(visibleTurnItems[5]); @@ -554,7 +552,7 @@ describe("V2 session presentation", () => { expect(errorEntry.entry.tone).toBe("info"); expect(errorEntry.entry.toolLifecycleStatus).toBe("failed"); } - const threadCreatedEntry = entries[5]; + const threadCreatedEntry = entries[6]; expect(threadCreatedEntry?.kind).toBe("work"); if (threadCreatedEntry?.kind === "work") { expect(threadCreatedEntry.entry.projectedItem?.item.type).toBe("thread_created"); @@ -562,7 +560,7 @@ describe("V2 session presentation", () => { }); it.each(["pending", "running", "completed"] as const)( - "keeps %s task progress available to the composer and out of the timeline", + "shows a %s todo update in the timeline where the agent wrote it", (stepStatus) => { const projection = makeThreadProjectionFixture(); const now = DateTime.makeUnsafe("2026-09-04T00:00:00.000Z"); @@ -615,46 +613,17 @@ describe("V2 session presentation", () => { optimisticMessages: [], plans, }), - ).toEqual([]); - expect( - deriveActivePlanState({ ...projection, plans, turnItems: [item] }, runId), - ).toMatchObject({ - runId, - steps: [ - { - step: "Verify the change", - status: stepStatus === "running" ? "inProgress" : stepStatus, + ).toMatchObject([ + { + kind: "work", + entry: { + label: stepStatus === "completed" ? "Tasks 1/1" : "Tasks 0/1 · Verify the change", }, - ], - }); + }, + ]); }, ); - it("preserves independently derived durations for repeated plan-step labels", () => { - const projection = makeThreadProjectionFixture(); - const runId = RunId.make("run-timed-tasks"); - const planId = PlanId.make("plan-timed-tasks"); - const plan = { - id: planId, - threadId: projection.thread.id, - runId, - nodeId: NodeId.make("node-timed-tasks"), - kind: "todo_list" as const, - status: "active" as const, - steps: [ - { id: "verify-a", text: "Verify", status: "completed" as const, durationMs: 3_000 }, - { id: "verify-b", text: "Verify", status: "completed" as const, durationMs: 4_000 }, - { id: "report", text: "Report", status: "pending" as const }, - ], - }; - - expect(deriveActivePlanState({ ...projection, plans: [plan] }, runId)?.steps).toEqual([ - { step: "Verify", status: "completed", durationMs: 3_000 }, - { step: "Verify", status: "completed", durationMs: 4_000 }, - { step: "Report", status: "pending" }, - ]); - }); - it("waits for a dispatched turn item before adding queued input to the timeline", () => { const projection = makeThreadProjectionFixture(); const now = DateTime.makeUnsafe("2026-06-20T00:00:00.000Z"); @@ -1041,190 +1010,6 @@ describe("V2 session presentation", () => { }); }); -describe("composer tasks drawer", () => { - const projection = makeThreadProjectionFixture(); - const now = projection.updatedAt; - - function providerThread(id: string, driver: string) { - return { - id: ProviderThreadId.make(id), - driver: ProviderDriverKind.make(driver), - providerInstanceId: ProviderInstanceId.make(driver), - providerSessionId: null, - appThreadId: projection.thread.id, - ownerNodeId: null, - nativeThreadRef: null, - nativeConversationHeadRef: null, - status: "idle" as const, - firstRunOrdinal: null, - lastRunOrdinal: null, - handoffIds: [], - forkedFrom: null, - createdAt: now, - updatedAt: now, - }; - } - - function run(id: string, ordinal: number, providerThreadId: string | null) { - return { - id: RunId.make(id), - threadId: projection.thread.id, - ordinal, - providerInstanceId: projection.thread.providerInstanceId, - modelSelection: projection.thread.modelSelection, - providerThreadId: providerThreadId === null ? null : ProviderThreadId.make(providerThreadId), - userMessageId: MessageId.make(`message-${id}`), - rootNodeId: null, - activeAttemptId: null, - status: "completed" as const, - requestedAt: now, - startedAt: now, - completedAt: now, - checkpointId: null, - contextHandoffId: null, - }; - } - - const openList = { - createdAt: "2026-06-20T00:00:00.000Z", - runId: RunId.make("run-1"), - steps: [ - { step: "Inspect", status: "completed" as const }, - { step: "Implement", status: "inProgress" as const }, - { step: "Verify", status: "pending" as const }, - ], - }; - const completedList = { - ...openList, - steps: openList.steps.map((step) => ({ ...step, status: "completed" as const })), - }; - - it.each(["claudeAgent", "codex"])( - "shows %s tasks through the run lifecycle, retaining unfinished tasks only for Claude", - (driver) => { - const firstRun = run("run-1", 1, driver); - const settled = { - ...projection, - providerThreads: [providerThread(driver, driver)], - runs: [firstRun], - }; - const running = { - ...settled, - runs: [{ ...firstRun, status: "running" as const, completedAt: null }], - }; - expect(selectComposerTasksPlan(running, openList, firstRun.id, false)).toBe(openList); - expect(selectComposerTasksPlan(running, completedList, firstRun.id, false)).toBe( - completedList, - ); - - const retainedList = driver === "claudeAgent" ? openList : null; - expect(selectComposerTasksPlan(settled, openList, firstRun.id, true)).toBe(retainedList); - expect(selectComposerTasksPlan(settled, completedList, firstRun.id, true)).toBeNull(); - - const nextRun = { - ...run("run-2", 2, driver), - status: "running" as const, - completedAt: null, - }; - const later = { ...settled, runs: [...settled.runs, nextRun] }; - expect(selectComposerTasksPlan(later, openList, nextRun.id, false)).toBe(retainedList); - }, - ); - - it("retains the newest unfinished Claude list after loading plans in snapshot order", () => { - const olderRun = run("run:ordinal:8", 8, "claudeAgent"); - const planRun = run("run:ordinal:12", 12, "claudeAgent"); - const laterRun = { - ...run("run:ordinal:13", 13, "claudeAgent"), - status: "running" as const, - completedAt: null, - }; - const newestPlan = { - id: PlanId.make("plan:run:ordinal:12"), - threadId: projection.thread.id, - runId: planRun.id, - nodeId: NodeId.make("node:ordinal:12"), - kind: "todo_list" as const, - status: "active" as const, - steps: [{ id: "new", text: "Finish the current task", status: "pending" as const }], - }; - for (const status of ["superseded", "active"] as const) { - const snapshot = { - ...projection, - providerThreads: [providerThread("claudeAgent", "claudeAgent")], - runs: [olderRun, planRun, laterRun], - plans: [ - newestPlan, - { - ...newestPlan, - id: PlanId.make("plan:run:ordinal:8"), - runId: olderRun.id, - nodeId: NodeId.make("node:ordinal:8"), - status, - steps: [{ id: "old", text: "Stale task", status: "pending" as const }], - }, - ], - }; - const plan = deriveActivePlanState(snapshot, laterRun.id); - expect - .soft(selectComposerTasksPlan(snapshot, plan, laterRun.id, false), status) - .toMatchObject({ - runId: planRun.id, - steps: [{ step: "Finish the current task", status: "pending" }], - }); - } - }); - - it.each(["codex", "claudeAgent"])( - "drops retained Claude tasks only after a new %s session actually starts", - (driver) => { - const settled = { - ...projection, - providerThreads: [ - providerThread("claude-original", "claudeAgent"), - providerThread("next-session", driver), - ], - runs: [run("run-1", 1, "claude-original")], - }; - const nextRun = run("run-2", 2, "next-session"); - for (const status of ["queued", "cancelled"] as const) { - const unstarted = { - ...settled, - runs: [ - ...settled.runs, - { - ...nextRun, - status, - startedAt: null, - completedAt: status === "cancelled" ? now : null, - }, - ], - }; - expect - .soft( - selectComposerTasksPlan(unstarted, openList, nextRun.id, status === "cancelled"), - `A ${status} run with an assigned provider thread has not switched sessions`, - ) - .toBe(openList); - } - - const started = { - ...settled, - runs: [...settled.runs, { ...nextRun, status: "running" as const, completedAt: null }], - }; - expect(selectComposerTasksPlan(started, openList, nextRun.id, false)).toBeNull(); - expect( - selectComposerTasksPlan( - { ...settled, runs: [...settled.runs, nextRun] }, - openList, - nextRun.id, - true, - ), - ).toBeNull(); - }, - ); -}); - describe("native provider presentation in the v2 timeline", () => { const timestamp = DateTime.makeUnsafe("2026-09-04T12:00:00.000Z"); const base = { diff --git a/apps/web/src/session-logic.ts b/apps/web/src/session-logic.ts index f386a858818b8..7fef6c52fe31d 100644 --- a/apps/web/src/session-logic.ts +++ b/apps/web/src/session-logic.ts @@ -7,7 +7,6 @@ import { type OrchestrationV2PlanArtifact, type OrchestrationV2ProjectedTurnItem, type OrchestrationV2RunAttempt, - type OrchestrationV2ThreadProjection, type OrchestrationV2TurnItem, type PlanId, type RunId, @@ -99,17 +98,6 @@ export interface WorkLogEntry { export type PendingApproval = ThreadPendingApproval; export type PendingUserInput = ThreadPendingUserInput; -export interface ActivePlanState { - readonly createdAt: string; - readonly runId: RunId | null; - readonly explanation?: string | null; - readonly steps: Array<{ - readonly step: string; - readonly status: "pending" | "inProgress" | "completed"; - readonly durationMs?: number; - }>; -} - export interface LatestProposedPlanState { readonly id: PlanId; readonly createdAt: string; @@ -251,71 +239,6 @@ export function derivePendingUserInputs( return [...inputs].toSorted((left, right) => left.createdAt.localeCompare(right.createdAt)); } -export function deriveActivePlanState( - projection: ThreadStructure | null, - latestRunId: RunId | undefined, -): ActivePlanState | null { - if (projection === null) return null; - const plans = projection.plans - .filter((plan) => plan.kind === "todo_list") - .filter((plan) => plan.status !== "superseded"); - const runOrdinals = new Map( - projection.runs.map((run) => [run.id, run.ordinal]), - ); - const plan = - plans.findLast((candidate) => candidate.runId === latestRunId) ?? - plans.reduce<(typeof plans)[number] | null>( - (latest, candidate) => - latest === null || - (runOrdinals.get(candidate.runId) ?? -1) >= (runOrdinals.get(latest.runId) ?? -1) - ? candidate - : latest, - null, - ); - if (plan === null || plan.steps.length === 0) return null; - return { - createdAt: planItemTime(projection, plan), - runId: plan.runId, - explanation: plan.explanation ?? null, - steps: plan.steps.map(({ text, status, durationMs }) => ({ - step: text, - status: status === "running" ? "inProgress" : status, - ...(durationMs === undefined ? {} : { durationMs }), - })), - }; -} - -// Claude's unfinished tasks belong to the provider session, not just the turn. -export function selectComposerTasksPlan( - projection: ThreadStructure | null, - plan: ActivePlanState | null, - activeRunId: RunId | null, - activeRunSettled: boolean, -): ActivePlanState | null { - if (projection === null || plan === null) return null; - if (activeRunId !== null && !activeRunSettled && plan.runId === activeRunId) return plan; - if (plan.steps.every((step) => step.status === "completed")) return null; - const planProviderThreadId = projection.runs.find( - (run) => run.id === plan.runId, - )?.providerThreadId; - if (planProviderThreadId === undefined || planProviderThreadId === null) return null; - const planDriver = projection.providerThreads.find( - (providerThread) => providerThread.id === planProviderThreadId, - )?.driver; - if (planDriver !== "claudeAgent") return null; - let latestStartedRun: OrchestrationV2ThreadProjection["runs"][number] | null = null; - for (const run of projection.runs) { - if ( - run.startedAt !== null && - run.providerThreadId !== null && - (latestStartedRun === null || run.ordinal > latestStartedRun.ordinal) - ) { - latestStartedRun = run; - } - } - return latestStartedRun?.providerThreadId === planProviderThreadId ? plan : null; -} - function planItemTime( projection: ThreadStructure, plan: Pick, @@ -589,6 +512,17 @@ function projectedWorkEntry(row: OrchestrationV2ProjectedTurnItem): WorkLogEntry toolData: { input: item.input, output: item.output }, }; } + case "todo_list": { + // Each todo update is a quiet row where the agent wrote it; it opens to every step. + const done = item.steps.filter((step) => step.status === "completed").length; + const current = + item.steps.find((step) => step.status === "running") ?? + item.steps.find((step) => step.status === "pending"); + return { + ...common, + label: `Tasks ${done}/${item.steps.length}${current ? ` · ${current.text}` : ""}`, + }; + } case "approval_request": return { ...common, @@ -666,7 +600,7 @@ export function deriveTimelineEntriesFromVisibleTurnItems( for (const row of input.visibleTurnItems) { const { item } = row; if (turnItemIsWorkspacePreparation(item)) continue; - if (item.type === "todo_list" || item.type === "checkpoint") continue; + if (item.type === "checkpoint") continue; if (item.type === "user_message" && foldedAnswerMessageIds.has(item.messageId)) continue; const createdAt = projectedItemCreatedAt(row); const attempt = resolveAttempt(item); diff --git a/apps/web/src/versionSkew.ts b/apps/web/src/versionSkew.ts index aaf1f5dc2e95b..661c0c4efca9f 100644 --- a/apps/web/src/versionSkew.ts +++ b/apps/web/src/versionSkew.ts @@ -114,10 +114,6 @@ export function manualServerUpdateCommand( return `${runner} t3@${targetVersion}`; } -export function serverUpdateGuidance(capability: ServerSelfUpdateCapability): string { - return capability === "desktop-managed" ? "Update the desktop app" : "Update to stay in sync"; -} - export function buildVersionMismatchDismissalKey( environmentId: EnvironmentId, mismatch: Pick, diff --git a/docs/user/composer.md b/docs/user/composer.md index acd49abdebf54..35b425faf31d1 100644 --- a/docs/user/composer.md +++ b/docs/user/composer.md @@ -54,7 +54,7 @@ See [images and videos](#images-and-videos-in-messages) for previewing and savin On web and desktop, choose **Settings → Chat → Follow-up behavior** to queue new messages for a later turn or steer the running turn immediately. The setting applies to this client; already queued messages keep their place. Queued messages -are saved on the server and can be edited, reordered, or removed above the composer. +are saved on the server and can be edited, reordered, or removed before they send. When Enter sends, `Cmd+Enter` on macOS or `Ctrl+Enter` on Windows and Linux uses the opposite action: it steers when your default is Queue and queues when your default is Steer. @@ -72,7 +72,7 @@ Press `Option+Up` on macOS or `Alt+Up` on Windows and Linux with the cursor at t start of the composer to edit the most recently queued message. Change `thread.editQueuedMessage` to use another shortcut. -Mobile has the same choice under **Settings → Follow-ups**. While a turn is +Mobile has the same choice under **Settings → Chat**. While a turn is running the send button shows which action it will take. Long-press it to use the other action for a single message, or hold `Cmd` while sending from a hardware keyboard. The button only offers Steer when the running agent supports it. @@ -204,19 +204,20 @@ Steer. Click it or press your send shortcut to use that action. Hold `Cmd` on ma Windows and Linux to switch the button to the opposite action, then click, or use the opposite-action shortcut described above. -Queued messages appear above the composer. Rows show a thumbnail of any attached image alongside -the text. Drag a row by its handle to reorder it, use the handle's arrow keys, promote the message -to a steer, or remove it. +On web and desktop, queued messages appear at the end of the thread under **Up next**, as dashed +messages that have not been sent yet. On mobile they appear above the composer. Each shows its text +and any attached images. Drag a message by its handle to reorder it, use the handle's arrow keys, +promote the message to a steer, or remove it. If you stop the agent or the server restarts, queued messages keep their order and are held. Press **Resume** in an empty composer on web and desktop, or **Resume queue** on mobile, to continue. Sending a new message also resumes the queue, unless it steers a turn that is already running. You can edit, reorder, or remove held messages without starting them. -The pencil on a queued row opens that message in the composer for editing. The original message -stays in the queue until you save, and its row is highlighted while you edit. The message's +The pencil on a queued message opens it in the composer for editing. The original message +stays in the queue until you save, and it is highlighted while you edit. The message's attachments appear above the text with a remove control, and new images can be added the usual way. -The checkmark saves the queued message in place; **Cancel** on its row leaves it unchanged. Whatever +The checkmark saves the queued message in place; **Cancel** next to it leaves it unchanged. Whatever you had typed in the composer before starting the edit is restored afterwards. If the queued message starts or is removed while you are editing, the edit ends: changed content moves into the composer when it is empty, and is discarded otherwise. @@ -248,7 +249,8 @@ Claude instances can also compact idle threads for you. See With Codex and Claude, send `/goal` followed by what "done" means, for example `/goal all tests in packages/api pass`. The agent keeps working across turns until it judges the goal met. The thread shows **Goal** while it works, and a -row above the composer shows the goal and its progress. +line at the end of the thread (above the composer on mobile) shows the goal and +its progress. - `/goal` alone shows the current goal. `/goal clear` removes it. - Codex also supports `/goal pause` and `/goal resume`. Stopping a Codex goal diff --git a/docs/user/cursor.md b/docs/user/cursor.md index 3def8de7c02a2..6a6b1c8f284b3 100644 --- a/docs/user/cursor.md +++ b/docs/user/cursor.md @@ -19,7 +19,7 @@ not expose yet. Choose **Sign in**, then open the sign-in page and complete it in your browser. T3 Code updates automatically when sign-in finishes. This works when connected to a remote environment too. -On mobile, use **Settings > Provider accounts** for an already configured Cursor instance. +On mobile, use **Settings > Providers** for an already configured Cursor instance. Each provider instance keeps its own login on the environment that runs it. Your Cursor editor and CLI login are separate. A configured `CURSOR_API_KEY` overrides browser sign-in; remove that override diff --git a/docs/user/project-settings.md b/docs/user/project-settings.md index 286ecb7a012d5..718f8723468a0 100644 --- a/docs/user/project-settings.md +++ b/docs/user/project-settings.md @@ -37,10 +37,10 @@ machine's setting. Every other provider setting stays per machine. On mobile, open **Settings** and use the filter in its header to choose connected environments and a project. The filter stays available in server-setting pages. With **All projects** selected, -the **Server settings** categories and auto-settle controls in **Thread behavior** edit the -selected environments' defaults. Choosing a project edits its overrides on the selected +the server-setting pages, such as Threads, Source control and Worktrees, edit the selected +environments' defaults. Choosing a project edits its overrides on the selected environments. Use **Use defaults** in a page to remove that page's project overrides. -Open **Settings → Projects & threads → Overview** to rename the project across its selected +Open **Settings → Projects** to rename the project across its selected connected checkouts and see where those checkouts live. Settings that are environment-wide stay read-only while a project is selected. When selected targets disagree, a control shows **Mixed** until you choose one value. Appearance, keyboard, diff --git a/docs/user/providers-acp.md b/docs/user/providers-acp.md index aef165d96eb4d..c40d2e0fec69a 100644 --- a/docs/user/providers-acp.md +++ b/docs/user/providers-acp.md @@ -54,7 +54,7 @@ but keeps package installs. To use an existing local binary, set **Executable ov Open the agent's account section in **Settings → Providers** on web or desktop. Choose **Sign in** and, if the agent offers several methods, select one. For an installed, configured -provider, mobile also offers **Settings → Provider accounts**. +provider, mobile also offers **Settings → Providers**. Browser sign-in shows the agent's URL and waits for you to open or copy it before telling the agent to proceed. The page opens on your device, while the agent runs on the environment. diff --git a/docs/user/providers-antigravity.md b/docs/user/providers-antigravity.md index 5d675e6eaa735..0b1cd2f2c6da1 100644 --- a/docs/user/providers-antigravity.md +++ b/docs/user/providers-antigravity.md @@ -10,7 +10,7 @@ On web or desktop, open **Settings > Providers**, choose the environment that ru your project, and enable Antigravity. Install its runtime there, then choose **Sign in** and complete the browser sign-in. Wait for T3 Code to confirm account access and load models before starting a thread. Once the runtime is installed, -you can also sign in from **Settings > Provider accounts** in the mobile app. +you can also sign in from **Settings > Providers** in the mobile app. Installation continues if you leave settings or reconnect. Setup requires permission to operate the environment; update an older server if it does not offer @@ -134,7 +134,7 @@ until a session, a refresh, or a sign-out reports something new. To check access and reload models, use **Refresh provider status** in web or desktop provider settings, or **Refresh models** in mobile thread settings. If asked to -sign in again, use provider settings on web or desktop, or **Provider accounts** on mobile. +sign in again, use provider settings on web or desktop, or **Settings > Providers** on mobile. If Google reports `SUBSCRIPTION_REQUIRED`, an account restriction, or a usage limit, follow the provider's message and any retry time. See [Google's account plans][plans] diff --git a/docs/user/providers-claude.md b/docs/user/providers-claude.md index 791951c199359..44ba9fa3b12c0 100644 --- a/docs/user/providers-claude.md +++ b/docs/user/providers-claude.md @@ -97,8 +97,8 @@ tool, which refuses skills reserved for manual invocation. To show Claude task lists in the web and desktop apps, add `CLAUDE_CODE_ENABLE_TODO_TOOLS=1` under **Variables** in the Claude instance's -**Environment** section in **Settings > Providers**. Unfinished tasks stay visible -between turns in the same Claude session. +**Environment** section in **Settings > Providers**. Each update shows as a Tasks +row in the thread; open it to see every step. ## OpenRouter diff --git a/docs/user/thread-sidebar.md b/docs/user/thread-sidebar.md index 60cf5a9cb0a14..8bf55006bd7d0 100644 --- a/docs/user/thread-sidebar.md +++ b/docs/user/thread-sidebar.md @@ -127,7 +127,7 @@ answer. The Working section lists the thread you last sent work to first. Pinned the pinned section. This is on by default. Turn it off with **Settings → General → Working section** on web and desktop, -or **Settings → Thread behavior → Working section** on iOS and Android. Each device keeps its own +or **Settings → General → Working section** on iOS and Android. Each device keeps its own choice. While this is on, the active list is ordered by when each thread last came back to you, so you @@ -170,7 +170,7 @@ choose **Auto-settle behavior**, and pick **Disabled**. The current option is ch **Enabled** to return to the usual rules. Manual settle, snooze, and archive still work while it is disabled. -Change these rules in **Settings → Threads** on web and desktop, or **Settings → Thread behavior** on mobile. +Change these rules in **Settings → Threads**. They continue to run when your apps are closed. On web and desktop, choose an environment at the top to change only its rules, or **All environments** to update connected environments together. Mixed values show where the selected environments disagree. Mobile applies these @@ -219,8 +219,7 @@ the continuation finishes. If the queue was held by a restart, resume it then. When the provider reports a reset time, choose **Resume at reset** to schedule a continuation. You can cancel it from the thread. Enable **Resume after -usage limits** in **Settings → Threads** on web and desktop, or **Settings → Thread -behavior** on mobile, to schedule limit stops by default. +usage limits** in **Settings → Threads** to schedule limit stops by default. The environment must be running when the reset arrives; it resumes overdue continuations after a restart. Stopping the thread, sending a new message, archiving, or settling it prevents a pending continuation from starting. diff --git a/docs/user/updating.md b/docs/user/updating.md index a8945c5ced2a3..e00329023afdc 100644 --- a/docs/user/updating.md +++ b/docs/user/updating.md @@ -1,9 +1,8 @@ # Updating T3 Code The app you use and the server running your agents can be on different machines. -When a server is behind your web or desktop app, an update notice appears in the -conversation and **Settings → Environments**. Update the machine named in that -notice. +When a server is behind your web or desktop app, the update button at the bottom +of the sidebar and **Settings → Environments** offer to update it. ## Update everything at once @@ -25,8 +24,8 @@ restarts. Server updates appear only after that version is published to npm. Remote desktop apps do not wait for npm. The confirmation lists each machine it skips -and why, such as a machine that is offline or needs a manual update. Use the -notice or **Settings → Environments** for those. +and why, such as a machine that is offline or needs a manual update. Use +**Settings → Environments** for those. If a desktop app restarts on its old version, T3 Code tells you the update did not apply. It does not install that version again on its own, even when another