TypeScript
fix(mobile): thread rows show wake status and elapsed time (#21394)
maria2085ea32cc72
diff --git a/apps/mobile/src/features/home/HomeScreen.tsx b/apps/mobile/src/features/home/HomeScreen.tsxindex eb31946d1f5..afa23370fe3 100644--- a/apps/mobile/src/features/home/HomeScreen.tsx+++ b/apps/mobile/src/features/home/HomeScreen.tsx@@ -636,6 +636,7 @@ export function HomeScreen(props: HomeScreenProps) {hasQueuedMessages={item.hasQueuedMessages}snoozed={item.item.snoozed}pinned={item.item.pinned}+ wokeAt={item.item.wokeAt}snoozePresetMinute={item.snoozePresetMinute ?? ""}snoozeWakeLabelText={item.snoozeWakeLabelText}timeLabel={item.timeLabel}diff --git a/apps/mobile/src/features/threads/ThreadDetailScreen.tsx b/apps/mobile/src/features/threads/ThreadDetailScreen.tsxindex 9bd8c04d84e..85e8dd96183 100644--- a/apps/mobile/src/features/threads/ThreadDetailScreen.tsx+++ b/apps/mobile/src/features/threads/ThreadDetailScreen.tsx@@ -357,7 +357,25 @@ function ThreadVisitWatermark(props: {const lastDispatchedVisitRef = useRef<string | null>(null);const lastVisitDispatchRef = useRef({ threadKey: selectedThreadKey, at: 0 });const selectedThreadId = thread.id;- const selectedThreadUpdatedAt = thread.updatedAt;+ const snoozedUntil = thread.snoozedUntil;+ // Keep the clock in state so React Compiler invalidates the wake calculation.+ const [wakeNow, setWakeNow] = useState(() => new Date().toISOString());+ useEffect(() => {+ if (!showContent || snoozedUntil == null) return;+ const delay = Date.parse(snoozedUntil) - Date.now();+ if (!Number.isFinite(delay)) return;+ const timer = setTimeout(() => setWakeNow(new Date().toISOString()), Math.max(0, delay) + 50);+ return () => clearTimeout(timer);+ }, [showContent, snoozedUntil]);+ const selectedThreadWokeAt = threadWokeAt(thread, {+ now: wakeNow,+ });+ // A scheduled wake can happen without a newer server update.+ const selectedThreadUpdatedAt =+ selectedThreadWokeAt !== null && Date.parse(selectedThreadWokeAt) > Date.parse(thread.updatedAt)+ ? selectedThreadWokeAt+ : thread.updatedAt;+ const wakeIsLatestUpdate = selectedThreadUpdatedAt === selectedThreadWokeAt;const selectedThreadLastVisitedAt = thread.lastVisitedAt;const selectedThreadCompletedAt = thread.latestRun?.completedAt;useEffect(() => {@@ -384,7 +402,14 @@ function ThreadVisitWatermark(props: {(Number.isNaN(lastVisitedAtMs) || completedAtMs > lastVisitedAtMs);const previous = lastVisitDispatchRef.current;const elapsed = Date.now() - previous.at;- if (previous.threadKey !== selectedThreadKey || hasUnseenCompletion || elapsed >= 10_000) {+ // Like a completion, a wake the user is looking at must not wait out the throttle:+ // leaving within it would cancel the dispatch and keep Woke in the list.+ if (+ previous.threadKey !== selectedThreadKey ||+ hasUnseenCompletion ||+ wakeIsLatestUpdate ||+ elapsed >= 10_000+ ) {dispatch();return;}@@ -399,6 +424,7 @@ function ThreadVisitWatermark(props: {selectedThreadUpdatedAt,showContent,visitThread,+ wakeIsLatestUpdate,]);return null;}diff --git a/apps/mobile/src/features/threads/ThreadNavigationSidebar.tsx b/apps/mobile/src/features/threads/ThreadNavigationSidebar.tsxindex 739efd50788..9813f0d4633 100644--- a/apps/mobile/src/features/threads/ThreadNavigationSidebar.tsx+++ b/apps/mobile/src/features/threads/ThreadNavigationSidebar.tsx@@ -599,6 +599,7 @@ function ThreadNavigationSidebarPane(hasQueuedMessages={item.hasQueuedMessages}snoozed={item.item.snoozed}pinned={item.item.pinned}+ wokeAt={item.item.wokeAt}snoozePresetMinute={item.snoozePresetMinute ?? ""}snoozeWakeLabelText={item.snoozeWakeLabelText}timeLabel={item.timeLabel}diff --git a/apps/mobile/src/features/threads/thread-list-v2-items.tsx b/apps/mobile/src/features/threads/thread-list-v2-items.tsxindex c23d60a5dc9..d072c17aa71 100644--- a/apps/mobile/src/features/threads/thread-list-v2-items.tsx+++ b/apps/mobile/src/features/threads/thread-list-v2-items.tsx@@ -12,12 +12,19 @@ import { RowPressable } from "../../components/ui/RowPressable";import { CustomSnoozeSheet } from "./CustomSnoozeSheet";import { appAtomRegistry } from "../../state/atom-registry";import { threadArrangementOpenAtom } from "../../state/thread-order";+import { threadEnvironment } from "../../state/threads";+import { useAtomCommand } from "../../state/use-atom-command";+import { useVisibleSecondClock } from "./use-visible-second-clock";import type { ThreadMoveDestination } from "./threadOrder";import type {EnvironmentProject,EnvironmentThreadShell,} from "@t3tools/client-runtime/state/shell";import type { EnvironmentThreadSearchMatch } from "@t3tools/client-runtime/state/thread-search";+import {+ formatWorkingDurationLabel,+ resolveThreadWorkingStartedAt,+} from "@t3tools/client-runtime/state/models";import { AuthOrchestrationOperateScope, type EnvironmentMachineKind } from "@t3tools/contracts";import { canSnooze, resolveSnoozePresets } from "@t3tools/client-runtime/state/thread-settled";import type { MenuAction } from "@react-native-menu/menu";@@ -112,6 +119,13 @@ const DONE_STATUS_LABEL: StatusLabel = {iconTintClassName: "accent-adaptive-emerald-700-300",};+function ThreadListV2Duration(props: { readonly startedAt: string | null }) {+ const startedAtMs = Date.parse(props.startedAt ?? "");+ const nowMs = useVisibleSecondClock(Number.isFinite(startedAtMs));+ if (!Number.isFinite(startedAtMs)) return null;+ return ` ${formatWorkingDurationLabel(nowMs - startedAtMs)}`;+}+const CARD_MENU_ACTIONS: MenuAction[] = [{ id: "settle", title: "Settle", image: "checkmark" },{ id: "delete", title: "Delete", image: "trash", attributes: { destructive: true } },@@ -477,6 +491,7 @@ export const ThreadListV2Row = memo(function ThreadListV2Row(props: {readonly hasQueuedMessages?: boolean;readonly snoozed?: boolean;readonly pinned?: boolean;+ readonly wokeAt: string | null;readonly snoozeWakeLabelText?: string;readonly timeLabel: string;readonly snoozePresetMinute: string;@@ -568,12 +583,6 @@ export const ThreadListV2Row = memo(function ThreadListV2Row(props: {const handleOpenPullRequests = useCallback(() => {if (pr) onOpenThreadPullRequests(thread, pr);}, [onOpenThreadPullRequests, pr, thread]);- // VoiceOver cannot focus the badge inside the accessible row, so the row- // exposes the same action.- const rowAccessibilityActions = useMemo(- () => (prBadgeLabel ? [{ name: "openPullRequests", label: prBadgeLabel }] : undefined),- [prBadgeLabel],- );const theme = useUniwindTheme();const sidebarPane = props.pane === "sidebar";@@ -583,6 +592,7 @@ export const ThreadListV2Row = memo(function ThreadListV2Row(props: {const status = resolveThreadListV2Status(thread);const isUnread = status === "ready" && threadHasUnseenCompletion(thread);const workingLabel = STATUS_LABEL_BY_STATUS[status];+ const showsWoke = status === "ready" && props.wokeAt !== null;const statusLabel =(status === "working" && workingLabel !== undefined && thread.goal?.status === "active"? { ...workingLabel, label: "Goal" }@@ -590,6 +600,23 @@ export const ThreadListV2Row = memo(function ThreadListV2Row(props: {const recede = shouldRecedeThreadRow({ status, selected });const timeLabel = props.timeLabel;+ const visitThread = useAtomCommand(threadEnvironment.visit, { reportFailure: false });+ const handleAcknowledgeWoke = useCallback(() => {+ if (props.wokeAt === null) return;+ void visitThread({+ environmentId: thread.environmentId,+ input: { threadId: thread.id, visitedAt: props.wokeAt },+ });+ }, [props.wokeAt, thread.environmentId, thread.id, visitThread]);+ // VoiceOver cannot focus buttons inside the accessible row.+ const rowAccessibilityActions = useMemo(+ () => [+ ...(prBadgeLabel ? [{ name: "openPullRequests", label: prBadgeLabel }] : []),+ ...(showsWoke ? [{ name: "dismissWoke", label: "Dismiss Woke notification" }] : []),+ ],+ [prBadgeLabel, showsWoke],+ );+const handleDelete = useCallback(() => onDeleteThread(thread), [onDeleteThread, thread]);const handleRename = useCallback(() => onRenameThread(thread), [onRenameThread, thread]);const canOperateThread = useEnvironmentScope(thread.environmentId, AuthOrchestrationOperateScope);@@ -948,7 +975,34 @@ export const ThreadListV2Row = memo(function ThreadListV2Row(props: {type="monochrome"/>) : null}- {statusLabel ? (+ {showsWoke ? (+ <Pressable+ className="-m-2.5 flex-row items-center gap-1 p-2.5"+ accessibilityRole="button"+ accessibilityLabel="Dismiss Woke notification"+ onPress={handleAcknowledgeWoke}+ onLongPress={() => undefined}+ style={({ pressed }) => ({ opacity: pressed ? 0.6 : 1 })}+ >+ <SymbolView+ name="bell.badge"+ size={13}+ tintColorClassName={+ selected ? selectedThreadRowColors.iconTintClassName : "accent-warning-foreground"+ }+ type="monochrome"+ weight="semibold"+ />+ <Text+ className={cn(+ "text-xs font-t3-bold",+ selected ? selectedThreadRowColors.foregroundClassName : "text-warning-foreground",+ )}+ >+ Woke+ </Text>+ </Pressable>+ ) : statusLabel ? (<View className="flex-row items-center gap-1"><SymbolViewname={statusLabel.icon}@@ -962,10 +1016,16 @@ export const ThreadListV2Row = memo(function ThreadListV2Row(props: {<TextclassName={cn("text-xs font-t3-bold",+ (status === "working" || status === "waiting") && "tabular-nums",selected ? selectedThreadRowColors.foregroundClassName : statusLabel.className,)}>{statusLabel.label}+ {status === "working" ? (+ <ThreadListV2Duration startedAt={resolveThreadWorkingStartedAt(thread)} />+ ) : status === "waiting" ? (+ <ThreadListV2Duration startedAt={thread.latestRun?.completedAt ?? null} />+ ) : null}</Text></View>) : (@@ -1156,6 +1216,7 @@ export const ThreadListV2Row = memo(function ThreadListV2Row(props: {accessibilityActions={rowAccessibilityActions}onAccessibilityAction={(event) => {if (event.nativeEvent.actionName === "openPullRequests") handleOpenPullRequests();+ if (event.nativeEvent.actionName === "dismissWoke") handleAcknowledgeWoke();}}onPress={() => {close();diff --git a/apps/mobile/src/features/threads/threadListV2.test.ts b/apps/mobile/src/features/threads/threadListV2.test.tsindex 82dfae31c31..2621d455186 100644--- a/apps/mobile/src/features/threads/threadListV2.test.ts+++ b/apps/mobile/src/features/threads/threadListV2.test.ts@@ -35,6 +35,7 @@ import {getThreadListV2OrderedSection,resolveThreadListV2SnoozeMenuSelection,resolveThreadListV2Status,+ resolveThreadListV2WokeAt,resolveThreadListV2SwipeActions,sortThreadsForListV2,threadListV2ListItemsAreEqual,@@ -1426,6 +1427,100 @@ describe("threadListV2ListItemsAreEqual", () => {});});+describe("thread list Woke marker", () => {+ const wokeAt = isoAt(BASE_MS - MINUTE_MS);+ const thread = makeThread({+ id: ThreadId.make("woke"),+ title: "Woke",+ latestUserMessageAt: isoAt(BASE_MS - 90 * MINUTE_MS),+ snoozedAt: isoAt(BASE_MS - 60 * MINUTE_MS),+ snoozedUntil: wokeAt,+ lastVisitedAt: null,+ });++ it("keeps a timer wake through a plain visit until acknowledgement reaches its timestamp", () => {+ expect(resolveThreadListV2WokeAt(thread, { now: NOW })).toBe(wokeAt);+ expect(+ resolveThreadListV2WokeAt(+ { ...thread, lastVisitedAt: isoAt(BASE_MS - 30 * MINUTE_MS) },+ { now: NOW },+ ),+ ).toBe(wokeAt);+ expect(+ resolveThreadListV2WokeAt({ ...thread, lastVisitedAt: wokeAt }, { now: NOW }),+ ).toBeNull();+ expect(resolveThreadListV2WokeAt({ ...thread, lastVisitedAt: "invalid" }, { now: NOW })).toBe(+ wokeAt,+ );+ });++ it("stays hidden while snoozed, after settling, and on servers without visited tracking", () => {+ expect(resolveThreadListV2WokeAt(thread, { now: isoAt(BASE_MS - 2 * MINUTE_MS) })).toBeNull();+ expect(+ resolveThreadListV2WokeAt({ ...thread, settledOverride: "settled" }, { now: NOW }),+ ).toBeNull();+ expect(+ resolveThreadListV2WokeAt({ ...thread, lastVisitedAt: undefined }, { now: NOW }),+ ).toBeNull();+ expect(resolveThreadListV2WokeAt({ ...thread, snoozedUntil: null }, { now: NOW })).toBeNull();+ });++ it("keeps an early failure wake acknowledged after the scheduled time passes", () => {+ const completedAt = isoAt(BASE_MS - 2 * MINUTE_MS);+ const failed = makeThread({+ ...thread,+ snoozedUntil: isoAt(BASE_MS + MINUTE_MS),+ runtime: {+ status: "failed",+ activeRunId: null,+ providerInstanceId: ProviderInstanceId.make("codex"),+ providerName: "Codex",+ lastError: "Run failed",+ updatedAt: completedAt,+ },+ latestRun: {+ runId: RunId.make("woke-run"),+ status: "failed",+ requestedAt: isoAt(BASE_MS - 3 * MINUTE_MS),+ startedAt: isoAt(BASE_MS - 3 * MINUTE_MS),+ completedAt,+ assistantMessageId: null,+ },+ });+ expect(resolveThreadListV2WokeAt(failed, { now: NOW })).toBe(completedAt);+ expect(+ resolveThreadListV2WokeAt(+ { ...failed, lastVisitedAt: completedAt },+ { now: isoAt(BASE_MS + 2 * MINUTE_MS) },+ ),+ ).toBeNull();+ });++ it("updates a recycled row at the wake boundary even without a new shell or minute tick", () => {+ const waking = { ...thread, snoozedUntil: isoAt(BASE_MS + 30_000) };+ const layout = (now: string) =>+ buildThreadListV2Items({+ threads: [waking],+ environmentId: null,+ searchQuery: "",+ now,+ snoozeEnvironmentIds: new Set<EnvironmentId>(),+ });+ const list = (now: string) =>+ buildThreadListV2ListItems({+ items: layout(now).items,+ pendingTasks: [],+ snoozeLabelNow: isoAt(BASE_MS),+ });+ const before = list(NOW)[0]!;+ const after = list(isoAt(BASE_MS + 37_500))[0]!;+ expect(before.type === "v2-thread" && before.item.wokeAt).toBeNull();+ expect(after.type === "v2-thread" && after.item.wokeAt).toBe(waking.snoozedUntil);+ expect(after.type === "v2-thread" && after.timeLabel).toBe("");+ expect(threadListV2ListItemsAreEqual(before, after)).toBe(false);+ });+});+describe("buildThreadListV2ListItems row-state stamps", () => {const readyThread = makeThread({id: ThreadId.make("stamp-ready"),diff --git a/apps/mobile/src/features/threads/threadListV2.ts b/apps/mobile/src/features/threads/threadListV2.tsindex 360fbe18f09..78a65df9062 100644--- a/apps/mobile/src/features/threads/threadListV2.ts+++ b/apps/mobile/src/features/threads/threadListV2.ts@@ -6,6 +6,7 @@ import {QUEUED_TURN_START_GRACE_MS,resolveSnoozePresets,snoozeWakeLabel,+ threadWokeAt,} from "@t3tools/client-runtime/state/thread-settled";import type { SnoozePreset } from "@t3tools/client-runtime/state/thread-settled";import type { EnvironmentThreadShell } from "@t3tools/client-runtime/state/shell";@@ -151,6 +152,20 @@ export function threadHasUnseenCompletion(return completedAtMs > lastVisitedAtMs;}+export function resolveThreadListV2WokeAt(+ thread: EnvironmentThreadShell,+ options: { readonly now: string },+): string | null {+ // Older servers cannot persist an acknowledgement.+ if (thread.lastVisitedAt === undefined || thread.settledOverride === "settled") return null;+ const wokeAt = threadWokeAt(thread, options);+ const wokeAtMs = Date.parse(wokeAt ?? "");+ const lastVisitedAtMs = Date.parse(thread.lastVisitedAt ?? "");+ return !Number.isNaN(wokeAtMs) && (Number.isNaN(lastVisitedAtMs) || lastVisitedAtMs < wokeAtMs)+ ? wokeAt+ : null;+}+export function resolveThreadListV2Status(thread: Pick<EnvironmentThreadShell,@@ -246,6 +261,7 @@ export interface ThreadListV2Item {readonly variant: "card" | "slim";readonly snoozed: boolean;readonly pinned: boolean;+ readonly wokeAt: string | null;readonly isLast: boolean;}@@ -357,6 +373,7 @@ export function threadListV2ListItemsAreEqual(previous.item.variant === item.item.variant &&previous.item.snoozed === item.item.snoozed &&previous.item.pinned === item.item.pinned &&+ previous.item.wokeAt === item.item.wokeAt &&previous.snoozeWakeLabelText === item.snoozeWakeLabelText &&previous.timeLabel === item.timeLabel &&previous.snoozePresetMinute === item.snoozePresetMinute &&@@ -405,7 +422,9 @@ function resolveThreadListV2ItemTimeLabel(if (showSnoozeWakeLabel) return "";if (variant === "card" &&- (resolveThreadListV2Status(thread) !== "ready" || threadHasUnseenCompletion(thread))+ (resolveThreadListV2Status(thread) !== "ready" ||+ item.wokeAt !== null ||+ threadHasUnseenCompletion(thread)))return "";const settledTimestamp =@@ -694,6 +713,7 @@ export function buildThreadListV2Items(input: {variant: "card",snoozed: false,pinned: true,+ wokeAt: resolveThreadListV2WokeAt(thread, { now }),isLast: false,});}@@ -703,6 +723,7 @@ export function buildThreadListV2Items(input: {variant: "card",snoozed: false,pinned: false,+ wokeAt: resolveThreadListV2WokeAt(thread, { now }),isLast: false,});}@@ -713,6 +734,7 @@ export function buildThreadListV2Items(input: {variant: "card",snoozed: false,pinned: false,+ wokeAt: resolveThreadListV2WokeAt(thread, { now }),isLast: false,});}@@ -723,6 +745,7 @@ export function buildThreadListV2Items(input: {variant: "slim",snoozed: true,pinned: false,+ wokeAt: null,isLast: false,});}@@ -733,6 +756,7 @@ export function buildThreadListV2Items(input: {variant: "slim",snoozed: false,pinned: false,+ wokeAt: null,isLast: false,});}diff --git a/apps/web/src/components/Sidebar.logic.test.ts b/apps/web/src/components/Sidebar.logic.test.tsindex 275d04a5486..161e4c9cf7a 100644--- a/apps/web/src/components/Sidebar.logic.test.ts+++ b/apps/web/src/components/Sidebar.logic.test.ts@@ -1,4 +1,7 @@-import { presentThreadShell } from "@t3tools/client-runtime/state/models";+import {+ formatWorkingDurationLabel,+ presentThreadShell,+} from "@t3tools/client-runtime/state/models";import * as DateTime from "effect/DateTime";import { deriveActiveWorkStartedAt } from "../session-logic.ts";import { describe, expect, it, vi } from "vite-plus/test";diff --git a/apps/web/src/components/Sidebar.logic.ts b/apps/web/src/components/Sidebar.logic.tsindex 36115a87e97..e5bcdffc980 100644--- a/apps/web/src/components/Sidebar.logic.ts+++ b/apps/web/src/components/Sidebar.logic.ts@@ -1058,14 +1058,6 @@ export function resolveWorkingStartedAt(return resolveThreadWorkingStartedAt(thread);}-export function formatWorkingDurationLabel(elapsedMs: number): string {- const seconds = Number.isFinite(elapsedMs) ? Math.max(0, Math.floor(elapsedMs / 1000)) : 0;- if (seconds < 60) return `${seconds}s`;- const minutes = Math.floor(seconds / 60);- if (minutes < 60) return `${minutes}m`;- return `${Math.floor(minutes / 60)}h ${minutes % 60}m`;-}-export function resolveThreadStatusPill(input: {thread: ThreadStatusInput;}): ThreadStatusPill | null {diff --git a/apps/web/src/components/Sidebar.tsx b/apps/web/src/components/Sidebar.tsxindex bcd24bf8498..70296a4806a 100644--- a/apps/web/src/components/Sidebar.tsx+++ b/apps/web/src/components/Sidebar.tsx@@ -48,6 +48,7 @@ import {type EnvironmentThreadSearchMatch,} from "@t3tools/client-runtime/state/thread-search";import {+ formatWorkingDurationLabel,resolveThreadProviderStack,threadRuntimeCanArchive,type EnvironmentThreadShell,@@ -195,7 +196,6 @@ import {buildBulkUnpinContextMenuItem,deleteSelectedThreadEntries,filterSidebarProjectScopeItems,- formatWorkingDurationLabel,firstValidTimestampMs,hasUnseenCompletion,isSidebarNestedLinkClick,diff --git a/packages/client-runtime/src/state/models.ts b/packages/client-runtime/src/state/models.tsindex 7fd2bfb39fb..ba78e2304d7 100644--- a/packages/client-runtime/src/state/models.ts+++ b/packages/client-runtime/src/state/models.ts@@ -333,3 +333,11 @@ export function resolveThreadWorkingStartedAt(input: {}return null;}++export function formatWorkingDurationLabel(elapsedMs: number): string {+ const seconds = Number.isFinite(elapsedMs) ? Math.max(0, Math.floor(elapsedMs / 1000)) : 0;+ if (seconds < 60) return `${seconds}s`;+ const minutes = Math.floor(seconds / 60);+ if (minutes < 60) return `${minutes}m`;+ return `${Math.floor(minutes / 60)}h ${minutes % 60}m`;+}