@devries-cameron20 / t3code-1 / commits / 671719b25c
Fork 0

The best way to control Claude Code, Codex and more from any computer or phone

perf(mobile): home, workspace layout and overlay pieces compile with the React Compiler (#21133)

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>

Julius Marminge committed Oct 18, 2026 at 14:33 UTC 671719b25c5bc1e3693c276ea1892acef9151833
9 files changed +922 -1244
apps/mobile/src/components/ui/OverlayPortal.tsx
+6 -4
@@ -1,4 +1,4 @@
1 -import { type ReactNode, useEffect, useRef, useState } from "react";
1 +import { type ReactNode, useEffect, useState } from "react";
2 import { View } from "react-native";
3
4 // AndroidAnchoredMenu projects its dropdown here instead of into an RN Modal: a Modal is a
@@ -8,6 +8,10 @@ type Entries = ReadonlyMap<number, ReactNode>;
8 type Listener = (entries: Entries) => void;
9
10 let nextKey = 0;
11 +
12 +function allocateKey() {
13 + return nextKey++;
14 +}
15 const entries = new Map<number, ReactNode>();
16 const listeners = new Set<Listener>();
17
@@ -19,9 +23,7 @@ function emit() {
23 }
24
25 export function OverlayPortal(props: { readonly children: ReactNode }) {
22 - const keyRef = useRef<number | null>(null);
23 - keyRef.current ??= nextKey++;
24 - const key = keyRef.current;
26 + const [key] = useState(allocateKey);
27
28 // No dependency array: re-project after every render so the host always
29 // shows the current content (menus re-render while open — drill-in, theme).
apps/mobile/src/features/home/HomeScreen.tsx
+278 -441
@@ -14,7 +14,7 @@ import {
14 import { type EnvironmentId, type SidebarProjectGroupingMode } from "@t3tools/contracts";
15 import { useAtomValue } from "@effect/atom-react";
16 import { useFocusEffect } from "@react-navigation/native";
17 -import { use, useCallback, useEffect, useMemo, useRef, useState, type ComponentProps } from "react";
17 +import { use, useEffect, useRef, useState, type ComponentProps } from "react";
18 import {
19 Platform,
20 ScrollView,
@@ -287,23 +287,20 @@ export function HomeScreen(props: HomeScreenProps) {
287 24,
288 workspace?.bottomClearance ?? 0,
289 );
290 - const searchEnvironmentIds = useMemo(
291 - () =>
292 - props.selectedEnvironmentId === null
293 - ? props.environments
294 - .filter((environment) => environment.connectionState === "connected")
295 - .map((environment) => environment.environmentId)
296 - : props.environments.some(
297 - (environment) =>
298 - environment.environmentId === props.selectedEnvironmentId &&
299 - environment.connectionState === "connected",
300 - )
301 - ? [props.selectedEnvironmentId]
302 - : [],
303 - [props.environments, props.selectedEnvironmentId],
304 - );
290 + const searchEnvironmentIds =
291 + props.selectedEnvironmentId === null
292 + ? props.environments
293 + .filter((environment) => environment.connectionState === "connected")
294 + .map((environment) => environment.environmentId)
295 + : props.environments.some(
296 + (environment) =>
297 + environment.environmentId === props.selectedEnvironmentId &&
298 + environment.connectionState === "connected",
299 + )
300 + ? [props.selectedEnvironmentId]
301 + : [];
302 const threadSearch = useThreadSearch(searchEnvironmentIds, props.searchQuery);
306 - const threadSearchMatchByKey = useMemo(() => {
303 + const threadSearchMatchByKey = (() => {
304 const matches = new Map<string, EnvironmentThreadSearchMatch>();
305 for (const match of threadSearch.matches) {
306 if (match.source === "user" || match.source === "assistant") {
@@ -311,35 +308,32 @@ export function HomeScreen(props: HomeScreenProps) {
308 }
309 }
310 return matches;
314 - }, [threadSearch.matches]);
315 - const matchedThreadKeys = useMemo(
316 - () => new Set(threadSearch.matches.map(threadSearchMatchKey)),
317 - [threadSearch.matches],
318 - );
319 - const handleSwipeableWillOpen = useCallback((methods: SwipeableMethods) => {
311 + })();
312 + const matchedThreadKeys = new Set(threadSearch.matches.map(threadSearchMatchKey));
313 + const handleSwipeableWillOpen = (methods: SwipeableMethods) => {
314 if (openSwipeableRef.current !== methods) {
315 openSwipeableRef.current?.close();
316 openSwipeableRef.current = methods;
317 }
324 - }, []);
318 + };
319
326 - const handleSwipeableClose = useCallback((methods: SwipeableMethods) => {
320 + const handleSwipeableClose = (methods: SwipeableMethods) => {
321 if (openSwipeableRef.current === methods) {
322 openSwipeableRef.current = null;
323 }
330 - }, []);
324 + };
325
332 - const handleScrollBeginDrag = useCallback(() => {
326 + const handleScrollBeginDrag = () => {
327 openSwipeableRef.current?.close();
334 - }, []);
328 + };
329 const openThreadPullRequests = useOpenThreadPullRequests();
336 - const handleOpenThreadPullRequests = useCallback(
337 - (thread: EnvironmentThreadShell, pr: ThreadPrPresentation) => {
338 - openSwipeableRef.current?.close();
339 - openThreadPullRequests(thread, pr);
340 - },
341 - [openThreadPullRequests],
342 - );
330 + const handleOpenThreadPullRequests = (
331 + thread: EnvironmentThreadShell,
332 + pr: ThreadPrPresentation,
333 + ) => {
334 + openSwipeableRef.current?.close();
335 + openThreadPullRequests(thread, pr);
336 + };
337 const onFabScroll = useFabScroll();
338 const listRef = useRef<LegendListRef>(null);
339 const searchMode = workspace?.state.tabs.threads.searchMode;
@@ -351,163 +345,111 @@ export function HomeScreen(props: HomeScreenProps) {
345 animated: false,
346 });
347 }, [searchMode, insets.top, restoredOffset]);
354 - const swipeRowActivation = useMemo(() => createSwipeRowActivation(), []);
355 - const activateVisibleRows = useCallback(
356 - (rows: ReadonlyArray<ThreadListV2ListItem>) => {
357 - const state = listRef.current?.getState();
358 - if (state === undefined || !(state.end >= 0)) return;
359 - swipeRowActivation.activate(
360 - rows.slice(Math.max(0, state.start - 2), state.end + 3).map((row) => row.key),
361 - );
362 - },
363 - [swipeRowActivation],
364 - );
348 + const swipeRowActivation = createSwipeRowActivation();
349 + const activateVisibleRows = (rows: ReadonlyArray<ThreadListV2ListItem>) => {
350 + const state = listRef.current?.getState();
351 + if (state === undefined || !(state.end >= 0)) return;
352 + swipeRowActivation.activate(
353 + rows.slice(Math.max(0, state.start - 2), state.end + 3).map((row) => row.key),
354 + );
355 + };
356 // Status-bar, accessibility and programmatic scrolls never arm the scroll
357 // gate, so every scroll also activates the visible rows once it settles.
358 const activationTimerRef = useRef<ReturnType<typeof setTimeout> | undefined>(undefined);
359 useEffect(() => () => clearTimeout(activationTimerRef.current), []);
369 - const handleListScroll = useCallback(
370 - (event: NativeSyntheticEvent<NativeScrollEvent>) => {
371 - onFabScroll?.(event);
372 - if (workspace)
373 - workspace.recordScrollOffset(
374 - "threads",
375 - Math.max(0, event.nativeEvent.contentOffset.y + (Platform.OS === "ios" ? insets.top : 0)),
376 - );
377 - clearTimeout(activationTimerRef.current);
378 - activationTimerRef.current = setTimeout(
379 - () => activateVisibleRows(listRef.current?.getState().data ?? []),
380 - 200,
360 + const handleListScroll = (event: NativeSyntheticEvent<NativeScrollEvent>) => {
361 + onFabScroll?.(event);
362 + if (workspace)
363 + workspace.recordScrollOffset(
364 + "threads",
365 + Math.max(0, event.nativeEvent.contentOffset.y + (Platform.OS === "ios" ? insets.top : 0)),
366 );
382 - },
383 - [activateVisibleRows, onFabScroll, workspace, insets.top],
384 - );
385 - const trackListTouches = useCallback(
386 - (event: GestureResponderEvent, started: boolean) => {
387 - const { changedTouches, touches } = event.nativeEvent;
388 - swipeRowActivation.trackTouches(
389 - started ? changedTouches.map((touch) => String(touch.identifier)) : [],
390 - touches.map((touch) => String(touch.identifier)),
391 - );
392 - },
393 - [swipeRowActivation],
394 - );
367 + clearTimeout(activationTimerRef.current);
368 + activationTimerRef.current = setTimeout(
369 + () => activateVisibleRows(listRef.current?.getState().data ?? []),
370 + 200,
371 + );
372 + };
373 + const trackListTouches = (event: GestureResponderEvent, started: boolean) => {
374 + const { changedTouches, touches } = event.nativeEvent;
375 + swipeRowActivation.trackTouches(
376 + started ? changedTouches.map((touch) => String(touch.identifier)) : [],
377 + touches.map((touch) => String(touch.identifier)),
378 + );
379 + };
380 const { swipeEnabled, scrollGateHandlers } = useSwipeableScrollGate({
381 onScroll: handleListScroll,
382 onScrollBeginDrag: handleScrollBeginDrag,
383 });
384
400 - const projectScopes = useMemo(
401 - () =>
402 - buildHomeProjectScopes({
403 - projects: props.projects,
404 - environmentId: props.selectedEnvironmentId,
405 - projectGroupingMode: props.projectGroupingMode,
406 - }),
407 - [props.projectGroupingMode, props.projects, props.selectedEnvironmentId],
408 - );
385 + const projectScopes = buildHomeProjectScopes({
386 + projects: props.projects,
387 + environmentId: props.selectedEnvironmentId,
388 + projectGroupingMode: props.projectGroupingMode,
389 + });
390 const hasSearchQuery = props.searchQuery.trim().length > 0;
410 - const projectByKey = useMemo(() => {
391 + const projectByKey = (() => {
392 const map = new Map<string, EnvironmentProject>();
393 for (const project of props.projects) {
394 map.set(scopedProjectKey(project.environmentId, project.id), project);
395 }
396 return map;
416 - }, [props.projects]);
397 + })();
398
399 const v2ProjectScopeKey = props.selectedProjectKey;
419 - const v2ScopedProjectGroup = useMemo(
420 - () => findHomeProjectScope(projectScopes, v2ProjectScopeKey),
421 - [v2ProjectScopeKey, projectScopes],
422 - );
423 - const v2ProjectTitleByProjectKey = useMemo(
424 - () =>
425 - new Map(
426 - projectScopes.flatMap((scope) =>
427 - scope.projectRefs.map(
428 - (projectRef) =>
429 - [
430 - scopedProjectKey(projectRef.environmentId, projectRef.projectId),
431 - scope.title,
432 - ] as const,
433 - ),
434 - ),
400 + const v2ScopedProjectGroup = findHomeProjectScope(projectScopes, v2ProjectScopeKey);
401 + const v2ProjectTitleByProjectKey = new Map(
402 + projectScopes.flatMap((scope) =>
403 + scope.projectRefs.map(
404 + (projectRef) =>
405 + [scopedProjectKey(projectRef.environmentId, projectRef.projectId), scope.title] as const,
406 ),
436 - [projectScopes],
407 + ),
408 );
438 - const v2ScopedProjectKeys = useMemo(
439 - () =>
440 - v2ScopedProjectGroup === null
441 - ? null
442 - : new Set(
443 - v2ScopedProjectGroup.projectRefs.map((projectRef) =>
444 - scopedProjectKey(projectRef.environmentId, projectRef.projectId),
445 - ),
409 + const v2ScopedProjectKeys =
410 + v2ScopedProjectGroup === null
411 + ? null
412 + : new Set(
413 + v2ScopedProjectGroup.projectRefs.map((projectRef) =>
414 + scopedProjectKey(projectRef.environmentId, projectRef.projectId),
415 ),
447 - [v2ScopedProjectGroup],
448 - );
416 + );
417 const handleSettleThread = props.onSettleThread;
450 - const handleSnoozeThread = useCallback(
451 - (thread: EnvironmentThreadShell, snoozedUntil: string) => {
452 - void props.onSnoozeThread(thread, snoozedUntil);
453 - },
454 - [props.onSnoozeThread],
455 - );
456 - const handleUnsnoozeThread = useCallback(
457 - (thread: EnvironmentThreadShell) => {
458 - void props.onUnsnoozeThread(thread);
459 - },
460 - [props.onUnsnoozeThread],
461 - );
462 - const handlePinThread = useCallback(
463 - (thread: EnvironmentThreadShell) => {
464 - void props.onPinThread(thread);
465 - },
466 - [props.onPinThread],
467 - );
468 - const handleMoveThread = useCallback(
469 - (thread: EnvironmentThreadShell, direction: ThreadMoveDestination) => {
470 - void props.onMoveThread(thread, direction);
471 - },
472 - [props.onMoveThread],
473 - );
474 - const handleUnpinThread = useCallback(
475 - (thread: EnvironmentThreadShell) => {
476 - void props.onUnpinThread(thread);
477 - },
478 - [props.onUnpinThread],
479 - );
480 - const handleSetThreadAutoSettle = useCallback(
481 - (thread: EnvironmentThreadShell, enabled: boolean) => {
482 - void props.onSetThreadAutoSettle(thread, enabled);
483 - },
484 - [props.onSetThreadAutoSettle],
485 - );
486 - const handleRegenerateThreadTitle = useCallback(
487 - (thread: EnvironmentThreadShell) => {
488 - void props.onRegenerateThreadTitle(thread);
489 - },
490 - [props.onRegenerateThreadTitle],
491 - );
492 - const handleRenameThread = useCallback(
493 - (thread: EnvironmentThreadShell) => props.onRenameThread(thread),
494 - [props.onRenameThread],
495 - );
418 + const handleSnoozeThread = (thread: EnvironmentThreadShell, snoozedUntil: string) => {
419 + void props.onSnoozeThread(thread, snoozedUntil);
420 + };
421 + const handleUnsnoozeThread = (thread: EnvironmentThreadShell) => {
422 + void props.onUnsnoozeThread(thread);
423 + };
424 + const handlePinThread = (thread: EnvironmentThreadShell) => {
425 + void props.onPinThread(thread);
426 + };
427 + const handleMoveThread = (thread: EnvironmentThreadShell, direction: ThreadMoveDestination) => {
428 + void props.onMoveThread(thread, direction);
429 + };
430 + const handleUnpinThread = (thread: EnvironmentThreadShell) => {
431 + void props.onUnpinThread(thread);
432 + };
433 + const handleSetThreadAutoSettle = (thread: EnvironmentThreadShell, enabled: boolean) => {
434 + void props.onSetThreadAutoSettle(thread, enabled);
435 + };
436 + const handleRegenerateThreadTitle = (thread: EnvironmentThreadShell) => {
437 + void props.onRegenerateThreadTitle(thread);
438 + };
439 + const handleRenameThread = (thread: EnvironmentThreadShell) => props.onRenameThread(thread);
440 const handleDeleteThread = props.onDeleteThread;
441 const handleUnsettleThread = props.onUnsettleThread;
442 const [settledVisibleCount, setSettledVisibleCount] = useState(
443 THREAD_LIST_V2_SETTLED_INITIAL_COUNT,
444 );
445 const settledResetKey = `${props.selectedEnvironmentId ?? "all"}:${v2ProjectScopeKey ?? "all"}:${props.searchQuery.trim()}`;
502 - const lastSettledResetKeyRef = useRef(settledResetKey);
503 - if (lastSettledResetKeyRef.current !== settledResetKey) {
504 - lastSettledResetKeyRef.current = settledResetKey;
446 + const [lastSettledResetKey, setLastSettledResetKey] = useState(settledResetKey);
447 + if (lastSettledResetKey !== settledResetKey) {
448 + setLastSettledResetKey(settledResetKey);
449 setSettledVisibleCount(THREAD_LIST_V2_SETTLED_INITIAL_COUNT);
450 }
507 - const showMoreSettled = useCallback(
508 - () => setSettledVisibleCount((count) => count + THREAD_LIST_V2_SETTLED_PAGE_COUNT),
509 - [],
510 - );
451 + const showMoreSettled = () =>
452 + setSettledVisibleCount((count) => count + THREAD_LIST_V2_SETTLED_PAGE_COUNT);
453 const {
454 loaded: shelfPreferencesLoaded,
455 settledShelfExpanded,
@@ -518,15 +460,17 @@ export function HomeScreen(props: HomeScreenProps) {
460 toggleSnoozedShelf,
461 toggleWorkingShelf,
462 } = useThreadListV2ShelfPreferences();
521 - const [nowMinute, setNowMinute] = useState(() => new Date().toISOString().slice(0, 16));
463 + // The list's clock is state: the compiler caches anything computed from it on
464 + // its other inputs, so a render-time `new Date()` would stop moving. The minute
465 + // interval and the snooze-wake timer below both advance it.
466 + const [now, setNow] = useState(() => new Date().toISOString());
467 + const nowMinute = now.slice(0, 16);
468 const [snoozeWakeTick, bumpSnoozeWakeTick] = useState(0);
523 - useFocusEffect(
524 - useCallback(() => {
525 - setNowMinute(new Date().toISOString().slice(0, 16));
526 - const id = setInterval(() => setNowMinute(new Date().toISOString().slice(0, 16)), 60_000);
527 - return () => clearInterval(id);
528 - }, []),
529 - );
469 + useFocusEffect(() => {
470 + setNow(new Date().toISOString());
471 + const id = setInterval(() => setNow(new Date().toISOString()), 60_000);
472 + return () => clearInterval(id);
473 + });
474 const listEnvironments = useAtomValue(threadListEnvironmentsAtom);
475 const {
476 providersByEnvironmentId,
@@ -544,7 +488,7 @@ export function HomeScreen(props: HomeScreenProps) {
488 // Up/down menu availability for every card, computed once per section per
489 // rebuild (see computeThreadMoveAvailability): per-thread planner calls made
490 // list construction quadratic, and this list rebuilds on every minute tick.
547 - const threadMoveAvailability = useMemo(() => {
491 + const threadMoveAvailability = (() => {
492 const sectionAvailability = (section: "pinned" | "active") =>
493 computeThreadMoveAvailability({
494 allThreads: props.threads,
@@ -556,7 +500,7 @@ export function HomeScreen(props: HomeScreenProps) {
500 threads: props.threads,
501 section,
502 pendingOrder,
559 - now: new Date().toISOString(),
503 + now,
504 settlementEnvironmentIds,
505 snoozeEnvironmentIds,
506 queuedThreadKeys,
@@ -566,19 +510,8 @@ export function HomeScreen(props: HomeScreenProps) {
510 ...sectionAvailability("pinned"),
511 ...(workingShelfEnabled ? [] : sectionAvailability("active")),
512 ]);
569 - }, [
570 - workingShelfEnabled,
571 - pinReorderEnvironmentIds,
572 - activeReorderEnvironmentIds,
573 - props.threads,
574 - pendingOrder,
575 - queuedThreadKeys,
576 - settlementEnvironmentIds,
577 - snoozeEnvironmentIds,
578 - nowMinute,
579 - snoozeWakeTick,
580 - ]);
581 - const threadListV2Layout = useMemo(() => {
513 + })();
514 + const threadListV2Layout = (() => {
515 threadListInboxReturns.observe(workingShelfEnabled ? props.threads : null);
516 return buildThreadListV2Items({
517 pendingOrder,
@@ -591,7 +524,7 @@ export function HomeScreen(props: HomeScreenProps) {
524 snoozeEnvironmentIds,
525 queuedThreadKeys,
526 settledLimit: settledVisibleCount,
594 - now: new Date().toISOString(),
527 + now,
528 workingShelfEnabled,
529 workingShelfExpanded,
530 inboxReturnAt: threadListInboxReturns.returnedAt,
@@ -599,292 +532,196 @@ export function HomeScreen(props: HomeScreenProps) {
532 settledShelfExpanded,
533 selectedThreadKey,
534 });
602 - }, [
603 - workingShelfEnabled,
604 - workingShelfExpanded,
605 - pendingOrder,
606 - selectedThreadKey,
607 - queuedThreadKeys,
608 - nowMinute,
609 - snoozeWakeTick,
610 - snoozedShelfExpanded,
611 - settledShelfExpanded,
612 - settledVisibleCount,
613 - settlementEnvironmentIds,
614 - snoozeEnvironmentIds,
615 - props.searchQuery,
616 - props.selectedEnvironmentId,
617 - props.threads,
618 - matchedThreadKeys,
619 - v2ScopedProjectGroup,
620 - ]);
535 + })();
536 const nextSnoozeWakeAt = threadListV2Layout.nextSnoozeWakeAt;
537 useEffect(() => {
538 if (nextSnoozeWakeAt === null) return;
539 const wakeAtMs = Date.parse(nextSnoozeWakeAt);
540 if (Number.isNaN(wakeAtMs)) return;
541 const delayMs = Math.min(Math.max(0, wakeAtMs - Date.now()) + 50, 2_147_483_647);
627 - const id = setTimeout(() => bumpSnoozeWakeTick((tick) => tick + 1), delayMs);
542 + const id = setTimeout(() => {
543 + setNow(new Date().toISOString());
544 + bumpSnoozeWakeTick((tick) => tick + 1);
545 + }, delayMs);
546 return () => clearTimeout(id);
547 // snoozeWakeTick must re-arm the timer even when nextSnoozeWakeAt is
548 // unchanged: after a clamped fire (wake beyond the 32-bit setTimeout
549 // range) the boundary string is identical and the chain would die.
550 }, [nextSnoozeWakeAt, snoozeWakeTick]);
551 const v2SearchQuery = props.searchQuery.trim().toLocaleLowerCase();
634 - const v2PendingTasks = useMemo(
635 - () =>
636 - props.pendingTasks.filter(
637 - (pendingTask) =>
638 - (props.selectedEnvironmentId === null ||
639 - pendingTask.environmentId === props.selectedEnvironmentId) &&
640 - (v2ScopedProjectKeys === null ||
641 - v2ScopedProjectKeys.has(
642 - scopedProjectKey(pendingTask.environmentId, pendingTask.projectId),
643 - )) &&
644 - (v2SearchQuery.length === 0 ||
645 - pendingTask.title.toLocaleLowerCase().includes(v2SearchQuery)),
646 - ),
647 - [props.pendingTasks, props.selectedEnvironmentId, v2ScopedProjectKeys, v2SearchQuery],
648 - );
649 - const threadListV2Items = useMemo(
650 - () =>
651 - buildThreadListV2ListItems({
652 - items: threadListV2Layout.items,
653 - pendingTasks: v2PendingTasks,
654 - workingCount: threadListV2Layout.workingCount,
655 - workingShelfExpanded,
656 - workingShelfHeaderIndex: threadListV2Layout.workingShelfHeaderIndex,
657 - snoozedCount: threadListV2Layout.snoozedCount,
658 - snoozedShelfExpanded,
659 - snoozedShelfHeaderIndex: threadListV2Layout.snoozedShelfHeaderIndex,
660 - settledCount: threadListV2Layout.settledCount,
661 - settledShelfExpanded,
662 - settledShelfHeaderIndex: threadListV2Layout.settledShelfHeaderIndex,
663 - snoozeLabelNow: `${nowMinute}:00.000Z`,
664 - snoozeEnvironmentIds,
665 - queuedThreadKeys,
666 - moveAvailability: threadMoveAvailability,
667 - shelfPreferencesLoading: !shelfPreferencesLoaded,
668 - }),
669 - [
670 - nowMinute,
671 - queuedThreadKeys,
672 - threadMoveAvailability,
673 - settledShelfExpanded,
674 - shelfPreferencesLoaded,
675 - snoozedShelfExpanded,
676 - snoozeEnvironmentIds,
677 - threadListV2Layout,
678 - v2PendingTasks,
679 - workingShelfExpanded,
680 - ],
552 + const v2PendingTasks = props.pendingTasks.filter(
553 + (pendingTask) =>
554 + (props.selectedEnvironmentId === null ||
555 + pendingTask.environmentId === props.selectedEnvironmentId) &&
556 + (v2ScopedProjectKeys === null ||
557 + v2ScopedProjectKeys.has(
558 + scopedProjectKey(pendingTask.environmentId, pendingTask.projectId),
559 + )) &&
560 + (v2SearchQuery.length === 0 || pendingTask.title.toLocaleLowerCase().includes(v2SearchQuery)),
561 );
562 + const threadListV2Items = buildThreadListV2ListItems({
563 + items: threadListV2Layout.items,
564 + pendingTasks: v2PendingTasks,
565 + workingCount: threadListV2Layout.workingCount,
566 + workingShelfExpanded,
567 + workingShelfHeaderIndex: threadListV2Layout.workingShelfHeaderIndex,
568 + snoozedCount: threadListV2Layout.snoozedCount,
569 + snoozedShelfExpanded,
570 + snoozedShelfHeaderIndex: threadListV2Layout.snoozedShelfHeaderIndex,
571 + settledCount: threadListV2Layout.settledCount,
572 + settledShelfExpanded,
573 + settledShelfHeaderIndex: threadListV2Layout.settledShelfHeaderIndex,
574 + snoozeLabelNow: `${nowMinute}:00.000Z`,
575 + snoozeEnvironmentIds,
576 + queuedThreadKeys,
577 + moveAvailability: threadMoveAvailability,
578 + shelfPreferencesLoading: !shelfPreferencesLoaded,
579 + });
580
581 useThreadJumpShortcuts(threadListV2Items, props.onSelectThread);
582 useEffect(() => {
583 if (swipeEnabled) activateVisibleRows(threadListV2Items);
584 }, [activateVisibleRows, swipeEnabled, threadListV2Items]);
585
688 - const renderV2Item = useCallback(
689 - ({ item }: { readonly item: ThreadListV2ListItem }) => {
690 - if (item.type === "v2-pending") {
691 - const pendingScopeKey = scopedProjectKey(
692 - item.pendingTask.environmentId,
693 - item.pendingTask.projectId,
694 - );
695 - return (
696 - <ThreadListV2PendingRow
697 - pendingTask={item.pendingTask}
698 - project={projectByKey.get(pendingScopeKey) ?? null}
699 - projectTitle={v2ProjectTitleByProjectKey.get(pendingScopeKey)}
700 - environmentLabel={
701 - Object.keys(props.savedConnectionsById).length > 1
702 - ? (props.savedConnectionsById[item.pendingTask.environmentId]?.environmentLabel ??
703 - null)
704 - : null
705 - }
706 - environmentMachine={machineByEnvironmentId.get(item.pendingTask.environmentId)}
707 - showPendingDivider={item.showPendingDivider}
708 - showTrailingDivider={item.showTrailingDivider}
709 - onSelectPendingTask={props.onSelectPendingTask}
710 - onDeletePendingTask={props.onDeletePendingTask}
711 - />
712 - );
713 - }
714 - if (item.type === "v2-working-shelf") {
715 - return (
716 - <ThreadListV2WorkingShelfHeader
717 - count={item.count}
718 - disabled={item.disabled}
719 - expanded={item.expanded}
720 - onToggle={toggleWorkingShelf}
721 - />
722 - );
723 - }
724 - if (item.type === "v2-snoozed-shelf") {
725 - return (
726 - <ThreadListV2SnoozedShelfHeader
727 - count={item.count}
728 - disabled={item.disabled}
729 - expanded={item.expanded}
730 - onToggle={toggleSnoozedShelf}
731 - />
732 - );
733 - }
734 - if (item.type === "v2-settled-shelf") {
735 - return (
736 - <ThreadListV2SettledShelfHeader
737 - count={item.count}
738 - disabled={item.disabled}
739 - expanded={item.expanded}
740 - onToggle={toggleSettledShelf}
741 - />
742 - );
743 - }
744 - const thread = item.item.thread;
586 + const renderV2Item = ({ item }: { readonly item: ThreadListV2ListItem }) => {
587 + if (item.type === "v2-pending") {
588 + const pendingScopeKey = scopedProjectKey(
589 + item.pendingTask.environmentId,
590 + item.pendingTask.projectId,
591 + );
592 return (
746 - <ThreadListV2Row
747 - pane={primaryColumn ? "sidebar" : "screen"}
748 - selected={scopedThreadKey(thread.environmentId, thread.id) === selectedThreadKey}
749 - fullSwipeWidth={fullSwipeWidth}
750 - onNewThreadOnBranch={props.onNewThreadOnBranch}
751 - thread={thread}
752 - variant={item.item.variant}
753 - hasQueuedMessages={item.hasQueuedMessages}
754 - snoozed={item.item.snoozed}
755 - pinned={item.item.pinned}
756 - snoozePresetMinute={item.snoozePresetMinute ?? ""}
757 - snoozeWakeLabelText={item.snoozeWakeLabelText}
758 - timeLabel={item.timeLabel}
759 - showTrailingDivider={item.showTrailingDivider}
760 - project={
761 - projectByKey.get(scopedProjectKey(thread.environmentId, thread.projectId)) ?? null
762 - }
763 - projectTitle={v2ProjectTitleByProjectKey.get(
764 - scopedProjectKey(thread.environmentId, thread.projectId),
765 - )}
766 - providerInstance={resolveProviderInstance(thread)}
767 - providers={providersByEnvironmentId.get(thread.environmentId)}
593 + <ThreadListV2PendingRow
594 + pendingTask={item.pendingTask}
595 + project={projectByKey.get(pendingScopeKey) ?? null}
596 + projectTitle={v2ProjectTitleByProjectKey.get(pendingScopeKey)}
597 environmentLabel={
598 Object.keys(props.savedConnectionsById).length > 1
770 - ? (props.savedConnectionsById[thread.environmentId]?.environmentLabel ?? null)
599 + ? (props.savedConnectionsById[item.pendingTask.environmentId]?.environmentLabel ??
600 + null)
601 : null
602 }
773 - environmentMachine={machineByEnvironmentId.get(thread.environmentId)}
774 - searchMatch={threadSearchMatchByKey.get(
775 - threadSearchMatchKey({
776 - environmentId: thread.environmentId,
777 - threadId: thread.id,
778 - }),
779 - )}
780 - searchQuery={props.searchQuery}
781 - onSelectThread={props.onSelectThread}
782 - onOpenThreadPullRequests={handleOpenThreadPullRequests}
783 - onDeleteThread={handleDeleteThread}
784 - onArchiveThread={props.onArchiveThread}
785 - onRenameThread={handleRenameThread}
786 - onRegenerateThreadTitle={handleRegenerateThreadTitle}
787 - titleRegenerationSupported={titleRegenerationEnvironmentIds.has(thread.environmentId)}
788 - settlementSupported={settlementEnvironmentIds.has(thread.environmentId)}
789 - onSettleThread={handleSettleThread}
790 - snoozeSupported={snoozeEnvironmentIds.has(thread.environmentId)}
791 - pinningSupported={pinningEnvironmentIds.has(thread.environmentId)}
792 - autoSettleOptOutSupported={autoSettleOptOutEnvironmentIds.has(thread.environmentId)}
793 - reorderSupported={
794 - item.item.pinned
795 - ? pinReorderEnvironmentIds.has(thread.environmentId)
796 - : !workingShelfEnabled && activeReorderEnvironmentIds.has(thread.environmentId)
797 - }
798 - canMoveUp={item.canMoveUp}
799 - canMoveDown={item.canMoveDown}
800 - onSnoozeThread={handleSnoozeThread}
801 - onUnsnoozeThread={handleUnsnoozeThread}
802 - onUnsettleThread={handleUnsettleThread}
803 - onPinThread={handlePinThread}
804 - onUnpinThread={handleUnpinThread}
805 - onSetThreadAutoSettle={handleSetThreadAutoSettle}
806 - onMoveThread={handleMoveThread}
807 - onSwipeableClose={handleSwipeableClose}
808 - onSwipeableWillOpen={handleSwipeableWillOpen}
809 - simultaneousSwipeGesture={homeScrollGesture}
810 - activationKey={item.key}
603 + environmentMachine={machineByEnvironmentId.get(item.pendingTask.environmentId)}
604 + showPendingDivider={item.showPendingDivider}
605 + showTrailingDivider={item.showTrailingDivider}
606 + onSelectPendingTask={props.onSelectPendingTask}
607 + onDeletePendingTask={props.onDeletePendingTask}
608 />
609 );
813 - },
814 - [
815 - handleDeleteThread,
816 - handleOpenThreadPullRequests,
817 - activeReorderEnvironmentIds,
818 - handleMoveThread,
819 - handlePinThread,
820 - handleRegenerateThreadTitle,
821 - handleRenameThread,
822 - handleSettleThread,
823 - handleSnoozeThread,
824 - handleUnpinThread,
825 - handleUnsnoozeThread,
826 - handleSwipeableClose,
827 - handleSwipeableWillOpen,
828 - handleUnsettleThread,
829 - handleSetThreadAutoSettle,
830 - homeScrollGesture,
831 - autoSettleOptOutEnvironmentIds,
832 - pinningEnvironmentIds,
833 - autoSettleOptOutEnvironmentIds,
834 - machineByEnvironmentId,
835 - pinReorderEnvironmentIds,
836 - projectByKey,
837 - props.onArchiveThread,
838 - props.onDeletePendingTask,
839 - props.onSelectPendingTask,
840 - props.onSelectThread,
841 - primaryColumn,
842 - selectedThreadKey,
843 - fullSwipeWidth,
844 - props.onNewThreadOnBranch,
845 - props.savedConnectionsById,
846 - resolveProviderInstance,
847 - providersByEnvironmentId,
848 - settlementEnvironmentIds,
849 - snoozeEnvironmentIds,
850 - threadSearchMatchByKey,
851 - titleRegenerationEnvironmentIds,
852 - toggleSettledShelf,
853 - toggleSnoozedShelf,
854 - toggleWorkingShelf,
855 - v2ProjectTitleByProjectKey,
856 - props.searchQuery,
857 - workingShelfEnabled,
858 - ],
859 - );
860 - const v2KeyExtractor = useCallback((item: ThreadListV2ListItem) => item.key, []);
610 + }
611 + if (item.type === "v2-working-shelf") {
612 + return (
613 + <ThreadListV2WorkingShelfHeader
614 + count={item.count}
615 + disabled={item.disabled}
616 + expanded={item.expanded}
617 + onToggle={toggleWorkingShelf}
618 + />
619 + );
620 + }
621 + if (item.type === "v2-snoozed-shelf") {
622 + return (
623 + <ThreadListV2SnoozedShelfHeader
624 + count={item.count}
625 + disabled={item.disabled}
626 + expanded={item.expanded}
627 + onToggle={toggleSnoozedShelf}
628 + />
629 + );
630 + }
631 + if (item.type === "v2-settled-shelf") {
632 + return (
633 + <ThreadListV2SettledShelfHeader
634 + count={item.count}
635 + disabled={item.disabled}
636 + expanded={item.expanded}
637 + onToggle={toggleSettledShelf}
638 + />
639 + );
640 + }
641 + const thread = item.item.thread;
642 + return (
643 + <ThreadListV2Row
644 + pane={primaryColumn ? "sidebar" : "screen"}
645 + selected={scopedThreadKey(thread.environmentId, thread.id) === selectedThreadKey}
646 + fullSwipeWidth={fullSwipeWidth}
647 + onNewThreadOnBranch={props.onNewThreadOnBranch}
648 + thread={thread}
649 + variant={item.item.variant}
650 + hasQueuedMessages={item.hasQueuedMessages}
651 + snoozed={item.item.snoozed}
652 + pinned={item.item.pinned}
653 + snoozePresetMinute={item.snoozePresetMinute ?? ""}
654 + snoozeWakeLabelText={item.snoozeWakeLabelText}
655 + timeLabel={item.timeLabel}
656 + showTrailingDivider={item.showTrailingDivider}
657 + project={projectByKey.get(scopedProjectKey(thread.environmentId, thread.projectId)) ?? null}
658 + projectTitle={v2ProjectTitleByProjectKey.get(
659 + scopedProjectKey(thread.environmentId, thread.projectId),
660 + )}
661 + providerInstance={resolveProviderInstance(thread)}
662 + providers={providersByEnvironmentId.get(thread.environmentId)}
663 + environmentLabel={
664 + Object.keys(props.savedConnectionsById).length > 1
665 + ? (props.savedConnectionsById[thread.environmentId]?.environmentLabel ?? null)
666 + : null
667 + }
668 + environmentMachine={machineByEnvironmentId.get(thread.environmentId)}
669 + searchMatch={threadSearchMatchByKey.get(
670 + threadSearchMatchKey({
671 + environmentId: thread.environmentId,
672 + threadId: thread.id,
673 + }),
674 + )}
675 + searchQuery={props.searchQuery}
676 + onSelectThread={props.onSelectThread}
677 + onOpenThreadPullRequests={handleOpenThreadPullRequests}
678 + onDeleteThread={handleDeleteThread}
679 + onArchiveThread={props.onArchiveThread}
680 + onRenameThread={handleRenameThread}
681 + onRegenerateThreadTitle={handleRegenerateThreadTitle}
682 + titleRegenerationSupported={titleRegenerationEnvironmentIds.has(thread.environmentId)}
683 + settlementSupported={settlementEnvironmentIds.has(thread.environmentId)}
684 + onSettleThread={handleSettleThread}
685 + snoozeSupported={snoozeEnvironmentIds.has(thread.environmentId)}
686 + pinningSupported={pinningEnvironmentIds.has(thread.environmentId)}
687 + autoSettleOptOutSupported={autoSettleOptOutEnvironmentIds.has(thread.environmentId)}
688 + reorderSupported={
689 + item.item.pinned
690 + ? pinReorderEnvironmentIds.has(thread.environmentId)
691 + : !workingShelfEnabled && activeReorderEnvironmentIds.has(thread.environmentId)
692 + }
693 + canMoveUp={item.canMoveUp}
694 + canMoveDown={item.canMoveDown}
695 + onSnoozeThread={handleSnoozeThread}
696 + onUnsnoozeThread={handleUnsnoozeThread}
697 + onUnsettleThread={handleUnsettleThread}
698 + onPinThread={handlePinThread}
699 + onUnpinThread={handleUnpinThread}
700 + onSetThreadAutoSettle={handleSetThreadAutoSettle}
701 + onMoveThread={handleMoveThread}
702 + onSwipeableClose={handleSwipeableClose}
703 + onSwipeableWillOpen={handleSwipeableWillOpen}
704 + simultaneousSwipeGesture={homeScrollGesture}
705 + activationKey={item.key}
706 + />
707 + );
708 + };
709 + const v2KeyExtractor = (item: ThreadListV2ListItem) => item.key;
710
711 // FlatList/LegendList treat a changed extraData identity as "re-render every
712 // visible row", so an inline object literal would invalidate all rows on
713 // every HomeScreen render — and the minute clock must stay out of it for
714 // the same reason: the clock text is precomputed per item instead.
866 - const v2ExtraData = useMemo(
867 - () => ({
868 - projectByKey,
869 - projectTitleByProjectKey: v2ProjectTitleByProjectKey,
870 - listEnvironments,
871 - savedConnectionsById: props.savedConnectionsById,
872 - searchQuery: props.searchQuery,
873 - selectedThreadKey,
874 - threadSearchMatchByKey,
875 - workingShelfEnabled,
876 - }),
877 - [
878 - projectByKey,
879 - props.searchQuery,
880 - selectedThreadKey,
881 - props.savedConnectionsById,
882 - listEnvironments,
883 - threadSearchMatchByKey,
884 - v2ProjectTitleByProjectKey,
885 - workingShelfEnabled,
886 - ],
887 - );
715 + const v2ExtraData = {
716 + projectByKey,
717 + projectTitleByProjectKey: v2ProjectTitleByProjectKey,
718 + listEnvironments,
719 + savedConnectionsById: props.savedConnectionsById,
720 + searchQuery: props.searchQuery,
721 + selectedThreadKey,
722 + threadSearchMatchByKey,
723 + workingShelfEnabled,
724 + };
725
726 const hasAnyThreads =
727 props.threads.some((thread) => thread.archivedAt === null) || props.pendingTasks.length > 0;
apps/mobile/src/features/home/WorkspaceConnectionTitle.tsx
+2 -2
@@ -1,5 +1,5 @@
1 import type { NativeStackNavigationOptions } from "@react-navigation/native-stack";
2 -import { useEffect, useRef, useState, type ReactNode } from "react";
2 +import { useEffect, useState, type ReactNode } from "react";
3 import { Animated, Platform, Pressable, View } from "react-native";
4
5 import { AppActivityIndicator } from "../../components/ui/AppActivityIndicator";
@@ -49,7 +49,7 @@ function StatusFadeIn(props: {
49 readonly grow?: boolean;
50 readonly maxWidth?: number;
51 }) {
52 - const opacity = useRef(new Animated.Value(0)).current;
52 + const [opacity] = useState(() => new Animated.Value(0));
53
54 useEffect(() => {
55 const animation = Animated.timing(opacity, {
apps/mobile/src/features/home/home-list-options.ts
+8 -16
@@ -4,10 +4,8 @@ import { useAtomSet } from "@effect/atom-react";
4 import {
5 createContext,
6 createElement,
7 - useCallback,
7 useContext,
8 useEffect,
10 - useMemo,
9 useRef,
10 useState,
11 type PropsWithChildren,
@@ -69,10 +67,7 @@ export function HomeListOptionsProvider({
67 saved.current = { environmentId, projectKey };
68 savePreferences({ threadListFilters: saved.current });
69 }, [environmentId, projectKey, savePreferences]);
72 - const value = useMemo(
73 - () => ({ options, setOptions, projectGroupingMode }),
74 - [options, projectGroupingMode],
75 - );
70 + const value = { options, setOptions, projectGroupingMode };
71 return createElement(HomeListOptionsContext, { value }, children);
72 }
73
@@ -95,18 +90,15 @@ export function useHomeListOptions(availableEnvironmentIds: ReadonlySet<Environm
90 projectGroupingMode: shared?.projectGroupingMode ?? "repository",
91 };
92
98 - const setSelectedEnvironmentId = useCallback((value: EnvironmentId | null) => {
93 + const setSelectedEnvironmentId = (value: EnvironmentId | null) => {
94 setOptions((current) => ({ ...current, selectedEnvironmentId: value }));
100 - }, []);
101 - const setSelectedProjectKey = useCallback(
102 - (value: string | null) => {
103 - setOptions((current) => ({ ...current, selectedProjectKey: value }));
104 - },
105 - [setOptions],
106 - );
107 - const setProjectSortOrder = useCallback((value: HomeProjectSortOrder) => {
95 + };
96 + const setSelectedProjectKey = (value: string | null) => {
97 + setOptions((current) => ({ ...current, selectedProjectKey: value }));
98 + };
99 + const setProjectSortOrder = (value: HomeProjectSortOrder) => {
100 setOptions((current) => ({ ...current, projectSortOrder: value }));
109 - }, []);
101 + };
102 return {
103 options: resolvedOptions,
104 setSelectedEnvironmentId,
apps/mobile/src/features/home/useThreadListActions.ts
+437 -500
@@ -4,7 +4,7 @@ import { canSnooze, effectiveSnoozed } from "@t3tools/client-runtime/state/threa
4 import { AuthOrchestrationOperateScope } from "@t3tools/contracts";
5 import * as Cause from "effect/Cause";
6 import * as Haptics from "expo-haptics";
7 -import { useCallback, useRef } from "react";
7 +import { useRef } from "react";
8
9 import { withThreadDismissal } from "./thread-dismissal";
10 import * as Dialog from "../../components/ui/Dialog";
@@ -125,104 +125,92 @@ function useThreadActionExecutor(
125 const unsettleMutation = useAtomCommand(threadEnvironment.unsettle, { reportFailure: false });
126 const inFlightThreadKeys = useRef(new Set<string>());
127
128 - const executeAction = useCallback(
129 - async (action: ThreadListAction, thread: EnvironmentThreadShell) => {
130 - if (!checkThreadOperationPermission(thread, actionFailureTitle(action))) return false;
131 - const key = scopedThreadKey(thread.environmentId, thread.id);
132 - if (inFlightThreadKeys.current.has(key)) {
128 + const executeAction = async (action: ThreadListAction, thread: EnvironmentThreadShell) => {
129 + if (!checkThreadOperationPermission(thread, actionFailureTitle(action))) return false;
130 + const key = scopedThreadKey(thread.environmentId, thread.id);
131 + if (inFlightThreadKeys.current.has(key)) {
132 + return false;
133 + }
134 +
135 + inFlightThreadKeys.current.add(key);
136 + selectionHaptic();
137 + const succeeded = await (async () => {
138 + if (
139 + (action === "settle" || action === "unsettle") &&
140 + !environmentSupportsSettlement(thread.environmentId)
141 + ) {
142 + Dialog.alert(
143 + actionFailureTitle(action),
144 + "This environment's server does not support settling yet. Update the server to use Settle.",
145 + );
146 return false;
147 }
135 -
136 - inFlightThreadKeys.current.add(key);
137 - selectionHaptic();
138 - try {
139 - if (
140 - (action === "settle" || action === "unsettle") &&
141 - !environmentSupportsSettlement(thread.environmentId)
142 - ) {
143 - Dialog.alert(
144 - actionFailureTitle(action),
145 - "This environment's server does not support settling yet. Update the server to use Settle.",
146 - );
147 - return false;
148 - }
149 - if (action === "archive" && !threadCanArchive(thread.runtime)) {
150 - Dialog.alert(
151 - actionFailureTitle(action),
152 - "This thread is working. Interrupt it first, then try again.",
153 - );
154 - return false;
155 - }
156 - const result = await withThreadDismissal(
157 - key,
158 - async () =>
159 - action === "unsettle"
160 - ? // reason "user" pins the thread active: auto-settle stays
161 - // suppressed until real activity clears the pin server-side.
162 - await unsettleMutation({
163 - environmentId: thread.environmentId,
164 - input: { threadId: thread.id, reason: "user" },
165 - })
166 - : await (
167 - action === "settle"
168 - ? settleMutation
169 - : action === "archive"
170 - ? archiveMutation
171 - : action === "unarchive"
172 - ? unarchiveMutation
173 - : deleteMutation
174 - )({
175 - environmentId: thread.environmentId,
176 - input: { threadId: thread.id },
177 - }),
178 - (result) => result._tag === "Success",
148 + if (action === "archive" && !threadCanArchive(thread.runtime)) {
149 + Dialog.alert(
150 + actionFailureTitle(action),
151 + "This thread is working. Interrupt it first, then try again.",
152 );
180 - if (result._tag === "Failure") {
181 - Dialog.alert(actionFailureTitle(action), actionFailureMessage(action, result.cause));
182 - return false;
183 - }
184 - if (action === "archive" || action === "unarchive" || action === "delete") {
185 - refreshArchivedThreadsForEnvironment(thread.environmentId);
186 - }
187 - onCompleted?.(action, thread);
188 - return true;
189 - } finally {
190 - inFlightThreadKeys.current.delete(key);
153 + return false;
154 }
192 - },
193 - [
194 - archiveMutation,
195 - deleteMutation,
196 - onCompleted,
197 - settleMutation,
198 - unarchiveMutation,
199 - unsettleMutation,
200 - ],
201 - );
155 + const result = await withThreadDismissal(
156 + key,
157 + async () =>
158 + action === "unsettle"
159 + ? // reason "user" pins the thread active: auto-settle stays
160 + // suppressed until real activity clears the pin server-side.
161 + await unsettleMutation({
162 + environmentId: thread.environmentId,
163 + input: { threadId: thread.id, reason: "user" },
164 + })
165 + : await (
166 + action === "settle"
167 + ? settleMutation
168 + : action === "archive"
169 + ? archiveMutation
170 + : action === "unarchive"
171 + ? unarchiveMutation
172 + : deleteMutation
173 + )({
174 + environmentId: thread.environmentId,
175 + input: { threadId: thread.id },
176 + }),
177 + (result) => result._tag === "Success",
178 + );
179 + if (result._tag === "Failure") {
180 + Dialog.alert(actionFailureTitle(action), actionFailureMessage(action, result.cause));
181 + return false;
182 + }
183 + if (action === "archive" || action === "unarchive" || action === "delete") {
184 + refreshArchivedThreadsForEnvironment(thread.environmentId);
185 + }
186 + onCompleted?.(action, thread);
187 + return true;
188 + })();
189 + inFlightThreadKeys.current.delete(key);
190 + return succeeded;
191 + };
192
193 return executeAction;
194 }
195
206 -function useConfirmDeleteThread(
196 +// A plain function, not a hook: a `use*` function that calls no hooks is skipped by
197 +// the compiler, so the delete handler it returned was a new closure every render.
198 +function confirmThreadDeletion(
199 executeAction: (action: ThreadListAction, thread: EnvironmentThreadShell) => Promise<boolean>,
200 + thread: EnvironmentThreadShell,
201 ) {
209 - return useCallback(
210 - (thread: EnvironmentThreadShell) => {
211 - if (!checkThreadOperationPermission(thread, actionFailureTitle("delete"))) return;
212 - const title = "Delete thread?";
213 - const message = `“${thread.title}” will be permanently deleted, including its terminal history.`;
214 - Dialog.confirm({
215 - title,
216 - message,
217 - confirmText: "Delete",
218 - destructive: true,
219 - onConfirm: () => {
220 - void executeAction("delete", thread);
221 - },
222 - });
202 + if (!checkThreadOperationPermission(thread, actionFailureTitle("delete"))) return;
203 + const title = "Delete thread?";
204 + const message = `“${thread.title}” will be permanently deleted, including its terminal history.`;
205 + Dialog.confirm({
206 + title,
207 + message,
208 + confirmText: "Delete",
209 + destructive: true,
210 + onConfirm: () => {
211 + void executeAction("delete", thread);
212 },
224 - [executeAction],
225 - );
213 + });
214 }
215
216 export function useThreadListActions(): {
@@ -259,296 +247,265 @@ export function useThreadListActions(): {
247 const snoozeInFlightThreadKeys = useRef(new Set<string>());
248 const titleRegenerationInFlightThreadKeys = useRef(new Set<string>());
249
262 - const archiveThread = useCallback(
263 - (thread: EnvironmentThreadShell) => {
264 - void executeAction("archive", thread);
265 - },
266 - [executeAction],
267 - );
268 - const settleThread = useCallback(
269 - async (thread: EnvironmentThreadShell) => (await executeAction("settle", thread)) === true,
270 - [executeAction],
271 - );
272 - const snoozeThread = useCallback(
273 - async (thread: EnvironmentThreadShell, snoozedUntil: string) => {
274 - if (!checkThreadOperationPermission(thread, "Could not snooze thread")) return false;
275 - const key = scopedThreadKey(thread.environmentId, thread.id);
276 - if (snoozeInFlightThreadKeys.current.has(key)) {
277 - return false;
278 - }
279 - snoozeInFlightThreadKeys.current.add(key);
280 - try {
281 - if (!environmentSupportsSnooze(thread.environmentId)) {
282 - Dialog.alert(
283 - "Could not snooze thread",
284 - "This environment's server does not support snoozing yet. Update the server to use Snooze.",
285 - );
286 - return false;
287 - }
288 - if (!canSnooze(thread, { now: new Date().toISOString() })) {
289 - Dialog.alert(
290 - "Could not snooze thread",
291 - thread.hasPendingApprovals ||
292 - thread.hasPendingUserInput ||
293 - thread.pendingSubagentRequest != null
294 - ? "This thread is waiting on you. Respond to the pending request before snoozing it."
295 - : "This thread is still starting a turn. Try again once it's running.",
296 - );
297 - return false;
298 - }
299 -
300 - selectionHaptic();
301 - const result = await withThreadDismissal(
302 - key,
303 - () =>
304 - snoozeMutation({
305 - environmentId: thread.environmentId,
306 - input: {
307 - threadId: thread.id,
308 - snoozedUntil,
309 - },
310 - }),
311 - (result) => result._tag === "Success",
250 + const archiveThread = (thread: EnvironmentThreadShell) => {
251 + void executeAction("archive", thread);
252 + };
253 + const settleThread = async (thread: EnvironmentThreadShell) =>
254 + (await executeAction("settle", thread)) === true;
255 + const snoozeThread = async (thread: EnvironmentThreadShell, snoozedUntil: string) => {
256 + if (!checkThreadOperationPermission(thread, "Could not snooze thread")) return false;
257 + const key = scopedThreadKey(thread.environmentId, thread.id);
258 + if (snoozeInFlightThreadKeys.current.has(key)) {
259 + return false;
260 + }
261 + snoozeInFlightThreadKeys.current.add(key);
262 + const succeeded = await (async () => {
263 + if (!environmentSupportsSnooze(thread.environmentId)) {
264 + Dialog.alert(
265 + "Could not snooze thread",
266 + "This environment's server does not support snoozing yet. Update the server to use Snooze.",
267 );
313 - if (result._tag === "Failure") {
314 - const error = Cause.squash(result.cause);
315 - Dialog.alert(
316 - "Could not snooze thread",
317 - error instanceof Error && error.message.trim().length > 0
318 - ? error.message
319 - : "The thread could not be snoozed.",
320 - );
321 - return false;
322 - }
323 - return true;
324 - } finally {
325 - snoozeInFlightThreadKeys.current.delete(key);
326 - }
327 - },
328 - [snoozeMutation],
329 - );
330 - const unsnoozeThread = useCallback(
331 - async (thread: EnvironmentThreadShell) => {
332 - if (!checkThreadOperationPermission(thread, "Could not wake thread")) return false;
333 - const key = scopedThreadKey(thread.environmentId, thread.id);
334 - if (snoozeInFlightThreadKeys.current.has(key)) {
268 return false;
269 }
337 - snoozeInFlightThreadKeys.current.add(key);
338 - try {
339 - if (!environmentSupportsSnooze(thread.environmentId)) {
340 - Dialog.alert(
341 - "Could not wake thread",
342 - "This environment's server does not support snoozing yet. Update the server to wake this thread.",
343 - );
344 - return false;
345 - }
346 -
347 - selectionHaptic();
348 - const result = await withThreadDismissal(
349 - key,
350 - () =>
351 - unsnoozeMutation({
352 - environmentId: thread.environmentId,
353 - input: { threadId: thread.id, reason: "user" },
354 - }),
355 - (result) => result._tag === "Success",
356 - );
357 - if (result._tag === "Failure") {
358 - const error = Cause.squash(result.cause);
359 - Dialog.alert(
360 - "Could not wake thread",
361 - error instanceof Error && error.message.trim().length > 0
362 - ? error.message
363 - : "The thread could not be woken.",
364 - );
365 - return false;
366 - }
367 - return true;
368 - } finally {
369 - snoozeInFlightThreadKeys.current.delete(key);
370 - }
371 - },
372 - [unsnoozeMutation],
373 - );
374 - const unsettleThread = useCallback(
375 - async (thread: EnvironmentThreadShell) => (await executeAction("unsettle", thread)) === true,
376 - [executeAction],
377 - );
378 - const pinThread = useCallback(
379 - async (thread: EnvironmentThreadShell) => {
380 - if (!checkThreadOperationPermission(thread, "Could not pin thread")) return false;
381 - if (!environmentSupportsPinning(thread.environmentId)) {
270 + if (!canSnooze(thread, { now: new Date().toISOString() })) {
271 Dialog.alert(
383 - "Could not pin thread",
384 - "This environment's server does not support pinning yet. Update the server to use Pin.",
272 + "Could not snooze thread",
273 + thread.hasPendingApprovals ||
274 + thread.hasPendingUserInput ||
275 + thread.pendingSubagentRequest != null
276 + ? "This thread is waiting on you. Respond to the pending request before snoozing it."
277 + : "This thread is still starting a turn. Try again once it's running.",
278 );
279 return false;
280 }
281 +
282 selectionHaptic();
389 - // Same placement as web: a fresh pin takes the top of the arranged
390 - // run. Servers that predate reordering get the bare pin (keyless).
391 - let orderKey: string | undefined;
392 - if (environmentSupportsPinReorder(thread.environmentId)) {
393 - const shells = appAtomRegistry.get(environmentThreadShells.threadShellsAtom);
394 - let firstKey: string | null = null;
395 - for (const shell of shells) {
396 - if (shell.pinnedAt == null || shell.pinOrderKey == null) continue;
397 - if (firstKey === null || shell.pinOrderKey < firstKey) firstKey = shell.pinOrderKey;
398 - }
399 - orderKey = pinOrderKeyBetween(null, firstKey) ?? undefined;
400 - }
401 - const result = await pinMutation({
402 - environmentId: thread.environmentId,
403 - input: { threadId: thread.id, ...(orderKey !== undefined ? { orderKey } : {}) },
404 - });
283 + const result = await withThreadDismissal(
284 + key,
285 + () =>
286 + snoozeMutation({
287 + environmentId: thread.environmentId,
288 + input: {
289 + threadId: thread.id,
290 + snoozedUntil,
291 + },
292 + }),
293 + (result) => result._tag === "Success",
294 + );
295 if (result._tag === "Failure") {
296 const error = Cause.squash(result.cause);
297 Dialog.alert(
408 - "Could not pin thread",
298 + "Could not snooze thread",
299 error instanceof Error && error.message.trim().length > 0
300 ? error.message
411 - : "The thread could not be pinned.",
301 + : "The thread could not be snoozed.",
302 );
303 return false;
304 }
305 return true;
416 - },
417 - [pinMutation],
418 - );
419 - const unpinThread = useCallback(
420 - async (thread: EnvironmentThreadShell) => {
421 - if (!checkThreadOperationPermission(thread, "Could not unpin thread")) return false;
422 - if (!environmentSupportsPinning(thread.environmentId)) {
306 + })();
307 + snoozeInFlightThreadKeys.current.delete(key);
308 + return succeeded;
309 + };
310 + const unsnoozeThread = async (thread: EnvironmentThreadShell) => {
311 + if (!checkThreadOperationPermission(thread, "Could not wake thread")) return false;
312 + const key = scopedThreadKey(thread.environmentId, thread.id);
313 + if (snoozeInFlightThreadKeys.current.has(key)) {
314 + return false;
315 + }
316 + snoozeInFlightThreadKeys.current.add(key);
317 + const succeeded = await (async () => {
318 + if (!environmentSupportsSnooze(thread.environmentId)) {
319 Dialog.alert(
424 - "Could not unpin thread",
425 - "This environment's server does not support pinning yet. Update the server to use Pin.",
320 + "Could not wake thread",
321 + "This environment's server does not support snoozing yet. Update the server to wake this thread.",
322 );
323 return false;
324 }
325 +
326 selectionHaptic();
430 - const result = await unpinMutation({
431 - environmentId: thread.environmentId,
432 - input: { threadId: thread.id },
433 - });
327 + const result = await withThreadDismissal(
328 + key,
329 + () =>
330 + unsnoozeMutation({
331 + environmentId: thread.environmentId,
332 + input: { threadId: thread.id, reason: "user" },
333 + }),
334 + (result) => result._tag === "Success",
335 + );
336 if (result._tag === "Failure") {
337 const error = Cause.squash(result.cause);
338 Dialog.alert(
437 - "Could not unpin thread",
339 + "Could not wake thread",
340 error instanceof Error && error.message.trim().length > 0
341 ? error.message
440 - : "The thread could not be unpinned.",
342 + : "The thread could not be woken.",
343 );
344 return false;
345 }
346 return true;
445 - },
446 - [unpinMutation],
447 - );
448 - const setThreadAutoSettle = useCallback(
449 - async (thread: EnvironmentThreadShell, enabled: boolean) => {
450 - if (!environmentSupportsAutoSettleOptOut(thread.environmentId)) {
451 - Dialog.alert(
452 - "Could not update auto-settle",
453 - "This environment's server does not support turning auto-settle off per thread yet. Update the server to use it.",
454 - );
455 - return false;
347 + })();
348 + snoozeInFlightThreadKeys.current.delete(key);
349 + return succeeded;
350 + };
351 + const unsettleThread = async (thread: EnvironmentThreadShell) =>
352 + (await executeAction("unsettle", thread)) === true;
353 + const pinThread = async (thread: EnvironmentThreadShell) => {
354 + if (!checkThreadOperationPermission(thread, "Could not pin thread")) return false;
355 + if (!environmentSupportsPinning(thread.environmentId)) {
356 + Dialog.alert(
357 + "Could not pin thread",
358 + "This environment's server does not support pinning yet. Update the server to use Pin.",
359 + );
360 + return false;
361 + }
362 + selectionHaptic();
363 + // Same placement as web: a fresh pin takes the top of the arranged
364 + // run. Servers that predate reordering get the bare pin (keyless).
365 + let orderKey: string | undefined;
366 + if (environmentSupportsPinReorder(thread.environmentId)) {
367 + const shells = appAtomRegistry.get(environmentThreadShells.threadShellsAtom);
368 + let firstKey: string | null = null;
369 + for (const shell of shells) {
370 + if (shell.pinnedAt == null || shell.pinOrderKey == null) continue;
371 + if (firstKey === null || shell.pinOrderKey < firstKey) firstKey = shell.pinOrderKey;
372 }
457 - selectionHaptic();
458 - const result = await setAutoSettleMutation({
373 + orderKey = pinOrderKeyBetween(null, firstKey) ?? undefined;
374 + }
375 + const result = await pinMutation({
376 + environmentId: thread.environmentId,
377 + input: { threadId: thread.id, ...(orderKey !== undefined ? { orderKey } : {}) },
378 + });
379 + if (result._tag === "Failure") {
380 + const error = Cause.squash(result.cause);
381 + Dialog.alert(
382 + "Could not pin thread",
383 + error instanceof Error && error.message.trim().length > 0
384 + ? error.message
385 + : "The thread could not be pinned.",
386 + );
387 + return false;
388 + }
389 + return true;
390 + };
391 + const unpinThread = async (thread: EnvironmentThreadShell) => {
392 + if (!checkThreadOperationPermission(thread, "Could not unpin thread")) return false;
393 + if (!environmentSupportsPinning(thread.environmentId)) {
394 + Dialog.alert(
395 + "Could not unpin thread",
396 + "This environment's server does not support pinning yet. Update the server to use Pin.",
397 + );
398 + return false;
399 + }
400 + selectionHaptic();
401 + const result = await unpinMutation({
402 + environmentId: thread.environmentId,
403 + input: { threadId: thread.id },
404 + });
405 + if (result._tag === "Failure") {
406 + const error = Cause.squash(result.cause);
407 + Dialog.alert(
408 + "Could not unpin thread",
409 + error instanceof Error && error.message.trim().length > 0
410 + ? error.message
411 + : "The thread could not be unpinned.",
412 + );
413 + return false;
414 + }
415 + return true;
416 + };
417 + const setThreadAutoSettle = async (thread: EnvironmentThreadShell, enabled: boolean) => {
418 + if (!environmentSupportsAutoSettleOptOut(thread.environmentId)) {
419 + Dialog.alert(
420 + "Could not update auto-settle",
421 + "This environment's server does not support turning auto-settle off per thread yet. Update the server to use it.",
422 + );
423 + return false;
424 + }
425 + selectionHaptic();
426 + const result = await setAutoSettleMutation({
427 + environmentId: thread.environmentId,
428 + input: { threadId: thread.id, enabled },
429 + });
430 + if (result._tag === "Failure") {
431 + const error = Cause.squash(result.cause);
432 + Dialog.alert(
433 + "Could not update auto-settle",
434 + error instanceof Error && error.message.trim().length > 0
435 + ? error.message
436 + : "The auto-settle setting could not be changed.",
437 + );
438 + return false;
439 + }
440 + return true;
441 + };
442 + const regenerateThreadTitle = async (thread: EnvironmentThreadShell) => {
443 + if (!checkThreadOperationPermission(thread, "Could not regenerate title")) return false;
444 + const key = scopedThreadKey(thread.environmentId, thread.id);
445 + if (thread.titleRegeneration != null || titleRegenerationInFlightThreadKeys.current.has(key)) {
446 + return false;
447 + }
448 + if (!environmentSupportsTitleRegeneration(thread.environmentId)) {
449 + Dialog.alert(
450 + "Could not regenerate title",
451 + "This environment's server does not support title regeneration yet. Update the server to regenerate thread titles.",
452 + );
453 + return false;
454 + }
455 +
456 + titleRegenerationInFlightThreadKeys.current.add(key);
457 + selectionHaptic();
458 + const succeeded = await (async () => {
459 + const result = await updateThreadMetadata({
460 environmentId: thread.environmentId,
460 - input: { threadId: thread.id, enabled },
461 + input: { threadId: thread.id, regenerateTitle: true },
462 });
463 if (result._tag === "Failure") {
464 const error = Cause.squash(result.cause);
465 Dialog.alert(
465 - "Could not update auto-settle",
466 + "Could not regenerate title",
467 error instanceof Error && error.message.trim().length > 0
468 ? error.message
468 - : "The auto-settle setting could not be changed.",
469 + : "The thread title could not be regenerated.",
470 );
471 return false;
472 }
473 return true;
473 - },
474 - [setAutoSettleMutation],
475 - );
476 - const regenerateThreadTitle = useCallback(
477 - async (thread: EnvironmentThreadShell) => {
478 - if (!checkThreadOperationPermission(thread, "Could not regenerate title")) return false;
479 - const key = scopedThreadKey(thread.environmentId, thread.id);
480 - if (
481 - thread.titleRegeneration != null ||
482 - titleRegenerationInFlightThreadKeys.current.has(key)
483 - ) {
484 - return false;
474 + })();
475 + titleRegenerationInFlightThreadKeys.current.delete(key);
476 + return succeeded;
477 + };
478 + const renameThread = (thread: EnvironmentThreadShell) => {
479 + const commit = (title: string) => {
480 + const resolution = resolveThreadTitleRename({ title, originalTitle: thread.title });
481 + if (resolution.action === "reject-empty") {
482 + Dialog.alert("Could not rename thread", "Thread title cannot be empty.");
483 + return;
484 }
486 - if (!environmentSupportsTitleRegeneration(thread.environmentId)) {
485 + if (resolution.action === "noop") return;
486 + selectionHaptic();
487 + void updateThreadMetadata({
488 + environmentId: thread.environmentId,
489 + input: { threadId: thread.id, title: resolution.title },
490 + }).then((result) => {
491 + if (result._tag === "Success") return;
492 + const error = Cause.squash(result.cause);
493 Dialog.alert(
488 - "Could not regenerate title",
489 - "This environment's server does not support title regeneration yet. Update the server to regenerate thread titles.",
494 + "Could not rename thread",
495 + error instanceof Error && error.message.trim().length > 0
496 + ? error.message
497 + : "The thread could not be renamed.",
498 );
491 - return false;
492 - }
493 -
494 - titleRegenerationInFlightThreadKeys.current.add(key);
495 - selectionHaptic();
496 - try {
497 - const result = await updateThreadMetadata({
498 - environmentId: thread.environmentId,
499 - input: { threadId: thread.id, regenerateTitle: true },
500 - });
501 - if (result._tag === "Failure") {
502 - const error = Cause.squash(result.cause);
503 - Dialog.alert(
504 - "Could not regenerate title",
505 - error instanceof Error && error.message.trim().length > 0
506 - ? error.message
507 - : "The thread title could not be regenerated.",
508 - );
509 - return false;
510 - }
511 - return true;
512 - } finally {
513 - titleRegenerationInFlightThreadKeys.current.delete(key);
514 - }
515 - },
516 - [updateThreadMetadata],
517 - );
518 - const renameThread = useCallback(
519 - (thread: EnvironmentThreadShell) => {
520 - const commit = (title: string) => {
521 - const resolution = resolveThreadTitleRename({ title, originalTitle: thread.title });
522 - if (resolution.action === "reject-empty") {
523 - Dialog.alert("Could not rename thread", "Thread title cannot be empty.");
524 - return;
525 - }
526 - if (resolution.action === "noop") return;
527 - selectionHaptic();
528 - void updateThreadMetadata({
529 - environmentId: thread.environmentId,
530 - input: { threadId: thread.id, title: resolution.title },
531 - }).then((result) => {
532 - if (result._tag === "Success") return;
533 - const error = Cause.squash(result.cause);
534 - Dialog.alert(
535 - "Could not rename thread",
536 - error instanceof Error && error.message.trim().length > 0
537 - ? error.message
538 - : "The thread could not be renamed.",
539 - );
540 - });
541 - };
542 -
543 - Dialog.prompt({
544 - title: "Rename thread",
545 - initialValue: thread.title,
546 - confirmText: "Rename",
547 - onConfirm: commit,
499 });
549 - },
550 - [updateThreadMetadata],
551 - );
500 + };
501 +
502 + Dialog.prompt({
503 + title: "Rename thread",
504 + initialValue: thread.title,
505 + confirmText: "Rename",
506 + onConfirm: commit,
507 + });
508 + };
509
510 // Plan against the complete section so filtering does not change a move.
511 const reorderPinnedMutation = useAtomCommand(threadEnvironment.reorderPin, {
@@ -557,172 +514,157 @@ export function useThreadListActions(): {
514 const reorderActiveMutation = useAtomCommand(threadEnvironment.reorderActive, {
515 reportFailure: false,
516 });
560 - const moveThread = useCallback(
561 - async (thread: EnvironmentThreadShell, direction: ThreadMoveDestination) => {
562 - if (!checkThreadOperationPermission(thread, "Could not move thread")) return false;
563 - if (getPendingThreadOrder() !== null || appAtomRegistry.get(threadDropBusyAtom)) return false;
564 - const shells = appAtomRegistry.get(environmentThreadShells.threadShellsAtom);
565 - const current = shells.find(
566 - (row) => row.id === thread.id && row.environmentId === thread.environmentId,
517 + const moveThread = async (thread: EnvironmentThreadShell, direction: ThreadMoveDestination) => {
518 + if (!checkThreadOperationPermission(thread, "Could not move thread")) return false;
519 + if (getPendingThreadOrder() !== null || appAtomRegistry.get(threadDropBusyAtom)) return false;
520 + const shells = appAtomRegistry.get(environmentThreadShells.threadShellsAtom);
521 + const current = shells.find(
522 + (row) => row.id === thread.id && row.environmentId === thread.environmentId,
523 + );
524 + if (!current || current.archivedAt !== null) return false;
525 + thread = current;
526 + const section =
527 + typeof direction === "object" && direction.section !== undefined
528 + ? direction.section
529 + : thread.pinnedAt != null
530 + ? "pinned"
531 + : "active";
532 + if (section === "settled") {
533 + if (!environmentSupportsSettlement(thread.environmentId)) return false;
534 + appAtomRegistry.set(threadDropBusyAtom, true);
535 + const settled = await settleThread(thread);
536 + appAtomRegistry.set(threadDropBusyAtom, false);
537 + return settled;
538 + }
539 + const configs = appAtomRegistry.get(environmentServerConfigsAtom);
540 + const supportsReorder = (environmentId: EnvironmentThreadShell["environmentId"]) => {
541 + const capabilities = configs.get(environmentId)?.environment.capabilities;
542 + return section === "pinned"
543 + ? capabilities?.threadPinReorder === true
544 + : capabilities?.threadActiveReorder === true;
545 + };
546 + if (!supportsReorder(thread.environmentId)) {
547 + Dialog.alert(
548 + "Could not move thread",
549 + "This environment's server does not support reordering these threads. Update the server to arrange them.",
550 );
568 - if (!current || current.archivedAt !== null) return false;
569 - thread = current;
570 - const section =
571 - typeof direction === "object" && direction.section !== undefined
572 - ? direction.section
573 - : thread.pinnedAt != null
574 - ? "pinned"
575 - : "active";
576 - if (section === "settled") {
577 - if (!environmentSupportsSettlement(thread.environmentId)) return false;
578 - appAtomRegistry.set(threadDropBusyAtom, true);
579 - try {
580 - return await settleThread(thread);
581 - } finally {
582 - appAtomRegistry.set(threadDropBusyAtom, false);
583 - }
584 - }
585 - const configs = appAtomRegistry.get(environmentServerConfigsAtom);
586 - const supportsReorder = (environmentId: EnvironmentThreadShell["environmentId"]) => {
587 - const capabilities = configs.get(environmentId)?.environment.capabilities;
588 - return section === "pinned"
589 - ? capabilities?.threadPinReorder === true
590 - : capabilities?.threadActiveReorder === true;
591 - };
592 - if (!supportsReorder(thread.environmentId)) {
593 - Dialog.alert(
594 - "Could not move thread",
595 - "This environment's server does not support reordering these threads. Update the server to arrange them.",
596 - );
597 - return false;
598 - }
599 - const ordered = getThreadListV2OrderedSection({
600 - threads: shells,
601 - section,
602 - now: new Date().toISOString(),
603 - queuedThreadKeys: appAtomRegistry.get(queuedThreadKeysAtom),
604 - settlementEnvironmentIds: new Set(
605 - [...configs].flatMap(([id, config]) =>
606 - config.environment.capabilities.threadSettlement === true ? [id] : [],
607 - ),
551 + return false;
552 + }
553 + const ordered = getThreadListV2OrderedSection({
554 + threads: shells,
555 + section,
556 + now: new Date().toISOString(),
557 + queuedThreadKeys: appAtomRegistry.get(queuedThreadKeysAtom),
558 + settlementEnvironmentIds: new Set(
559 + [...configs].flatMap(([id, config]) =>
560 + config.environment.capabilities.threadSettlement === true ? [id] : [],
561 ),
609 - snoozeEnvironmentIds: new Set(
610 - [...configs].flatMap(([id, config]) =>
611 - config.environment.capabilities.threadSnooze === true ? [id] : [],
612 - ),
562 + ),
563 + snoozeEnvironmentIds: new Set(
564 + [...configs].flatMap(([id, config]) =>
565 + config.environment.capabilities.threadSnooze === true ? [id] : [],
566 ),
614 - });
615 - const assignments = createThreadMovePlanner({
616 - allThreads: shells,
617 - ordered,
618 - section,
619 - reorderableEnvironmentIds: new Set([...configs.keys()].filter(supportsReorder)),
620 - })(scopedThreadKey(thread.environmentId, thread.id), direction);
621 - if (assignments === null) return false;
622 - const lifecycle = threadDropLifecycle(thread, section, new Date().toISOString());
623 - const crossSection = !ordered.some(
624 - (row) => row.id === thread.id && row.environmentId === thread.environmentId,
625 - );
626 - if (
627 - crossSection &&
628 - (((section === "pinned" || thread.pinnedAt != null) &&
629 - !environmentSupportsPinning(thread.environmentId)) ||
630 - (thread.settledOverride === "settled" &&
631 - !environmentSupportsSettlement(thread.environmentId)) ||
632 - (effectiveSnoozed(thread, { now: new Date().toISOString() }) &&
633 - !environmentSupportsSnooze(thread.environmentId)))
634 - )
635 - return false;
636 - const shellByKey = new Map(
637 - shells.map((shell) => [scopedThreadKey(shell.environmentId, shell.id), shell]),
638 - );
639 - for (const assignment of assignments) {
640 - const target = shellByKey.get(assignment.id);
641 - if (target && !checkThreadOperationPermission(target, "Could not move thread"))
642 - return false;
643 - }
644 - selectionHaptic();
645 - appAtomRegistry.set(threadDropBusyAtom, true);
646 - const pending = crossSection
647 - ? null
648 - : beginPendingThreadOrder(
649 - createPendingThreadOrder({
650 - section,
651 - ordered,
652 - movedId: scopedThreadKey(thread.environmentId, thread.id),
653 - direction,
654 - assignments,
655 - }),
656 - );
657 - let succeeded = false;
658 - const reorder = section === "pinned" ? reorderPinnedMutation : reorderActiveMutation;
659 - try {
660 - if (crossSection) {
661 - if (section === "pinned") {
662 - const orderKey = assignments.find(
663 - ({ id }) => id === scopedThreadKey(thread.environmentId, thread.id),
664 - )?.orderKey;
665 - const result = await pinMutation({
666 - environmentId: thread.environmentId,
667 - input: { threadId: thread.id, ...(orderKey === undefined ? {} : { orderKey }) },
668 - });
669 - if (result._tag === "Failure") {
670 - Dialog.alert("Could not pin thread", String(Cause.squash(result.cause)));
671 - return false;
672 - }
673 - } else {
674 - if (lifecycle.unpin && !(await unpinThread(thread))) return false;
675 - if (lifecycle.unsettle && !(await unsettleThread(thread))) return false;
676 - if (lifecycle.unsnooze && !(await unsnoozeThread(thread))) return false;
677 - }
678 - }
679 - for (const assignment of assignments) {
680 - if (
681 - crossSection &&
682 - section === "pinned" &&
683 - thread.pinnedAt == null &&
684 - assignment.id === scopedThreadKey(thread.environmentId, thread.id)
685 - )
686 - continue;
687 - if (pending !== null && !pending.isPending()) return false;
688 - const target = shellByKey.get(assignment.id);
689 - if (target === undefined) continue;
690 - if (!checkThreadOperationPermission(target, "Could not move thread")) return false;
691 - const result = await reorder({
692 - environmentId: target.environmentId,
693 - input: { threadId: target.id, orderKey: assignment.orderKey },
567 + ),
568 + });
569 + const assignments = createThreadMovePlanner({
570 + allThreads: shells,
571 + ordered,
572 + section,
573 + reorderableEnvironmentIds: new Set([...configs.keys()].filter(supportsReorder)),
574 + })(scopedThreadKey(thread.environmentId, thread.id), direction);
575 + if (assignments === null) return false;
576 + const lifecycle = threadDropLifecycle(thread, section, new Date().toISOString());
577 + const crossSection = !ordered.some(
578 + (row) => row.id === thread.id && row.environmentId === thread.environmentId,
579 + );
580 + if (
581 + crossSection &&
582 + (((section === "pinned" || thread.pinnedAt != null) &&
583 + !environmentSupportsPinning(thread.environmentId)) ||
584 + (thread.settledOverride === "settled" &&
585 + !environmentSupportsSettlement(thread.environmentId)) ||
586 + (effectiveSnoozed(thread, { now: new Date().toISOString() }) &&
587 + !environmentSupportsSnooze(thread.environmentId)))
588 + )
589 + return false;
590 + const shellByKey = new Map(
591 + shells.map((shell) => [scopedThreadKey(shell.environmentId, shell.id), shell]),
592 + );
593 + for (const assignment of assignments) {
594 + const target = shellByKey.get(assignment.id);
595 + if (target && !checkThreadOperationPermission(target, "Could not move thread")) return false;
596 + }
597 + selectionHaptic();
598 + appAtomRegistry.set(threadDropBusyAtom, true);
599 + const pending = crossSection
600 + ? null
601 + : beginPendingThreadOrder(
602 + createPendingThreadOrder({
603 + section,
604 + ordered,
605 + movedId: scopedThreadKey(thread.environmentId, thread.id),
606 + direction,
607 + assignments,
608 + }),
609 + );
610 + const reorder = section === "pinned" ? reorderPinnedMutation : reorderActiveMutation;
611 + const moved = await (async () => {
612 + if (crossSection) {
613 + if (section === "pinned") {
614 + const orderKey = assignments.find(
615 + ({ id }) => id === scopedThreadKey(thread.environmentId, thread.id),
616 + )?.orderKey;
617 + const result = await pinMutation({
618 + environmentId: thread.environmentId,
619 + input: { threadId: thread.id, ...(orderKey === undefined ? {} : { orderKey }) },
620 });
621 if (result._tag === "Failure") {
696 - const error = Cause.squash(result.cause);
697 - Dialog.alert(
698 - "Could not move thread",
699 - error instanceof Error && error.message.trim().length > 0
700 - ? error.message
701 - : "The thread could not be moved.",
702 - );
622 + Dialog.alert("Could not pin thread", String(Cause.squash(result.cause)));
623 return false;
624 }
625 + } else {
626 + if (lifecycle.unpin && !(await unpinThread(thread))) return false;
627 + if (lifecycle.unsettle && !(await unsettleThread(thread))) return false;
628 + if (lifecycle.unsnooze && !(await unsnoozeThread(thread))) return false;
629 }
706 - succeeded = true;
707 - pending?.complete();
708 - return true;
709 - } finally {
710 - if (!succeeded) pending?.cancel();
711 - appAtomRegistry.set(threadDropBusyAtom, false);
630 }
713 - },
714 - [
715 - settleThread,
716 - reorderActiveMutation,
717 - reorderPinnedMutation,
718 - pinMutation,
719 - unpinThread,
720 - unsettleThread,
721 - unsnoozeThread,
722 - ],
723 - );
631 + for (const assignment of assignments) {
632 + if (
633 + crossSection &&
634 + section === "pinned" &&
635 + thread.pinnedAt == null &&
636 + assignment.id === scopedThreadKey(thread.environmentId, thread.id)
637 + )
638 + continue;
639 + if (pending !== null && !pending.isPending()) return false;
640 + const target = shellByKey.get(assignment.id);
641 + if (target === undefined) continue;
642 + if (!checkThreadOperationPermission(target, "Could not move thread")) return false;
643 + const result = await reorder({
644 + environmentId: target.environmentId,
645 + input: { threadId: target.id, orderKey: assignment.orderKey },
646 + });
647 + if (result._tag === "Failure") {
648 + const error = Cause.squash(result.cause);
649 + Dialog.alert(
650 + "Could not move thread",
651 + error instanceof Error && error.message.trim().length > 0
652 + ? error.message
653 + : "The thread could not be moved.",
654 + );
655 + return false;
656 + }
657 + }
658 + pending?.complete();
659 + return true;
660 + })();
661 + if (!moved) pending?.cancel();
662 + appAtomRegistry.set(threadDropBusyAtom, false);
663 + return moved;
664 + };
665
725 - const confirmDeleteThread = useConfirmDeleteThread(executeAction);
666 + const confirmDeleteThread = (thread: EnvironmentThreadShell) =>
667 + confirmThreadDeletion(executeAction, thread);
668
669 return {
670 archiveThread,
@@ -746,20 +688,15 @@ export function useArchivedThreadListActions(
688 readonly unarchiveThread: (thread: EnvironmentThreadShell) => void;
689 readonly confirmDeleteThread: (thread: EnvironmentThreadShell) => void;
690 } {
749 - const handleCompleted = useCallback(
750 - (_action: ThreadListAction, thread: EnvironmentThreadShell) => {
751 - onCompleted(thread);
752 - },
753 - [onCompleted],
754 - );
691 + const handleCompleted = (_action: ThreadListAction, thread: EnvironmentThreadShell) => {
692 + onCompleted(thread);
693 + };
694 const executeAction = useThreadActionExecutor(handleCompleted);
756 - const unarchiveThread = useCallback(
757 - (thread: EnvironmentThreadShell) => {
758 - void executeAction("unarchive", thread);
759 - },
760 - [executeAction],
761 - );
762 - const confirmDeleteThread = useConfirmDeleteThread(executeAction);
695 + const unarchiveThread = (thread: EnvironmentThreadShell) => {
696 + void executeAction("unarchive", thread);
697 + };
698 + const confirmDeleteThread = (thread: EnvironmentThreadShell) =>
699 + confirmThreadDeletion(executeAction, thread);
700
701 return { unarchiveThread, confirmDeleteThread };
702 }
apps/mobile/src/features/layout/AdaptiveWorkspaceLayout.tsx
+150 -227
@@ -15,9 +15,8 @@ import {
15 import {
16 createContext,
17 use,
18 - useCallback,
18 useEffect,
20 - useMemo,
19 + useEffectEvent,
20 useRef,
21 useState,
22 type ReactNode,
@@ -126,9 +125,7 @@ export function useAdaptiveWorkspaceLayout(): AdaptiveWorkspaceContextValue {
125 export function useAdaptiveWorkspacePaneRole(role: WorkspaceAuxiliaryPaneRole) {
126 const { activateAuxiliaryPaneRole } = useAdaptiveWorkspaceLayout();
127
129 - useFocusEffect(
130 - useCallback(() => activateAuxiliaryPaneRole(role), [activateAuxiliaryPaneRole, role]),
131 - );
128 + useFocusEffect(() => activateAuxiliaryPaneRole(role));
129 }
130
131 /**
@@ -146,7 +143,7 @@ export function useRegisterWorkspaceInspector(render: (() => ReactNode) | undefi
143 const navigation = use(NavigationContext);
144 const route = use(NavigationRouteContext);
145
149 - const wrappedRender = useMemo(() => {
146 + const wrappedRender = (() => {
147 if (render === undefined) {
148 return undefined;
149 }
@@ -155,37 +152,35 @@ export function useRegisterWorkspaceInspector(render: (() => ReactNode) | undefi
152 <NavigationRouteContext.Provider value={route}>{render()}</NavigationRouteContext.Provider>
153 </NavigationContext.Provider>
154 );
158 - }, [navigation, render, route]);
155 + })();
156
160 - const wrappedRenderRef = useRef(wrappedRender);
161 - wrappedRenderRef.current = wrappedRender;
157 const focusedRef = useRef(false);
158 const deactivateRef = useRef<(() => void) | null>(null);
159
165 - const syncRegistration = useCallback(() => {
166 - if (!focusedRef.current || wrappedRenderRef.current === undefined) {
160 + // An effect event reads this render's pane without making the focus
161 + // subscription re-run (and deactivate) every time the pane closure changes.
162 + const syncRegistration = useEffectEvent(() => {
163 + if (!focusedRef.current || wrappedRender === undefined) {
164 deactivateRef.current?.();
165 return;
166 }
170 - deactivateRef.current = registerWorkspaceInspector(wrappedRenderRef.current);
171 - }, [registerWorkspaceInspector]);
167 + deactivateRef.current = registerWorkspaceInspector(wrappedRender);
168 + });
169
173 - useFocusEffect(
174 - useCallback(() => {
175 - focusedRef.current = true;
170 + useFocusEffect(() => {
171 + focusedRef.current = true;
172 + syncRegistration();
173 + return () => {
174 + focusedRef.current = false;
175 syncRegistration();
177 - return () => {
178 - focusedRef.current = false;
179 - syncRegistration();
180 - };
181 - }, [syncRegistration]),
182 - );
176 + };
177 + });
178
179 useEffect(() => {
180 if (focusedRef.current) {
181 syncRegistration();
182 }
188 - }, [syncRegistration, wrappedRender]);
183 + }, [wrappedRender]);
184
185 useEffect(
186 () => () => {
@@ -252,10 +247,7 @@ function AdaptiveWorkspaceLayoutContent(
247 const [primarySidebarSearchQuery, setPrimarySidebarSearchQuery] = useState("");
248 const [focusedAuxiliaryPaneRole, setFocusedAuxiliaryPaneRole] =
249 useState<WorkspaceAuxiliaryPaneRole | null>(null);
255 - const baseLayout = useMemo(
256 - () => deriveLayout({ width: viewportWidth, height, nativeMetrics }),
257 - [height, viewportWidth, nativeMetrics],
258 - );
250 + const baseLayout = deriveLayout({ width: viewportWidth, height, nativeMetrics });
251 const primarySidebarPinned = isPrimarySidebarPinned({
252 pathname,
253 nativeWorkspace,
@@ -264,37 +256,21 @@ function AdaptiveWorkspaceLayoutContent(
256 const showPrimarySidebar = primarySidebarPinned || primarySidebarPreferredVisible;
257 const [hinge, setHinge] = useState<VerticalHinge | null>(null);
258 const [windowHinge, setWindowHinge] = useState<VerticalHinge | null>(null);
267 - const handleHingeChange = useCallback(
268 - (next: VerticalHinge | null, nextWindow: VerticalHinge | null) => {
269 - setHinge(next);
270 - setWindowHinge(nextWindow);
271 - },
272 - [],
273 - );
274 - const layout = useMemo(
275 - () => alignListPaneToHinge({ layout: baseLayout, hinge, viewportWidth }),
276 - [baseLayout, hinge, viewportWidth],
277 - );
259 + const handleHingeChange = (next: VerticalHinge | null, nextWindow: VerticalHinge | null) => {
260 + setHinge(next);
261 + setWindowHinge(nextWindow);
262 + };
263 + const layout = alignListPaneToHinge({ layout: baseLayout, hinge, viewportWidth });
264 const shouldRenderPrimarySidebar = layout.usesSplitView;
279 - const fileInspector = useMemo(
280 - () =>
281 - deriveFileInspectorPaneLayout({
282 - layout,
283 - viewportWidth,
284 - preferredWidth: fileInspectorPreferredWidth ?? undefined,
285 - reservedLeadingWidth:
286 - shouldRenderPrimarySidebar && showPrimarySidebar
287 - ? (layout.listPaneWidth ?? 0) + (layout.listPaneGap ?? 0)
288 - : 0,
289 - }),
290 - [
291 - fileInspectorPreferredWidth,
292 - layout,
293 - showPrimarySidebar,
294 - shouldRenderPrimarySidebar,
295 - viewportWidth,
296 - ],
297 - );
265 + const fileInspector = deriveFileInspectorPaneLayout({
266 + layout,
267 + viewportWidth,
268 + preferredWidth: fileInspectorPreferredWidth ?? undefined,
269 + reservedLeadingWidth:
270 + shouldRenderPrimarySidebar && showPrimarySidebar
271 + ? (layout.listPaneWidth ?? 0) + (layout.listPaneGap ?? 0)
272 + : 0,
273 + });
274 const auxiliaryPaneRole: WorkspaceAuxiliaryPaneRole =
275 focusedAuxiliaryPaneRole ?? (/\/files(?:\/|$)/.test(pathname) ? "inspector" : "supplementary");
276 const auxiliaryPanePreferredVisible =
@@ -305,29 +281,18 @@ function AdaptiveWorkspaceLayoutContent(
281 auxiliaryPaneRole === "inspector"
282 ? fileInspectorPreferredWidth
283 : supplementaryPanePreferredWidth;
308 - const panes = useMemo(
309 - () =>
310 - deriveWorkspacePaneLayout({
311 - layout,
312 - viewportWidth,
313 - primarySidebarPreferredVisible: showPrimarySidebar,
314 - auxiliaryPanePreferredVisible,
315 - auxiliaryPaneRole,
316 - auxiliaryPanePreferredWidth: auxiliaryPanePreferredWidth ?? undefined,
317 - }),
318 - [
319 - auxiliaryPanePreferredVisible,
320 - auxiliaryPaneRole,
321 - auxiliaryPanePreferredWidth,
322 - layout,
323 - showPrimarySidebar,
324 - viewportWidth,
325 - ],
326 - );
284 + const panes = deriveWorkspacePaneLayout({
285 + layout,
286 + viewportWidth,
287 + primarySidebarPreferredVisible: showPrimarySidebar,
288 + auxiliaryPanePreferredVisible,
289 + auxiliaryPaneRole,
290 + auxiliaryPanePreferredWidth: auxiliaryPanePreferredWidth ?? undefined,
291 + });
292 const activeThread = parseActiveThreadPath(pathname);
293 const environmentId = activeThread?.environmentId ?? null;
294 const threadId = activeThread?.threadId ?? null;
330 - const selectedThreadKey = useMemo(() => {
295 + const selectedThreadKey = (() => {
296 if (environmentId === null || threadId === null) {
297 return null;
298 }
@@ -336,13 +301,13 @@ function AdaptiveWorkspaceLayoutContent(
301 } catch {
302 return null;
303 }
339 - }, [environmentId, threadId]);
304 + })();
305 const [workspaceInspector, setWorkspaceInspector] = useState<{
306 readonly render: () => ReactNode;
307 readonly active: boolean;
308 } | null>(null);
309 const workspaceInspectorOwner = useRef<symbol | null>(null);
345 - const registerWorkspaceInspector = useCallback((render: () => ReactNode) => {
310 + const registerWorkspaceInspector = (render: () => ReactNode) => {
311 const owner = Symbol("workspace-inspector");
312 workspaceInspectorOwner.current = owner;
313 setWorkspaceInspector({ render, active: true });
@@ -355,11 +320,11 @@ function AdaptiveWorkspaceLayoutContent(
320 }
321 setWorkspaceInspector((current) => (current === null ? null : { ...current, active: false }));
322 };
358 - }, []);
359 - const handleWorkspaceInspectorClosed = useCallback(() => {
323 + };
324 + const handleWorkspaceInspectorClosed = () => {
325 setWorkspaceInspector((current) => (current !== null && !current.active ? null : current));
361 - }, []);
362 - const activateAuxiliaryPaneRole = useCallback((role: WorkspaceAuxiliaryPaneRole) => {
326 + };
327 + const activateAuxiliaryPaneRole = (role: WorkspaceAuxiliaryPaneRole) => {
328 const owner = Symbol(role);
329 activeRoleOwner.current = owner;
330 setFocusedAuxiliaryPaneRole(role);
@@ -371,8 +336,8 @@ function AdaptiveWorkspaceLayoutContent(
336 activeRoleOwner.current = null;
337 setFocusedAuxiliaryPaneRole(null);
338 };
374 - }, []);
375 - const togglePrimarySidebar = useCallback(() => {
339 + };
340 + const togglePrimarySidebar = () => {
341 if (primarySidebarPinned) {
342 return;
343 }
@@ -382,27 +347,20 @@ function AdaptiveWorkspaceLayoutContent(
347 return;
348 }
349 setPrimarySidebarPreferredVisible((current) => !current);
385 - }, [
386 - panes.primarySidebarSuppressedByAuxiliary,
387 - panes.primarySidebarVisible,
388 - primarySidebarPinned,
389 - ]);
390 - const revealPrimarySidebar = useCallback(() => {
350 + };
351 + const revealPrimarySidebar = () => {
352 if (panes.primarySidebarSuppressedByAuxiliary) {
353 setFileInspectorPreferredVisible(false);
354 }
355 setPrimarySidebarPreferredVisible(true);
395 - }, [panes.primarySidebarSuppressedByAuxiliary]);
396 - const handleToggleSidebarCommand = useCallback(() => {
356 + };
357 + const handleToggleSidebarCommand = () => {
358 togglePrimarySidebar();
359 return true;
399 - }, [togglePrimarySidebar]);
400 - const sidebarCommands = useMemo(
401 - () => (primarySidebarPinned ? [] : (["toggleSidebar"] as const)),
402 - [primarySidebarPinned],
403 - );
360 + };
361 + const sidebarCommands = primarySidebarPinned ? [] : (["toggleSidebar"] as const);
362 useHardwareKeyboardCommand(sidebarCommands, handleToggleSidebarCommand);
405 - const showAuxiliaryPane = useCallback((role: WorkspaceAuxiliaryPaneRole) => {
363 + const showAuxiliaryPane = (role: WorkspaceAuxiliaryPaneRole) => {
364 if (role === "inspector") {
365 setFocusedAuxiliaryPaneRole("inspector");
366 setFileInspectorPreferredVisible(true);
@@ -410,8 +368,8 @@ function AdaptiveWorkspaceLayoutContent(
368 }
369 setFocusedAuxiliaryPaneRole("supplementary");
370 setSupplementaryPanePreferredVisible(true);
413 - }, []);
414 - const handleOpenFilesCommand = useCallback(() => {
371 + };
372 + const handleOpenFilesCommand = () => {
373 const activeThread = parseActiveThreadPath(pathname);
374 if (!layout.usesSplitView || !fileInspector.supported || activeThread === null) {
375 return false;
@@ -422,75 +380,66 @@ function AdaptiveWorkspaceLayoutContent(
380 }
381 navigation.navigate("ThreadFiles", activeThread);
382 return true;
425 - }, [fileInspector.supported, layout.usesSplitView, pathname, navigation, showAuxiliaryPane]);
383 + };
384 useHardwareKeyboardCommand("files", handleOpenFilesCommand);
427 - const toggleAuxiliaryPane = useCallback(() => {
385 + const toggleAuxiliaryPane = () => {
386 if (auxiliaryPaneRole === "inspector") {
387 setFileInspectorPreferredVisible((current) => !current);
388 return;
389 }
390 setSupplementaryPanePreferredVisible((current) => !current);
433 - }, [auxiliaryPaneRole]);
434 - const setAuxiliaryPaneWidth = useCallback(
435 - (nextWidth: number) => {
436 - if (auxiliaryPaneRole === "inspector") {
437 - setFileInspectorPreferredWidth(nextWidth);
438 - return;
439 - }
440 - setSupplementaryPanePreferredWidth(nextWidth);
441 - },
442 - [auxiliaryPaneRole],
443 - );
444 - const handleOpenSettings = useCallback(() => {
391 + };
392 + const setAuxiliaryPaneWidth = (nextWidth: number) => {
393 + if (auxiliaryPaneRole === "inspector") {
394 + setFileInspectorPreferredWidth(nextWidth);
395 + return;
396 + }
397 + setSupplementaryPanePreferredWidth(nextWidth);
398 + };
399 + const handleOpenSettings = () => {
400 navigation.navigate("SettingsSheet", {
401 screen: "SettingsContent",
402 params: { screen: "Settings" },
403 });
449 - }, [navigation]);
404 + };
405
451 - const handleStartNewTask = useCallback(() => {
406 + const handleStartNewTask = () => {
407 navigation.navigate("NewTaskSheet", { screen: "NewTask" });
453 - }, [navigation]);
408 + };
409
410 // Minted here (root stack navigation) so the sidebar pane stays free of
411 // navigation hooks — on iOS it renders inside an independent nav tree.
457 - const handleOpenEnvironmentSettings = useCallback(() => {
412 + const handleOpenEnvironmentSettings = () => {
413 navigation.navigate("SettingsSheet", {
414 screen: "SettingsContent",
415 params: { screen: "SettingsEnvironments" },
416 });
462 - }, [navigation]);
417 + };
418
419 const handleOpenThreadPullRequests = useOpenThreadPullRequests();
420
466 - const handleNewThreadOnBranch = useCallback(
467 - (thread: EnvironmentThreadShell) => {
468 - navigation.navigate("NewTaskSheet", {
469 - screen: "NewTaskDraft",
470 - params: {
471 - environmentId: String(thread.environmentId),
472 - projectId: String(thread.projectId),
473 - branch: thread.branch,
474 - worktreePath: thread.worktreePath,
475 - },
476 - });
477 - },
478 - [navigation],
479 - );
421 + const handleNewThreadOnBranch = (thread: EnvironmentThreadShell) => {
422 + navigation.navigate("NewTaskSheet", {
423 + screen: "NewTaskDraft",
424 + params: {
425 + environmentId: String(thread.environmentId),
426 + projectId: String(thread.projectId),
427 + branch: thread.branch,
428 + worktreePath: thread.worktreePath,
429 + },
430 + });
431 + };
432
481 - const handleNewThreadInProject = useCallback(
482 - (project: EnvironmentProject) => {
483 - navigation.navigate("NewTaskSheet", {
484 - screen: "NewTaskDraft",
485 - params: {
486 - environmentId: String(project.environmentId),
487 - projectId: String(project.id),
488 - title: project.title,
489 - },
490 - });
491 - },
492 - [navigation],
493 - );
433 + const handleNewThreadInProject = (project: EnvironmentProject) => {
434 + navigation.navigate("NewTaskSheet", {
435 + screen: "NewTaskDraft",
436 + params: {
437 + environmentId: String(project.environmentId),
438 + projectId: String(project.id),
439 + title: project.title,
440 + },
441 + });
442 + };
443
444 const inspectorColumnTargetWidth =
445 workspaceInspector !== null && workspaceInspector.active && panes.auxiliaryPaneVisible
@@ -550,7 +499,7 @@ function AdaptiveWorkspaceLayoutContent(
499 revision: contentSizing.revision + 1,
500 });
501 }
553 - const settleContentWidth = useCallback((revision: number) => {
502 + const settleContentWidth = (revision: number) => {
503 setContentSizing((current) =>
504 current.revision !== revision ||
505 (current.width === current.target &&
@@ -564,7 +513,7 @@ function AdaptiveWorkspaceLayoutContent(
513 listPaneCeiling: current.listPaneTarget,
514 },
515 );
567 - }, []);
516 + };
517 const listPaneFloor = contentSizing.listPaneFloor ?? 0;
518 const listPaneCeiling = contentSizing.listPaneCeiling ?? 0;
519 const contentSettledWidth = Platform.OS === "android" ? contentSizing.width : contentTargetWidth;
@@ -614,88 +563,62 @@ function AdaptiveWorkspaceLayoutContent(
563 );
564
565 const selectAndroidWorkspace = useAndroidWorkspaceSelection();
617 - const handleSelectThread = useCallback(
618 - (thread: EnvironmentThreadShell) => {
619 - const params = {
620 - environmentId: String(thread.environmentId),
621 - threadId: String(thread.id),
622 - };
623 - if (Platform.OS === "android") {
624 - setFileInspectorPreferredVisible(false);
625 - selectAndroidWorkspace({ name: "Thread", params });
626 - return;
627 - }
628 - const navigationAction = resolveThreadSelectionNavigationAction({
629 - usesSplitView: layout.usesSplitView,
630 - pathname,
631 - });
632 - const overlayState = resolveThreadSelectionOverlayState({
633 - state: navigation.getState(),
634 - workspaceRouteKey: props.workspaceRouteKey,
635 - action: navigationAction,
636 - params,
637 - });
638 - if (overlayState !== null) {
639 - setFileInspectorPreferredVisible(false);
640 - navigation.dispatch(CommonActions.reset(overlayState));
641 - return;
642 - }
643 - if (navigationAction === "set-params") {
644 - const nextThreadKey = scopedThreadKey(thread.environmentId, thread.id);
645 - if (nextThreadKey === selectedThreadKey) {
646 - return;
647 - }
648 - setFileInspectorPreferredVisible(false);
649 - navigation.navigate("Thread", params);
650 - return;
651 - }
652 - if (navigationAction === "replace") {
653 - setFileInspectorPreferredVisible(false);
654 - navigation.dispatch(StackActions.replace("Thread", params));
566 + const handleSelectThread = (thread: EnvironmentThreadShell) => {
567 + const params = {
568 + environmentId: String(thread.environmentId),
569 + threadId: String(thread.id),
570 + };
571 + if (Platform.OS === "android") {
572 + setFileInspectorPreferredVisible(false);
573 + selectAndroidWorkspace({ name: "Thread", params });
574 + return;
575 + }
576 + const navigationAction = resolveThreadSelectionNavigationAction({
577 + usesSplitView: layout.usesSplitView,
578 + pathname,
579 + });
580 + const overlayState = resolveThreadSelectionOverlayState({
581 + state: navigation.getState(),
582 + workspaceRouteKey: props.workspaceRouteKey,
583 + action: navigationAction,
584 + params,
585 + });
586 + if (overlayState !== null) {
587 + setFileInspectorPreferredVisible(false);
588 + navigation.dispatch(CommonActions.reset(overlayState));
589 + return;
590 + }
591 + if (navigationAction === "set-params") {
592 + const nextThreadKey = scopedThreadKey(thread.environmentId, thread.id);
593 + if (nextThreadKey === selectedThreadKey) {
594 return;
595 }
596 + setFileInspectorPreferredVisible(false);
597 navigation.navigate("Thread", params);
658 - },
659 - [
660 - layout.usesSplitView,
661 - pathname,
662 - navigation,
663 - selectedThreadKey,
664 - props.workspaceRouteKey,
665 - selectAndroidWorkspace,
666 - ],
667 - );
598 + return;
599 + }
600 + if (navigationAction === "replace") {
601 + setFileInspectorPreferredVisible(false);
602 + navigation.dispatch(StackActions.replace("Thread", params));
603 + return;
604 + }
605 + navigation.navigate("Thread", params);
606 + };
607
669 - const contextValue = useMemo(
670 - () => ({
671 - layout,
672 - panes,
673 - fileInspector,
674 - primarySidebarSearchQuery,
675 - selectThread: handleSelectThread,
676 - activateAuxiliaryPaneRole,
677 - registerWorkspaceInspector,
678 - setPrimarySidebarSearchQuery,
679 - showAuxiliaryPane,
680 - toggleAuxiliaryPane,
681 - togglePrimarySidebar,
682 - setAuxiliaryPaneWidth,
683 - }),
684 - [
685 - activateAuxiliaryPaneRole,
686 - fileInspector,
687 - handleSelectThread,
688 - layout,
689 - panes,
690 - primarySidebarSearchQuery,
691 - registerWorkspaceInspector,
692 - showAuxiliaryPane,
693 - setPrimarySidebarSearchQuery,
694 - setAuxiliaryPaneWidth,
695 - toggleAuxiliaryPane,
696 - togglePrimarySidebar,
697 - ],
698 - );
608 + const contextValue = {
609 + layout,
610 + panes,
611 + fileInspector,
612 + primarySidebarSearchQuery,
613 + selectThread: handleSelectThread,
614 + activateAuxiliaryPaneRole,
615 + registerWorkspaceInspector,
616 + setPrimarySidebarSearchQuery,
617 + showAuxiliaryPane,
618 + toggleAuxiliaryPane,
619 + togglePrimarySidebar,
620 + setAuxiliaryPaneWidth,
621 + };
622
623 if (nativeWorkspace) {
624 return (
apps/mobile/src/features/layout/workspace-inspector-pane.tsx
+16 -19
@@ -1,4 +1,4 @@
1 -import { useCallback, useEffect, useRef, useState, type ReactNode } from "react";
1 +import { useEffect, useRef, useState, type ReactNode } from "react";
2 import Animated, {
3 runOnJS,
4 useAnimatedStyle,
@@ -49,9 +49,9 @@ export function WorkspaceInspectorPane(props: {
49 },
50 );
51 const targetWidth = inspectorVisible ? (inspectorWidth ?? 0) : 0;
52 - renderedInspectorWidth.value = resizing
53 - ? targetWidth
54 - : withTiming(targetWidth, WORKSPACE_PANE_TIMING);
52 + renderedInspectorWidth.set(
53 + resizing ? targetWidth : withTiming(targetWidth, WORKSPACE_PANE_TIMING),
54 + );
55 }, [
56 inspectorProgress,
57 inspectorVisible,
@@ -79,24 +79,21 @@ export function WorkspaceInspectorPane(props: {
79 [],
80 );
81 const inspectorContentStyle = useAnimatedStyle(() => ({ width: renderedContentWidth.value }), []);
82 - const beginResize = useCallback(() => {
82 + const beginResize = () => {
83 resizeStartWidth.current = inspectorWidth ?? 0;
84 setResizing(true);
85 - }, [inspectorWidth]);
86 - const resizeBy = useCallback(
87 - (delta: number) => {
88 - setAuxiliaryPaneWidth(
89 - constrainAuxiliaryPaneWidth({
90 - preferredWidth: resizeStartWidth.current + delta,
91 - availableWidth: panes.contentPaneWidth,
92 - }),
93 - );
94 - },
95 - [panes.contentPaneWidth, setAuxiliaryPaneWidth],
96 - );
97 - const endResize = useCallback(() => {
85 + };
86 + const resizeBy = (delta: number) => {
87 + setAuxiliaryPaneWidth(
88 + constrainAuxiliaryPaneWidth({
89 + preferredWidth: resizeStartWidth.current + delta,
90 + availableWidth: panes.contentPaneWidth,
91 + }),
92 + );
93 + };
94 + const endResize = () => {
95 setResizing(false);
99 - }, []);
96 + };
97
98 return (
99 <>
apps/mobile/src/features/layout/workspace-pane-divider.tsx
+25 -27
@@ -1,4 +1,4 @@
1 -import { useCallback, useMemo, useRef, useState } from "react";
1 +import { useEffectEvent, useState } from "react";
2 import { Platform, Pressable, StyleSheet, View, type AccessibilityActionEvent } from "react-native";
3 import { Gesture, GestureDetector } from "react-native-gesture-handler";
4 import { runOnJS } from "react-native-reanimated";
@@ -16,35 +16,33 @@ interface WorkspacePaneDividerProps {
16 }
17
18 export function WorkspacePaneDivider(props: WorkspacePaneDividerProps) {
19 - const latestProps = useRef(props);
20 - latestProps.current = props;
19 const [dragging, setDragging] = useState(false);
22 - const handleResizeStart = useCallback(() => {
20 + // The pan callbacks fire after render, so effect events read the latest props
21 + // while the gesture object stays stable across renders.
22 + const handleResizeStart = useEffectEvent(() => {
23 setDragging(true);
24 - latestProps.current.onResizeStart?.();
25 - }, []);
26 - const handleResize = useCallback((translationX: number) => {
27 - latestProps.current.onResizeBy(translationX * latestProps.current.resizeDirection);
28 - }, []);
29 - const handleResizeEnd = useCallback(() => {
24 + props.onResizeStart?.();
25 + });
26 + const handleResize = useEffectEvent((translationX: number) => {
27 + props.onResizeBy(translationX * props.resizeDirection);
28 + });
29 + const handleResizeEnd = useEffectEvent(() => {
30 setDragging(false);
31 - latestProps.current.onResizeEnd?.();
32 - }, []);
33 - const resizeGesture = useMemo(
34 - () =>
35 - Gesture.Pan()
36 - .activeOffsetX([-4, 4])
37 - .failOffsetY([-24, 24])
38 - .onStart(() => {
39 - runOnJS(handleResizeStart)();
40 - })
41 - .onUpdate((event) => {
42 - runOnJS(handleResize)(event.translationX);
43 - })
44 - .onFinalize(() => {
45 - runOnJS(handleResizeEnd)();
46 - }),
47 - [handleResize, handleResizeEnd, handleResizeStart],
31 + props.onResizeEnd?.();
32 + });
33 + const [resizeGesture] = useState(() =>
34 + Gesture.Pan()
35 + .activeOffsetX([-4, 4])
36 + .failOffsetY([-24, 24])
37 + .onStart(() => {
38 + runOnJS(handleResizeStart)();
39 + })
40 + .onUpdate((event) => {
41 + runOnJS(handleResize)(event.translationX);
42 + })
43 + .onFinalize(() => {
44 + runOnJS(handleResizeEnd)();
45 + }),
46 );
47
48 const handleAccessibilityAction = (event: AccessibilityActionEvent) => {
apps/mobile/src/reactCompilerCoverage.test.ts
-8
@@ -24,17 +24,9 @@ const KNOWN_BAILOUTS: Record<string, string> = {
24 "src/components/VideoPreviewModal.tsx": "ref read during render",
25 "src/components/ui/AndroidAnchoredMenu.tsx": "ref read during render",
26 "src/components/ui/Menu.tsx": "ref read during render",
27 - "src/components/ui/OverlayPortal.tsx": "unsupported syntax",
27 "src/features/connection/ConnectionsNewRouteScreen.tsx": "try without catch",
28 "src/features/diffs/nativeReviewDiffSurface.ts": "ref read during render",
30 - "src/features/home/HomeScreen.tsx": "ref read during render",
31 - "src/features/home/WorkspaceConnectionTitle.tsx": "ref read during render",
32 - "src/features/home/home-list-options.ts": "manual memo not preserved",
29 "src/features/home/thread-swipe-actions.tsx": "ref read during render",
34 - "src/features/home/useThreadListActions.ts": "try without catch",
35 - "src/features/layout/AdaptiveWorkspaceLayout.tsx": "ref read during render",
36 - "src/features/layout/workspace-inspector-pane.tsx": "mutates a frozen value",
37 - "src/features/layout/workspace-pane-divider.tsx": "ref read during render",
30 "src/features/projects/AddProjectScreen.tsx": "try without catch",
31 "src/features/pull-requests/PullRequestDiscussionScreen.tsx": "try/finally",
32 "src/features/pull-requests/PullRequestInlineCommentScreen.tsx": "try without catch",