TypeScript
fix(mobile): expose background work and thread status actions (#21395)
mariafe414ebdd3cb
diff --git a/apps/mobile/src/Stack.tsx b/apps/mobile/src/Stack.tsxindex 5589ad38235..13240c54a97 100644--- a/apps/mobile/src/Stack.tsx+++ b/apps/mobile/src/Stack.tsx@@ -71,6 +71,7 @@ import { GitConfirmSheet } from "./features/threads/git/GitConfirmSheet";import { GitOverviewSheet } from "./features/threads/git/GitOverviewSheet";import { ThreadPullRequestsSheet } from "./features/threads/ThreadPullRequestsSheet";import { ThreadAgentsSheet } from "./features/threads/ThreadAgentsSheet";+import { ThreadBackgroundWorkSheet } from "./features/threads/ThreadBackgroundWorkSheet";import { ThreadQueueSheet } from "./features/threads/ThreadQueueControl";import { ThreadRouteScreen } from "./features/threads/ThreadRouteScreen";import { McpAppFullscreenScreen } from "./features/threads/McpAppFullscreenScreen";@@ -558,6 +559,7 @@ const WORKSPACE_OVERLAY_ROUTES = new Set(["SettingsLegal","SettingsSheet","ThreadAgents",+ "ThreadBackgroundWork","ThreadPullRequests","ThreadQueue","ThreadReviewComment",@@ -869,6 +871,15 @@ const RootStackConfig = createWorkspaceStackNavigator({sheetGrabberVisible: true,},}),+ ThreadBackgroundWork: createNativeStackScreen({+ screen: ThreadBackgroundWorkSheet,+ options: {+ ...FORM_SHEET_PRESENTATION_OPTIONS,+ headerShown: false,+ sheetAllowedDetents: [0.5, 0.9],+ sheetGrabberVisible: true,+ },+ }),ThreadAgents: createNativeStackScreen({screen: ThreadAgentsSheet,options: {diff --git a/apps/mobile/src/features/threads/ThreadBackgroundWorkSheet.tsx b/apps/mobile/src/features/threads/ThreadBackgroundWorkSheet.tsxnew file mode 100644index 00000000000..c4db6d7a937--- /dev/null+++ b/apps/mobile/src/features/threads/ThreadBackgroundWorkSheet.tsx@@ -0,0 +1,143 @@+import { useAtomValue } from "@effect/atom-react";+import { StackActions, useNavigation, type StaticScreenProps } from "@react-navigation/native";+import { scopeThreadRef } from "@t3tools/client-runtime/environment";+import {+ presentPendingBackgroundWork,+ type PendingBackgroundWorkItem,+} from "@t3tools/client-runtime/state/thread-execution";+import type { EnvironmentId, ThreadId } from "@t3tools/contracts";+import * as Haptics from "expo-haptics";+import { Platform, Pressable, ScrollView, View } from "react-native";+import { ScreenStack } from "react-native-screens";+import { useSafeAreaInsets } from "react-native-safe-area-context";++import { AndroidSheetHeader } from "../../components/ui/AndroidScreenHeader";+import { SymbolView } from "../../components/ui/AppSymbol";+import { AppText as Text } from "../../components/ui/AppText";+import { ScreenContent } from "../../components/ui/ScreenContent";+import { NativeStackScreenOptions, nativeHeaderScrollEdgeEffects } from "../../native/StackHeader";+import { NativeHeader, NativeScreen } from "../../native/ThemedScreenStack";+import { environmentThreadShells } from "../../state/threads";+import { useAdaptiveWorkspaceLayout } from "../layout/AdaptiveWorkspaceLayout";++const HEADER_SCROLL_EDGE_EFFECTS = nativeHeaderScrollEdgeEffects(Platform.OS, Platform.Version);+const KIND_LABELS = {+ subagent: "Subagent",+ command: "Command",+ monitor: "Monitor",+ background_task: "Background task",+} as const;++type BackgroundWorkTarget = { readonly environmentId: EnvironmentId; readonly threadId: ThreadId };++export function ThreadBackgroundWorkSheet({ route }: StaticScreenProps<BackgroundWorkTarget>) {+ const { layout } = useAdaptiveWorkspaceLayout();+ const navigation = useNavigation();+ const insets = useSafeAreaInsets();+ const target = route.params;+ const thread = useAtomValue(+ environmentThreadShells.threadShellAtom(scopeThreadRef(target.environmentId, target.threadId)),+ );+ const presentation = presentPendingBackgroundWork(thread?.pendingBackgroundTasks ?? []);+ const openThread = (threadId: ThreadId) => {+ void Haptics.selectionAsync();+ // A thread replaces the leaf sheet so workspace back navigation still works.+ navigation.dispatch(+ StackActions.replace("Thread", { environmentId: target.environmentId, threadId }),+ );+ };+ const content = (+ <ScrollView+ nestedScrollEnabled+ className="flex-1"+ contentInsetAdjustmentBehavior={Platform.OS === "ios" ? "automatic" : "never"}+ contentContainerClassName="px-5 pb-6"+ contentContainerStyle={{ paddingBottom: Math.max(insets.bottom, 16) + 8 }}+ >+ {presentation === null ? (+ <Text className="pt-6 text-center text-sm text-foreground-muted">+ Nothing running in the background.+ </Text>+ ) : (+ presentation.items.map((item) => (+ <BackgroundWorkRow key={item.taskId} item={item} onOpen={openThread} />+ ))+ )}+ </ScrollView>+ );+ if (Platform.OS === "ios") {+ return (+ <View collapsable={false} className="flex-1 bg-sheet">+ <ScreenStack style={{ flex: 1 }}>+ <NativeScreen+ activityState={2}+ enabled+ isNativeStack+ screenId="thread-background-work-sheet-native"+ scrollEdgeEffects={HEADER_SCROLL_EDGE_EFFECTS}+ className="flex-1 bg-sheet"+ >+ {content}+ <NativeHeader+ backgroundColor="rgba(0,0,0,0)"+ tintColorClassName="accent-foreground"+ hideBackButton+ hideShadow={false}+ title="Background work"+ titleColorClassName="accent-foreground"+ titleFontSize={18}+ titleFontWeight="800"+ translucent+ />+ </NativeScreen>+ </ScreenStack>+ </View>+ );+ }+ return (+ <View collapsable={false} className="flex-1 bg-sheet">+ <NativeStackScreenOptions options={{ sheetCornerRadius: 28 }} />+ <AndroidSheetHeader title="Background work" onBack={() => navigation.goBack()} />+ <ScreenContent insetHorizontal={layout.usesSplitView}>{content}</ScreenContent>+ </View>+ );+}++function BackgroundWorkRow(props: {+ readonly item: PendingBackgroundWorkItem;+ readonly onOpen: (threadId: ThreadId) => void;+}) {+ const { item } = props;+ const childThreadId = item.childThreadId;+ const row = (+ <View className="flex-row items-center gap-3 border-b border-border py-3.5">+ <SymbolView+ name={+ item.kind === "subagent" ? "person.2" : item.kind === "monitor" ? "clock" : "terminal"+ }+ size={15}+ tintColorClassName="accent-foreground-muted"+ type="monochrome"+ />+ <View className="min-w-0 flex-1">+ <Text className="font-t3-medium text-sm text-foreground">{item.label}</Text>+ <Text className="text-xs text-foreground-muted">{KIND_LABELS[item.kind]}</Text>+ </View>+ {childThreadId === undefined ? null : (+ <SymbolView name="chevron.right" size={12} tintColorClassName="accent-icon-subtle" />+ )}+ </View>+ );+ return childThreadId === undefined ? (+ <View accessible>{row}</View>+ ) : (+ <Pressable+ accessibilityRole="link"+ accessibilityLabel={`Open subagent ${item.label}`}+ onPress={() => props.onOpen(childThreadId)}+ className="active:opacity-70"+ >+ {row}+ </Pressable>+ );+}diff --git a/apps/mobile/src/features/threads/ThreadDetailScreen.tsx b/apps/mobile/src/features/threads/ThreadDetailScreen.tsxindex d32c35f6c7d..9bd8c04d84e 100644--- a/apps/mobile/src/features/threads/ThreadDetailScreen.tsx+++ b/apps/mobile/src/features/threads/ThreadDetailScreen.tsx@@ -1,4 +1,8 @@-import { settlePromise, squashAtomCommandFailure } from "@t3tools/client-runtime/state/runtime";+import {+ isAtomCommandInterrupted,+ settlePromise,+ squashAtomCommandFailure,+} from "@t3tools/client-runtime/state/runtime";import { AsyncResult } from "effect/reactivity";import * as Dialog from "../../components/ui/Dialog";import { useAtomValue } from "@effect/atom-react";@@ -8,7 +12,13 @@ import {useThreadShell,} from "../../state/entities";import { UsageLimitRecoveryCard } from "./UsageLimitRecoveryCard";-import { StackActions, useNavigation } from "@react-navigation/native";+import { StackActions, useFocusEffect, useNavigation } from "@react-navigation/native";+import {+ effectiveSnoozed,+ threadWokeAt,+ isThreadWokeUnseen,+ snoozeWakeLabel,+} from "@t3tools/client-runtime/state/thread-settled";import type { WorktreeSetupCardProps } from "./worktree-setup-card";import type { ComposerTextPaste } from "../../native/T3ComposerEditor.types";import { type EnvironmentConnectionPhase } from "@t3tools/client-runtime/connection";@@ -516,6 +526,96 @@ export const ThreadDetailScreen = function ThreadDetailScreen(props: ThreadDetai}})();const threadSyncLabel = useDelayedStatus(selectedThreadKey, realThreadSyncLabel);+ const interruptThreadTurn = useAtomCommand(threadEnvironment.interruptTurn, {+ reportFailure: false,+ });+ const unsnoozeThread = useAtomCommand(threadEnvironment.unsnooze, { reportFailure: false });+ const unsettleThread = useAtomCommand(threadEnvironment.unsettle, { reportFailure: false });+ const updateMetadata = useAtomCommand(threadEnvironment.updateMetadata, { reportFailure: false });+ const visitThread = useAtomCommand(threadEnvironment.visit, { reportFailure: false });+ const [statusRequest, setStatusRequest] = useState<{ threadKey: string } | null>(null);+ const statusPending = statusRequest?.threadKey === selectedThreadKey;+ const [lifecycleNow, setLifecycleNow] = useState(() => new Date().toISOString());+ useFocusEffect(+ useCallback(() => {+ setLifecycleNow(new Date().toISOString());+ const timer = setInterval(() => setLifecycleNow(new Date().toISOString()), 60_000);+ return () => clearInterval(timer);+ }, []),+ );+ const snoozed =+ props.serverConfig?.environment.capabilities.threadSnooze === true &&+ effectiveSnoozed(props.selectedThread, { now: lifecycleNow });+ const snoozedUntil = props.selectedThread.snoozedUntil;+ useEffect(() => {+ if (!snoozed || snoozedUntil === null) return;+ const timer = setTimeout(+ () => setLifecycleNow(new Date().toISOString()),+ Math.min(Math.max(0, Date.parse(snoozedUntil) - Date.now()) + 50, 2_147_483_647),+ );+ return () => clearTimeout(timer);+ // oxlint-disable-next-line react/exhaustive-effect-dependencies -- Re-arm if timer clamping fires before the wake time.+ }, [snoozed, snoozedUntil, lifecycleNow]);+ const settled =+ props.serverConfig?.environment.capabilities.threadSettlement === true &&+ props.selectedThread.settledOverride === "settled";+ const wokeAt =+ props.serverConfig?.environment.capabilities.threadSnooze === true+ ? threadWokeAt(props.selectedThread, { now: lifecycleNow })+ : null;+ const woke = isThreadWokeUnseen({+ wokeAt,+ settled,+ lastVisitedAt: props.selectedThread.lastVisitedAt,+ latestRunCompletedAt: props.selectedThread.latestRun?.completedAt ?? null,+ });+ const runStatusAction = async (action: "stop" | "wake" | "unsettle" | "dismiss") => {+ if (statusPending || !props.canOperateThread) return;+ const request = { threadKey: selectedThreadKey };+ setStatusRequest(request);+ const target = {+ environmentId: props.environmentId,+ input: { threadId: props.selectedThread.id },+ };+ const recovery = props.selectedThread.limitRecovery;+ const recoveryOwnsSnooze =+ recovery?.snooze === true &&+ recovery.runId === props.selectedThread.latestRun?.runId &&+ snoozedUntil !== null &&+ Date.parse(snoozedUntil) === Date.parse(recovery.resetAt);+ const result =+ action === "stop"+ ? await interruptThreadTurn(target)+ : action === "wake"+ ? recoveryOwnsSnooze+ ? await updateMetadata({+ ...target,+ input: {+ ...target.input,+ limitRecovery: {+ runId: recovery.runId,+ resetAt: recovery.resetAt,+ snooze: false,+ },+ },+ })+ : await unsnoozeThread({ ...target, input: { ...target.input, reason: "user" } })+ : action === "unsettle"+ ? await unsettleThread({ ...target, input: { ...target.input, reason: "user" } })+ : await visitThread({+ ...target,+ input: { ...target.input, visitedAt: wokeAt ?? lifecycleNow },+ });+ // An accepted interrupt can leave tasks running. Release the action for retry.+ setStatusRequest((current) => (current === request ? null : current));+ if (result._tag === "Failure" && !isAtomCommandInterrupted(result)) {+ const error = squashAtomCommandFailure(result);+ Dialog.alert(+ "Could not update thread",+ error instanceof Error ? error.message : "Try again.",+ );+ }+ };const pendingBackgroundWork = presentPendingBackgroundWork(props.selectedThread.pendingBackgroundTasks,);@@ -576,6 +676,46 @@ export const ThreadDetailScreen = function ThreadDetailScreen(props: ThreadDetai.map((item) => item.label).join(", ")}`,waiting: pendingBackgroundWork.waiting,+ onPress: () => {+ Keyboard.dismiss();+ navigation.navigate("ThreadBackgroundWork", {+ environmentId: props.environmentId,+ threadId: props.selectedThread.id,+ });+ },+ action: {+ label: statusPending ? "Stopping..." : "Stop",+ accessibilityLabel: "Stop background work",+ disabled: !props.canOperateThread || statusPending,+ onPress: () => void runStatusAction("stop"),+ },+ };+ }+ if (contentPresentationKind === "ready" && (snoozed || settled || woke)) {+ const state = snoozed ? "snoozed" : settled ? "settled" : "woke";+ const label =+ snoozed && snoozedUntil !== null+ ? `Snoozed, wakes in ${snoozeWakeLabel(snoozedUntil, { now: lifecycleNow })}`+ : settled+ ? "Settled"+ : "Woke from snooze";+ const actionLabel = snoozed ? "Wake now" : settled ? "Un-settle" : "Dismiss";+ return {+ kind: "lifecycle",+ state,+ label,+ action: {+ label: statusPending+ ? snoozed+ ? "Waking..."+ : settled+ ? "Un-settling..."+ : "Dismissing..."+ : actionLabel,+ accessibilityLabel: actionLabel,+ disabled: !props.canOperateThread || statusPending,+ onPress: () => void runStatusAction(snoozed ? "wake" : settled ? "unsettle" : "dismiss"),+ },};}if (props.selectedThread.goal !== null && contentPresentationKind === "ready") {diff --git a/apps/mobile/src/features/threads/floating-working-control.tsx b/apps/mobile/src/features/threads/floating-working-control.tsxindex 0c740e5060b..a012e6253f4 100644--- a/apps/mobile/src/features/threads/floating-working-control.tsx+++ b/apps/mobile/src/features/threads/floating-working-control.tsx@@ -84,6 +84,11 @@ export function FloatingWorkingControl(props: {const { width: windowWidth } = useWindowDimensions();const [overlayWidth, setOverlayWidth] = useState(windowWidth);const [queueWidth, setQueueWidth] = useState(0);+ const [actionWidth, setActionWidth] = useState(0);+ const action =+ props.status?.kind === "background" || props.status?.kind === "lifecycle"+ ? props.status.action+ : null;const [agentsWidth, setAgentsWidth] = useState(0);const hasQueue = props.queuedCount > 0;const hasPreview = props.devicePreview !== null || props.browserPreview !== null;@@ -95,6 +100,7 @@ export function FloatingWorkingControl(props: {Math.min(overlayWidth, windowWidth) -CONTROL_HEIGHT -32 -+ (action !== null ? actionWidth : 0) -(hasQueue ? queueWidth : 0) -(hasAgents ? agentsWidth : 0) -(hasPreview ? previewWidth : 0),@@ -156,8 +162,11 @@ export function FloatingWorkingControl(props: {hasQueue ||(props.devicePreview !== null && props.browserPreview !== null);const statusInteractive =- props.status?.kind === "connection" || props.status?.kind === "child-input";- const capsuleInteractive = statusInteractive || hasQueue || hasAgents || hasPreview;+ props.status?.kind === "connection" ||+ props.status?.kind === "child-input" ||+ props.status?.kind === "background";+ const capsuleInteractive =+ statusInteractive || action !== null || hasQueue || hasAgents || hasPreview;const statusContent =props.status !== null ? (<View@@ -186,6 +195,22 @@ export function FloatingWorkingControl(props: {const capsuleContent = (<View className="flex-row items-center">{statusContent}+ {action !== null ? (+ <Pressable+ accessibilityRole="button"+ accessibilityLabel={action.accessibilityLabel}+ accessibilityState={{ disabled: action.disabled }}+ disabled={action.disabled}+ onPress={action.onPress}+ onLayout={(event) => setActionWidth(settleWidth(event.nativeEvent.layout.width))}+ className={`h-11 flex-row items-center gap-1.5 px-3 active:opacity-70 ${action.disabled ? "opacity-50" : ""}`}+ >+ <View className="mr-1 h-4 w-px bg-border" />+ <Text className="font-t3-medium text-xs text-foreground" numberOfLines={1}>+ {action.label}+ </Text>+ </Pressable>+ ) : null}{hasPreview ? (<ViewclassName="h-11 flex-row items-center"@@ -404,16 +429,38 @@ function FloatingStatusLabel(props: {</StatusLabelRow>);}+ if (props.status.kind === "lifecycle") {+ return (+ <StatusLabelRow+ key="lifecycle"+ accessibilityLabel={props.status.label}+ className="gap-2"+ onLayout={props.onLayout}+ >+ <SymbolView+ name={props.status.state === "settled" ? "checkmark.circle" : "clock"}+ size={13}+ tintColorClassName="foreground"+ type="monochrome"+ />+ <Text className="shrink font-t3-medium text-xs text-foreground" numberOfLines={1}>+ {props.status.label}+ </Text>+ </StatusLabelRow>+ );+ }if (props.status.kind === "background") {return (<StatusLabelRowkey="background"accessibilityLabel={props.status.accessibilityLabel}+ accessibilityRole="button"+ onPress={props.status.onPress}className="gap-2"onLayout={props.onLayout}><SymbolView- name={props.status.waiting ? { ios: "bolt", android: "bolt" } : "terminal"}+ name={props.status.waiting ? "person.2" : "terminal"}size={13}tintColorClassName="foreground"type="monochrome"diff --git a/apps/mobile/src/features/threads/floating-working-status.ts b/apps/mobile/src/features/threads/floating-working-status.tsindex ac099ee1d78..264d110f75f 100644--- a/apps/mobile/src/features/threads/floating-working-status.ts+++ b/apps/mobile/src/features/threads/floating-working-status.ts@@ -1,5 +1,12 @@import type { EnvironmentConnectionPhase } from "@t3tools/client-runtime/connection";+export interface FloatingStatusAction {+ readonly label: string;+ readonly accessibilityLabel: string;+ readonly disabled: boolean;+ readonly onPress: () => void;+}+export type FloatingWorkingStatus =| { readonly kind: "working"; readonly startedAt: string }| { readonly kind: "syncing"; readonly label: string }@@ -15,6 +22,14 @@ export type FloatingWorkingStatus =readonly label: string;readonly accessibilityLabel: string;readonly waiting: boolean;+ readonly onPress: () => void;+ readonly action: FloatingStatusAction;+ }+ | {+ readonly kind: "lifecycle";+ readonly state: "snoozed" | "settled" | "woke";+ readonly label: string;+ readonly action: FloatingStatusAction;}| { readonly kind: "goal"; readonly label: string; readonly accessibilityLabel: string }| { readonly kind: "preparing"; readonly label: string }diff --git a/apps/web/src/components/ChatView.logic.ts b/apps/web/src/components/ChatView.logic.tsindex 03ba62765e3..408ec2e3e5b 100644--- a/apps/web/src/components/ChatView.logic.ts+++ b/apps/web/src/components/ChatView.logic.ts@@ -1362,21 +1362,4 @@ export function mergeDirectPreviewAnnotation(input: {return { images, previewAnnotations };}-/**- * Whether a woken thread woke after the user last saw it. A run that completed- * after the last visit counts as seeing it, since the user watched it finish.- */-export function isThreadWokeUnseen(input: {- readonly wokeAt: string | null;- readonly settled: boolean;- readonly lastVisitedAt: string | null | undefined;- readonly latestRunCompletedAt: string | null;-}): boolean {- if (input.wokeAt === null || input.settled) return false;- const wokeAtMs = Date.parse(input.wokeAt);- if (Number.isNaN(wokeAtMs)) return false;- const seenAt = [input.lastVisitedAt, input.latestRunCompletedAt]- .map((value) => (value ? Date.parse(value) : NaN))- .filter((ms) => !Number.isNaN(ms));- return seenAt.every((ms) => ms < wokeAtMs);-}+export { isThreadWokeUnseen } from "@t3tools/client-runtime/state/thread-settled";diff --git a/packages/client-runtime/src/state/threadSettled.ts b/packages/client-runtime/src/state/threadSettled.tsindex 86f4914f6c3..cd156ccdc2e 100644--- a/packages/client-runtime/src/state/threadSettled.ts+++ b/packages/client-runtime/src/state/threadSettled.ts@@ -294,3 +294,22 @@ export function localSnoozeDate(date: Date): string {export function localSnoozeTime(date: Date): string {return `${String(date.getHours()).padStart(2, "0")}:${String(date.getMinutes()).padStart(2, "0")}`;}++/**+ * Whether a woken thread woke after the user last saw it. A run that completed+ * after the last visit counts as seeing it, since the user watched it finish.+ */+export function isThreadWokeUnseen(input: {+ readonly wokeAt: string | null;+ readonly settled: boolean;+ readonly lastVisitedAt: string | null | undefined;+ readonly latestRunCompletedAt: string | null;+}): boolean {+ if (input.wokeAt === null || input.settled) return false;+ const wokeAtMs = Date.parse(input.wokeAt);+ if (Number.isNaN(wokeAtMs)) return false;+ const seenAt = [input.lastVisitedAt, input.latestRunCompletedAt]+ .map((value) => (value ? Date.parse(value) : NaN))+ .filter((ms) => !Number.isNaN(ms));+ return seenAt.every((ms) => ms < wokeAtMs);+}diff --git a/packages/client-runtime/src/state/threadSnoozed.test.ts b/packages/client-runtime/src/state/threadSnoozed.test.tsindex 5b7960ea980..58c9f7e28b3 100644--- a/packages/client-runtime/src/state/threadSnoozed.test.ts+++ b/packages/client-runtime/src/state/threadSnoozed.test.ts@@ -11,6 +11,7 @@ import {snoozeWakeLabel,threadRaisedHandWhileSnoozed,threadWokeAt,+ isThreadWokeUnseen,type ThreadSnoozeShell,} from "./threadSettled.ts";@@ -418,3 +419,16 @@ describe("resolveSnoozePresets", () => {expect(tomorrow.getDay()).toBe(1);});});++it("dismisses a wake at its timestamp without hiding a later wake", () => {+ const firstWake = "2026-04-10T10:00:00.000Z";+ const state = {+ wokeAt: firstWake,+ settled: false,+ lastVisitedAt: null,+ latestRunCompletedAt: null,+ };+ expect(isThreadWokeUnseen(state)).toBe(true);+ expect(isThreadWokeUnseen({ ...state, lastVisitedAt: firstWake })).toBe(false);+ expect(isThreadWokeUnseen({ ...state, lastVisitedAt: firstWake, wokeAt: NOW })).toBe(true);+});