From 8149b327a4772e0ef45cf785f5aba5a3dfedf9c4 Mon Sep 17 00:00:00 2001 From: Jackson Miller Date: Wed, 11 Nov 2026 17:08:55 -0500 Subject: [PATCH 1/3] feat(mobile): a Captain's Crew and spawned agents move into the thread's Agents sheet Co-Authored-By: Claude Opus 5.5 --- FORK.md | 8 +- .../features/threads/ThreadAgentsSheet.tsx | 10 +- .../features/threads/ThreadDetailScreen.tsx | 8 +- .../features/threads/thread-list-v2-items.tsx | 33 +- apps/mobile/src/j5/crew/CaptainSeats.tsx | 313 ------------------ apps/mobile/src/j5/crew/J5ThreadAgents.tsx | 267 +++++++++++++++ apps/mobile/src/j5/crew/spawnedChildren.ts | 27 +- apps/mobile/src/j5/upstreamSeams.test.ts | 14 +- .../client-runtime/src/j5/crewState.test.ts | 35 ++ packages/client-runtime/src/j5/crewState.ts | 35 ++ .../src/j5/spawnedChildren.test.ts | 27 +- .../client-runtime/src/j5/spawnedChildren.ts | 31 +- 12 files changed, 429 insertions(+), 379 deletions(-) delete mode 100644 apps/mobile/src/j5/crew/CaptainSeats.tsx create mode 100644 apps/mobile/src/j5/crew/J5ThreadAgents.tsx diff --git a/FORK.md b/FORK.md index f7e36dc0d66f4..9e74becee0599 100644 --- a/FORK.md +++ b/FORK.md @@ -49,7 +49,7 @@ Mobile follows the same add-beside rule with a fixed seam set, decided on 2026-0 | ------------------- | ------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------ | ----------------------------------------------------------------------------------------------------------------------------------------------- | | Timeline delegate | `features/threads/ThreadFeed.tsx` message rows | The A2A timeline's groups from the shared classifier, `packages/client-runtime/src/j5/userMessagePresentation.ts` (web case 7) | Landed: case 97. | | Queue-row formatter | `features/threads/ThreadQueueControl.tsx` | The sender line and the letter's first line for queued deliveries (web case 24) | Landed: case 97. | -| Thread-row identity | `features/threads/thread-list-v2-items.tsx` | Crew membership (web case 23) | Landed for spawned agents (case 115). The row also mounts the persona's `AgentIdentityChip`, at upstream's title inset. | +| Thread-row identity | `features/threads/thread-list-v2-items.tsx` | Crew membership (web case 23) | Not landed. The row mounts only the persona's `AgentIdentityChip`, at upstream's title inset. | | Route registration | `Stack.tsx` and the settings row targets | J5 screens such as Inbox, Fleet and Artifacts | Landed for Artifacts (case 98) and the Inbox (case 101): `Stack.tsx` spreads `j5ThreadArtifactRoutes` and `j5InboxRoutes`. Fleet is not landed. | | Link resolver | the thread feed's markdown link press (`features/threads/ThreadFeed.tsx`) | `artifacts/…` links open the artifact instead of a workspace file | Landed (case 98). | @@ -550,7 +550,7 @@ migrations after upstream migrations. 114. Mobile roster review for a Captain's Crew proposal ([#836](https://github.com/Jacksondr5/j5code/issues/836), Jackson's decisions 1 and 2 of 2026-11-07/08: a phone approves, declines and removes seats, showing each seat's access; other edits stay on web). `apps/mobile/src/features/threads/ThreadDetailScreen.tsx` mounts J5-owned `J5ComposerControls` (`apps/mobile/src/j5/composer/`) beside case 49's `PlaybookComposerControl`, under the same conditions; every J5 row above the composer joins there, not as another seam. Its first row, `CrewRosterStrip` (`apps/mobile/src/j5/crew/`), shows one row per open, human-approved proposal for the thread and opens the `ThreadCrewProposal` screen, which case 98's `j5ThreadRoutes` spread registers. The gate filter, seat lines, playbook notes and preview binding live in `packages/client-runtime/src/j5/crewProposals.ts` (a new `./j5/crew-proposals` export in `packages/client-runtime/package.json`), shared with web's card; approval sends only the token from a complete preview of the seats on screen. Its second row, `AdjudicationDock` (`apps/mobile/src/j5/a2a/`), pins a Captain's open asks to the person, as web's dock does (#836 piece 6): the Inbox's own asks from this thread, answered through the Inbox's `useInboxAnswers`, shown only when `useCrewMembership` (`apps/mobile/src/j5/crew/crewMemberships.ts`, over case 115's `threadReadConnectionsAtom`, re-read whenever the server's Crew revision moves) says the thread commands a Crew. It has no attachments and no owner's clear action, since the mobile Inbox has neither. The dock's logic is `packages/client-runtime/src/j5/adjudicationDock.ts` and the membership replace is `crewMemberships.ts`, both shared with web and reached through the `./j5/adjudication-dock` and `./j5/crew-memberships` exports this case appends to upstream-owned `packages/client-runtime/package.json`. -115. Mobile lists a spawner's agents under its row (register D22, the mobile half of case 23; [#836](https://github.com/Jacksondr5/j5code/issues/836) decisions 3 and 4). `apps/mobile/src/features/threads/useThreadListV2.ts` passes its threads through J5-owned `useCrewListedThreads` (`apps/mobile/src/j5/crew/spawnedChildren.ts`), which keeps the spawned-children read (`j5.fleet.listSpawnedChildren`) current for every listed thread and drops the threads an agent spawned unless they are pinned, so every list, shelf and reorder computed after it sees the same rows. Mobile has no Fleet roster to bound re-reads by, so a moved `crew` or `fleet` revision re-reads that server's listed rows in one batched read. `apps/mobile/src/features/threads/thread-list-v2-items.tsx` mounts J5-owned `CaptainSeatsToggle` (`apps/mobile/src/j5/crew/CaptainSeats.tsx`) inside the card row's bottom line, before the pull request badge, and inside the slim row before its time, so a collapsed spawner is no taller; and it mounts `CaptainSeats` after the row's swipeable, outside its long-press menu, handing it upstream's own `STATUS_LABEL_BY_STATUS` so seat rows read as rows do. The expanded seats show each Crew's summary, Stop crew while a seat is running, "Not started", and "Replaced by". The grouping, the membership rule and the Crew state labels moved from web to `packages/client-runtime/src/j5/spawnedChildren.ts` and `crewState.ts`, reached through the `./j5/spawned-children` and `./j5/crew-state` exports this case adds to `packages/client-runtime/package.json`. Its test mocks the hook as a passthrough, since the hook reads server connections. On a pin advance: keep the one wrap at the top of `useThreadListV2`, the toggle inside both row layouts, and the seats outside the swipeable. +115. Mobile shows a spawner's agents in its Agents sheet (register D22, the mobile half of case 23; [#836](https://github.com/Jacksondr5/j5code/issues/836) decisions 3 and 4, and [#1009](https://github.com/Jacksondr5/j5code/issues/1009), Jackson's call at Checkpoint 4 that replaced the Chats-row count). `apps/mobile/src/features/threads/useThreadListV2.ts` passes its threads through J5-owned `useCrewListedThreads` (`apps/mobile/src/j5/crew/spawnedChildren.ts`), which keeps the spawned-children read (`j5.fleet.listSpawnedChildren`) current for every listed thread and drops the threads an agent spawned unless they are pinned, so every list, shelf and reorder computed after it sees the same rows; its test mocks the hook as a passthrough, since the hook reads server connections. Mobile has no Fleet roster to bound re-reads by, so a moved `crew` or `fleet` revision re-reads that server's listed rows in one batched read. Upstream's in-thread Agents pill and sheet carry the rest. `apps/mobile/src/features/threads/ThreadDetailScreen.tsx` passes upstream's own `resolveSubagentPillSegment` result through J5-owned `useJ5AgentsPillSegment` (`apps/mobile/src/j5/crew/J5ThreadAgents.tsx`), which adds the thread's spawned agents to the pill's counts and keeps the pill while a Crew idles between turns; and `apps/mobile/src/features/threads/ThreadAgentsSheet.tsx` mounts `J5ThreadAgents` above upstream's subagent rows, opening a member through upstream's own `openChildThread`, and shows upstream's empty text only when neither list has a row (`useHasJ5Agents`). The J5 rows show each Crew's summary, Stop crew while a seat is running, "Not started" and "Replaced by", in the tones of upstream's agent rows. The grouping, the membership rule, the pill counts and the Crew state labels live in `packages/client-runtime/src/j5/spawnedChildren.ts` and `crewState.ts`, reached through the `./j5/spawned-children` and `./j5/crew-state` exports this case adds to `packages/client-runtime/package.json`. On a pin advance: keep the one wrap at the top of `useThreadListV2`, the segment wrap in `ThreadDetailScreen`, and the sheet's mount and empty-text condition. 116. The Lineage section shows J5's command relations ([#283](https://github.com/Jacksondr5/j5code/issues/283), Jackson's decision of 2026-09-24). Upstream's Lineage (`apps/web/src/components/chat/ThreadRelationshipsControl.tsx`) draws upstream's lineage only, so a Peer Agent or Crew seat looks like an unrelated root thread there. The file exports `ThreadLineageRowList` and `LineageTooltipContent` (one word each), calls J5-owned `useJ5LineageRows` once before its early return, adds `j5Lineage.length > 0` to `lineageVisible` and to the section's `showHeading`, and renders `` after the delegated-from list. The rows live in `apps/web/src/j5/threads/J5LineageRows.tsx` and read the live Fleet roster: the thread's placement parent and Crew Captain, and the agents placed under it or seated in its Crews. They reuse upstream's row control, icon, tooltip and list, and they leave upstream's lineage and `relationshipToParent` alone. Upstream's `ThreadRelationshipsControl.browser.test.tsx` mocks them. Proof: `apps/web/src/j5/threads/j5Lineage.logic.test.ts`. On a pin advance, keep the clause in both visibility lists and the render beside upstream's own extra row lists. If upstream exports a shared row component, render J5's rows with it. @@ -768,7 +768,7 @@ explicitly marked. | `apps/mobile/metro.config.js` | A | 113 | | `apps/mobile/package.json` | A | B, 45 | | `apps/mobile/src/features/threads/NewTaskDraftScreen.tsx` | A | 45, 90, 100, Saved-agent mentions | -| `apps/mobile/src/features/threads/ThreadDetailScreen.tsx` | A | 45, 49, 114 | +| `apps/mobile/src/features/threads/ThreadDetailScreen.tsx` | A | 45, 49, 114, 115 | | `apps/mobile/src/features/threads/ThreadRouteScreen.tsx` | A | 69, 90, 99 | | `apps/mobile/src/features/settings/SettingsRouteScreen.tsx` | A | 72, Role library, 105 | | `apps/mobile/src/features/settings/components/SettingsScreen.tsx` | N | 72 | @@ -984,7 +984,7 @@ explicitly marked. | `apps/mobile/src/lib/filePreview.test.ts` | N | 97, 99 | | `apps/mobile/src/features/threads/thread-search-match.tsx` | N | 99 | | `apps/mobile/src/features/threads/thread-work-log.tsx` | N | 99 | -| `apps/mobile/src/features/threads/thread-list-v2-items.tsx` | N | 115 | +| `apps/mobile/src/features/threads/ThreadAgentsSheet.tsx` | N | 115 | | `apps/mobile/src/features/threads/useThreadListV2.ts` | N | 115 | | `apps/mobile/src/features/threads/useThreadListV2.test.tsx` | N | 115 | | `apps/mobile/src/features/threads/ThreadComposer.tsx` | A | 49, 100, Role library, Saved-agent mentions | diff --git a/apps/mobile/src/features/threads/ThreadAgentsSheet.tsx b/apps/mobile/src/features/threads/ThreadAgentsSheet.tsx index 03915d47bc23b..73373f11c4f95 100644 --- a/apps/mobile/src/features/threads/ThreadAgentsSheet.tsx +++ b/apps/mobile/src/features/threads/ThreadAgentsSheet.tsx @@ -21,6 +21,7 @@ import { ScreenStack } from "react-native-screens"; import { useSafeAreaInsets } from "react-native-safe-area-context"; import { AndroidSheetHeader } from "../../components/ui/AndroidScreenHeader"; +import { J5ThreadAgents, useHasJ5Agents } from "../../j5/crew/J5ThreadAgents"; import { AppText as Text } from "../../components/ui/AppText"; import { environmentThreadDetails } from "../../state/threads"; import { NativeStackScreenOptions, nativeHeaderScrollEdgeEffects } from "../../native/StackHeader"; @@ -61,6 +62,8 @@ export function ThreadAgentsSheet({ route }: StaticScreenProps) { const turn = useThreadTurnSubagents(target); const subagents = turn?.subagents ?? []; const hasLiveAgent = (turn?.liveCount ?? 0) > 0; + // J5 (case 115): the Crew seats and Peer Agents this thread spawned list above the subagents. + const hasJ5Agents = useHasJ5Agents(target); const workflowGroups = useMemo( () => new Map( @@ -100,7 +103,12 @@ export function ThreadAgentsSheet({ route }: StaticScreenProps) { contentContainerClassName="px-5 pb-6" contentContainerStyle={{ paddingBottom: Math.max(insets.bottom, 16) + 8 }} > - {subagents.length === 0 ? ( + + {subagents.length === 0 && !hasJ5Agents ? ( No agents in this turn. diff --git a/apps/mobile/src/features/threads/ThreadDetailScreen.tsx b/apps/mobile/src/features/threads/ThreadDetailScreen.tsx index c2adf65a6ec11..d1ef02e5af0f6 100644 --- a/apps/mobile/src/features/threads/ThreadDetailScreen.tsx +++ b/apps/mobile/src/features/threads/ThreadDetailScreen.tsx @@ -201,6 +201,7 @@ import { ComposerPopoverHost } from "./ComposerPopoverHost"; import { ThreadFeed, type ThreadFeedHandle, type ThreadFeedHistoryControls } from "./ThreadFeed"; import { WorkspaceMutationIdProvider } from "./WorkspaceMutationIdProvider"; import { useThreadTurnSubagents } from "./ThreadAgentsSheet"; +import { useJ5AgentsPillSegment } from "../../j5/crew/J5ThreadAgents"; import { ComposerQueuedEditBanner } from "./ComposerQueuedEdit"; import { useThreadQueuedCount } from "./ThreadQueueControl"; import { ThreadGuestShareBar } from "./ThreadGuestShareBar"; @@ -483,7 +484,12 @@ function ThreadDetailBody( const composerError = useAtomValue(threadComposerErrorsAtom)[selectedThreadKey]?.message ?? null; const queuedCount = useThreadQueuedCount(props.selectedThreadDetailRef); const turnSubagents = useThreadTurnSubagents(props.selectedThreadDetailRef); - const agentsSegment = resolveSubagentPillSegment(turnSubagents); + // J5 (case 115): the pill counts the Crew seats and Peer Agents this thread spawned too. + const agentsSegment = useJ5AgentsPillSegment( + props.selectedThreadDetailRef, + turnSubagents, + resolveSubagentPillSegment(turnSubagents), + ); const defaultComposerEditorRef = useRef(null); const composerEditorRef = props.draftMode?.editorRef ?? defaultComposerEditorRef; const isProviderSubagent = isProviderNativeSubagentThread(props.selectedThread.source); diff --git a/apps/mobile/src/features/threads/thread-list-v2-items.tsx b/apps/mobile/src/features/threads/thread-list-v2-items.tsx index e2147d5406ccc..1e859f73cc6c7 100644 --- a/apps/mobile/src/features/threads/thread-list-v2-items.tsx +++ b/apps/mobile/src/features/threads/thread-list-v2-items.tsx @@ -39,7 +39,6 @@ import { SymbolView, type AppSymbolName } from "../../components/ui/AppSymbol"; import { AppText as Text } from "../../components/ui/AppText"; import { Menu } from "../../components/ui/Menu"; import { AgentIdentityChip } from "../../j5/agents/AgentIdentityChip"; -import { CaptainSeats, CaptainSeatsToggle } from "../../j5/crew/CaptainSeats"; import { EnvironmentMachineSymbol } from "../../components/EnvironmentMachineSymbol"; import { ProjectFavicon } from "../../components/ProjectFavicon"; import { ProviderIcon, ProviderInstanceIcon } from "../../components/ProviderIcon"; @@ -1278,14 +1277,6 @@ export const ThreadListV2Row = memo(function ThreadListV2Row(props: { ) : ( )} - {pr ? ( ) : null} - {props.hasQueuedMessages ? : null} ); - const captainSeats = ( - - ); - if (!canOperateThread) - return ( - <> - {rowContent(() => {})} - {captainSeats} - - ); + return {rowContent(() => {})}; return ( @@ -1547,7 +1517,6 @@ export const ThreadListV2Row = memo(function ThreadListV2Row(props: { )} - {captainSeats} ); }); diff --git a/apps/mobile/src/j5/crew/CaptainSeats.tsx b/apps/mobile/src/j5/crew/CaptainSeats.tsx deleted file mode 100644 index 652ba86573a06..0000000000000 --- a/apps/mobile/src/j5/crew/CaptainSeats.tsx +++ /dev/null @@ -1,313 +0,0 @@ -import { useAtomValue } from "@effect/atom-react"; -import { scopeThreadRef } from "@t3tools/client-runtime/environment"; -import { seatQuietLabel } from "@t3tools/client-runtime/j5/crew-state"; -import { - groupSpawnedChildren, - selectSpawnedChildRows, - spawnedChildrenCountLabel, - stoppableCrew, - type SpawnedChildGroup, -} from "@t3tools/client-runtime/j5/spawned-children"; -import type { EnvironmentThreadShell } from "@t3tools/client-runtime/state/models"; -import type { EnvironmentId } from "@t3tools/contracts"; -import type { SpawnedChild } from "@t3tools/contracts/j5"; -import * as Cause from "effect/Cause"; -import { useState, useSyncExternalStore } from "react"; -import { Alert, Pressable, View } from "react-native"; - -import { SymbolView, type AppSymbolName } from "../../components/ui/AppSymbol"; -import { AppText as Text } from "../../components/ui/AppText"; -import { - resolveThreadListV2Status, - type ThreadListV2Status, -} from "../../features/threads/threadListV2"; -import { cn } from "../../lib/cn"; -import { relativeTime } from "../../lib/time"; -import { appAtomRegistry } from "../../state/atom-registry"; -import { useThreadShells } from "../../state/entities"; -import { j5Environment } from "../state"; -import { useSpawnedChildren } from "./spawnedChildren"; - -/** Upstream's row status labels, handed in by the row so seats read the way rows do. */ -export type SeatStatusLabels = Partial< - Record< - ThreadListV2Status, - { - readonly label: string; - readonly icon: AppSymbolName; - readonly className: string; - readonly iconTintClassName: string; - } - > ->; - -// Expanded spawners for this session, shared by the in-row toggle and the seats below the row. -let expanded: ReadonlySet = new Set(); -const listeners = new Set<() => void>(); -const subscribe = (listener: () => void) => { - listeners.add(listener); - return () => { - listeners.delete(listener); - }; -}; -const expansionKey = (thread: EnvironmentThreadShell) => `${thread.environmentId}/${thread.id}`; -/** One row's expansion, so toggling a row re-renders only that row. */ -const useIsExpanded = (key: string) => { - const read = () => expanded.has(key); - return useSyncExternalStore(subscribe, read, read); -}; -const toggle = (key: string) => { - const next = new Set(expanded); - if (next.has(key)) next.delete(key); - else next.add(key); - expanded = next; - listeners.forEach((listener) => listener()); -}; - -function useGroups(thread: EnvironmentThreadShell, children: ReadonlyArray) { - const threads = useThreadShells(); - // Children are placed on the parent's environment; the same local id elsewhere is unrelated. - const threadsById = new Map( - threads - .filter((candidate) => candidate.environmentId === thread.environmentId) - .map((candidate) => [candidate.id as string, candidate]), - ); - return groupSpawnedChildren(selectSpawnedChildRows(children, threadsById)); -} - -/** - * The spawner's count and expand control, inside its existing row so a collapsed row is no - * taller. Most rows have no children and render nothing. - */ -export function CaptainSeatsToggle(props: { - readonly thread: EnvironmentThreadShell; - readonly mutedClassName: string; -}) { - const children = useSpawnedChildren(scopeThreadRef(props.thread.environmentId, props.thread.id)); - if (children.length === 0) return null; - return ; -} - -function SeatsToggle(props: { - readonly thread: EnvironmentThreadShell; - readonly mutedClassName: string; - readonly spawned: ReadonlyArray; -}) { - const groups = useGroups(props.thread, props.spawned); - const key = expansionKey(props.thread); - const isOpen = useIsExpanded(key); - if (groups.length === 0) return null; - const count = spawnedChildrenCountLabel(groups); - const needsAttention = !isOpen && groups.some((group) => group.needsAttention); - return ( - // As tall as the provider icon beside it, so the text's taller line box can't grow the row. - - toggle(key)} - onLongPress={() => undefined} - style={({ pressed }) => ({ opacity: pressed ? 0.6 : 1 })} - > - - - {count} - - {needsAttention ? : null} - - - ); -} - -/** The seats and agents under an expanded spawner's row, one block per Crew and one for solo agents. */ -export function CaptainSeats(props: { - readonly thread: EnvironmentThreadShell; - readonly statusLabels: SeatStatusLabels; - readonly onSelectThread: (thread: EnvironmentThreadShell) => void; -}) { - const children = useSpawnedChildren(scopeThreadRef(props.thread.environmentId, props.thread.id)); - const isOpen = useIsExpanded(expansionKey(props.thread)); - if (!isOpen || children.length === 0) return null; - return ; -} - -function SeatGroups(props: { - readonly thread: EnvironmentThreadShell; - readonly statusLabels: SeatStatusLabels; - readonly onSelectThread: (thread: EnvironmentThreadShell) => void; - readonly spawned: ReadonlyArray; -}) { - const groups = useGroups(props.thread, props.spawned); - return ( - - {groups.map((group) => ( - - ))} - - ); -} - -function SeatGroup(props: { - readonly environmentId: EnvironmentId; - readonly group: SpawnedChildGroup; - readonly statusLabels: SeatStatusLabels; - readonly onSelectThread: (thread: EnvironmentThreadShell) => void; -}) { - const { group } = props; - const canStop = useAtomValue(j5Environment.stopCrew.permissionAtom(props.environmentId)); - const stoppable = canStop ? stoppableCrew(group) : null; - const [stopping, setStopping] = useState(false); - const stop = (crew: { readonly crewInstanceId: string; readonly crewName: string }) => { - setStopping(true); - void j5Environment.stopCrew - .run(appAtomRegistry, { - environmentId: props.environmentId, - input: { crewInstanceId: crew.crewInstanceId }, - }) - .then((result) => { - if (result._tag === "Failure") throw Cause.squash(result.cause); - }) - .catch((error: unknown) => { - Alert.alert( - `Couldn't stop crew ${crew.crewName}`, - error instanceof Error ? error.message : String(error), - ); - }) - .finally(() => setStopping(false)); - }; - return ( - - - - {group.crew === null ? null : ( - {group.crew.crewName} · - )} - {group.summary} - - {stoppable === null ? null : ( - // Interrupts this Crew's running seats; it retires nothing. - stop(stoppable)} - style={({ pressed }) => ({ opacity: stopping ? 0.5 : pressed ? 0.6 : 1 })} - > - Stop crew - - )} - - {group.rows.map(({ child, thread }) => ( - - ))} - - ); -} - -function SeatStatus(props: { - readonly child: SpawnedChild; - readonly thread: EnvironmentThreadShell; - readonly statusLabels: SeatStatusLabels; -}) { - const { child, thread } = props; - // A replaced member's last run says nothing about it now; being replaced does. - if (child.replaced !== undefined) - return ( - - Replaced by {child.replaced.replacedBy} - - ); - const status = resolveThreadListV2Status(thread); - // Upstream reads an idle session as Waiting; a seat says how its last run ended instead. - const live = - status === "waiting" && thread.runtime?.status === "idle" - ? undefined - : props.statusLabels[status]; - if (live === undefined) - return ( - - {child.seat === null - ? "Idle" - : seatQuietLabel({ notStarted: child.seat.notStarted, runtime: thread.runtime })} - - ); - return ( - - - {live.label} - - ); -} - -function SeatRow(props: { - readonly child: SpawnedChild; - readonly thread: EnvironmentThreadShell | undefined; - readonly statusLabels: SeatStatusLabels; - readonly onSelectThread: (thread: EnvironmentThreadShell) => void; -}) { - const { child, thread } = props; - // A seat the client holds no facts for is listed, not opened: there may be no thread. - if (thread === undefined) - return ( - - - {child.seat?.seat ?? "Seat"} - - Unknown - - ); - // A seat thread is titled by its seat, so the badge repeats it only once renamed. - const renamedSeat = - child.seat !== null && child.seat.seat !== thread.title ? child.seat.seat : null; - return ( - props.onSelectThread(thread)} - style={({ pressed }) => ({ opacity: pressed ? 0.6 : 1 })} - > - - {renamedSeat === null ? null : ( - - {renamedSeat} - - )} - - {thread.title} - - - {relativeTime(thread.updatedAt)} - - - - - ); -} diff --git a/apps/mobile/src/j5/crew/J5ThreadAgents.tsx b/apps/mobile/src/j5/crew/J5ThreadAgents.tsx new file mode 100644 index 0000000000000..f41c3e334f789 --- /dev/null +++ b/apps/mobile/src/j5/crew/J5ThreadAgents.tsx @@ -0,0 +1,267 @@ +import { useAtomValue } from "@effect/atom-react"; +import { scopeThreadRef } from "@t3tools/client-runtime/environment"; +import { crewAgentStatus } from "@t3tools/client-runtime/j5/crew-state"; +import { + groupSpawnedChildren, + j5AgentsPillSegment, + selectSpawnedChildRows, + stoppableCrew, + type SpawnedChildGroup, +} from "@t3tools/client-runtime/j5/spawned-children"; +import { + threadRuntimeIsActive, + type EnvironmentThreadShell, +} from "@t3tools/client-runtime/state/models"; +import type { + SubagentPillSegment, + ThreadTurnSubagents, +} from "@t3tools/client-runtime/state/thread-subagents"; +import type { EnvironmentId, ScopedThreadRef, ThreadId } from "@t3tools/contracts"; +import type { SpawnedChild } from "@t3tools/contracts/j5"; +import * as Cause from "effect/Cause"; +import { Atom } from "effect/reactivity"; +import { useState } from "react"; +import { Alert, Pressable, View } from "react-native"; + +import { SymbolView } from "../../components/ui/AppSymbol"; +import { AppText as Text } from "../../components/ui/AppText"; +import { + SUBAGENT_TONE_TEXT_CLASS, + SubagentStatusDot, +} from "../../features/threads/SubagentStatusDot"; +import { cn } from "../../lib/cn"; +import { relativeTime } from "../../lib/time"; +import { appAtomRegistry } from "../../state/atom-registry"; +import { useThreadShells } from "../../state/entities"; +import { environmentThreadShells } from "../../state/threads"; +import { j5Environment } from "../state"; +import { useThreadSpawnedChildren } from "./spawnedChildren"; + +type ChildTarget = { readonly environmentId: EnvironmentId; readonly threadId: ThreadId }; + +// "running/total" for one thread's children, so the pill re-renders only when a count changes. +const childCountsAtom = Atom.family((key: string) => { + const [environmentId, children] = JSON.parse(key) as [EnvironmentId, Array<[ThreadId, boolean]>]; + return Atom.make((get) => { + let running = 0; + let total = 0; + for (const [threadId, isSeat] of children) { + const shell = get( + environmentThreadShells.threadShellAtom(scopeThreadRef(environmentId, threadId)), + ); + // The same rows the sheet lists: no archived child, and no solo agent the client lacks. + if (shell === null ? !isSeat : shell.archivedAt !== null) continue; + total += 1; + if (shell !== null && threadRuntimeIsActive(shell.runtime)) running += 1; + } + return `${running}/${total}`; + }).pipe(Atom.withLabel(`mobile-j5:spawned-child-counts:${key}`)); +}); + +/** Upstream's Agents pill segment, counting the Crew seats and Peer Agents the thread spawned. */ +export function useJ5AgentsPillSegment( + ref: ScopedThreadRef | null, + turn: ThreadTurnSubagents | null, + upstream: SubagentPillSegment | null, +): SubagentPillSegment | null { + const children = useThreadSpawnedChildren(ref); + const counts = useAtomValue( + childCountsAtom( + JSON.stringify([ + ref?.environmentId ?? null, + children.map((child) => [child.threadId, child.seat !== null]), + ]), + ), + ); + const [running = 0, total = 0] = counts.split("/").map(Number); + return j5AgentsPillSegment(turn, upstream, { running, total }); +} + +/** Whether the sheet lists spawned agents, so upstream's empty text stays only for an empty sheet. */ +export function useHasJ5Agents(ref: ScopedThreadRef): boolean { + return useThreadSpawnedChildren(ref).length > 0; +} + +/** + * The thread's Crew seats and Peer Agents in upstream's Agents sheet: one block per Crew, with + * Stop crew while a seat runs, and one for agents spawned outside a Crew. + */ +export function J5ThreadAgents(props: { + readonly environmentId: EnvironmentId; + readonly threadId: ThreadId; + readonly onOpen: (child: ChildTarget) => void; +}) { + const children = useThreadSpawnedChildren(scopeThreadRef(props.environmentId, props.threadId)); + if (children.length === 0) return null; + return ; +} + +function SpawnedAgentGroups(props: { + readonly environmentId: EnvironmentId; + readonly onOpen: (child: ChildTarget) => void; + readonly spawned: ReadonlyArray; +}) { + const threads = useThreadShells(); + // Children are placed on the parent's environment; the same local id elsewhere is unrelated. + const threadsById = new Map( + threads + .filter((thread) => thread.environmentId === props.environmentId) + .map((thread) => [thread.id as string, thread]), + ); + const groups = groupSpawnedChildren(selectSpawnedChildRows(props.spawned, threadsById)); + return ( + <> + {groups.map((group) => ( + + ))} + + ); +} + +function SpawnedAgentGroup(props: { + readonly environmentId: EnvironmentId; + readonly group: SpawnedChildGroup; + readonly onOpen: (child: ChildTarget) => void; +}) { + const { group } = props; + const canStop = useAtomValue(j5Environment.stopCrew.permissionAtom(props.environmentId)); + const stoppable = canStop ? stoppableCrew(group) : null; + const [stopping, setStopping] = useState(false); + const stop = (crew: { readonly crewInstanceId: string; readonly crewName: string }) => { + setStopping(true); + void j5Environment.stopCrew + .run(appAtomRegistry, { + environmentId: props.environmentId, + input: { crewInstanceId: crew.crewInstanceId }, + }) + .then((result) => { + if (result._tag === "Failure") throw Cause.squash(result.cause); + }) + .catch((error: unknown) => { + Alert.alert( + `Couldn't stop crew ${crew.crewName}`, + error instanceof Error ? error.message : String(error), + ); + }) + .finally(() => setStopping(false)); + }; + return ( + + + + + {group.crew === null ? "Peer Agents" : group.crew.crewName} + + {group.crew === null ? null : ` · ${group.summary}`} + + {stoppable === null ? null : ( + // Interrupts this Crew's running seats; it retires nothing. + stop(stoppable)} + style={({ pressed }) => ({ opacity: stopping ? 0.5 : pressed ? 0.6 : 1 })} + > + Stop crew + + )} + + {group.rows.map(({ child, thread }) => ( + + ))} + + ); +} + +function SpawnedAgentRow(props: { + readonly environmentId: EnvironmentId; + readonly child: SpawnedChild; + readonly thread: EnvironmentThreadShell | undefined; + readonly onOpen: (child: ChildTarget) => void; +}) { + const { child, thread } = props; + const status = crewAgentStatus( + { isSeat: child.seat !== null, replacedBy: child.replaced?.replacedBy ?? null }, + thread, + ); + // A seat thread is titled by its seat, so the seat is named again only once renamed. + const renamedSeat = + child.seat !== null && thread !== undefined && child.seat.seat !== thread.title + ? child.seat.seat + : null; + const row = ( + + + + + + + + + {thread?.title ?? child.seat?.seat ?? "Agent"} + + + · + + + {status.label} + + + {thread === undefined ? null : ( + <> + + {relativeTime(thread.updatedAt)} + + + + )} + + {renamedSeat === null ? null : ( + + Seat {renamedSeat} + + )} + + + ); + // A seat the client holds no thread for is listed, not opened: there may be no thread. + if (thread === undefined) + return ( + + {row} + + ); + return ( + props.onOpen({ environmentId: props.environmentId, threadId: thread.id })} + className="border-b border-border active:opacity-70" + > + {row} + + ); +} diff --git a/apps/mobile/src/j5/crew/spawnedChildren.ts b/apps/mobile/src/j5/crew/spawnedChildren.ts index 2207355226e10..0d737177c2ff9 100644 --- a/apps/mobile/src/j5/crew/spawnedChildren.ts +++ b/apps/mobile/src/j5/crew/spawnedChildren.ts @@ -82,8 +82,8 @@ const requestRows = (refs: ReadonlyArray, revisions: string) => }; /** - * The list's threads without the ones an agent spawned (register D22): those show under their - * spawner's row unless pinned. Also keeps the spawned-children read current for every thread. + * The list's threads without the ones an agent spawned (register D22): those show in their + * spawner's Agents sheet unless pinned. Also keeps the spawned-children read current for every thread. */ export function useCrewListedThreads< T extends { @@ -125,10 +125,23 @@ export function useCrewListedThreads< const EMPTY: ReadonlyArray = []; -/** The agents placed under one thread, as last read. */ -export function useSpawnedChildren(ref: ScopedThreadRef): ReadonlyArray { - const key = scopedThreadKey(ref); - // Per row: a batch keeps untouched rows' values, so other rows' updates skip this one. - const read = () => store.getSnapshot().get(key)?.children ?? EMPTY; +/** + * The agents placed under one open thread. It is read on open and again when placements change, + * so it stays current even when no list has the thread on screen. + */ +export function useThreadSpawnedChildren(ref: ScopedThreadRef | null): ReadonlyArray { + const connections = useAtomValue(threadReadConnectionsAtom); + const revisions = useAtomValue(placementRevisionsAtom); + const environmentId = ref?.environmentId; + const threadId = ref?.threadId; + // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- asks the thread's server for the agents under it, again when placements change. + useEffect(() => { + store.setConnections(connections); + if (environmentId !== undefined && threadId !== undefined) + store.request([scopeThreadRef(environmentId, threadId)], true); + // oxlint-disable-next-line react/exhaustive-effect-dependencies -- a moved revision re-reads the thread. + }, [connections, revisions, environmentId, threadId]); + const key = ref === null ? null : scopedThreadKey(ref); + const read = () => (key === null ? EMPTY : (store.getSnapshot().get(key)?.children ?? EMPTY)); return useSyncExternalStore(store.subscribe, read, read); } diff --git a/apps/mobile/src/j5/upstreamSeams.test.ts b/apps/mobile/src/j5/upstreamSeams.test.ts index 9513d0c9b7b99..d907acfea0af7 100644 --- a/apps/mobile/src/j5/upstreamSeams.test.ts +++ b/apps/mobile/src/j5/upstreamSeams.test.ts @@ -187,10 +187,16 @@ const SEAMS: ReadonlyArray = [ ], }, { - file: "features/threads/thread-list-v2-items.tsx", - record: "case 115: spawned agents under their spawner's row", - from: "../../j5/crew/CaptainSeats", - reaches: [" { expect(seatQuietLabel({ notStarted: false })).toBe("Idle"); expect(seatQuietLabel({})).toBe("Idle"); }); + + it("gives a spawned agent's row its status, replacement first", () => { + const asSeat = { isSeat: true, replacedBy: null }; + expect( + crewAgentStatus( + { isSeat: true, replacedBy: "beta" }, + seat({ runtime: { status: "running" } }), + ), + ).toEqual({ tone: "stopped", label: "Replaced by beta" }); + expect(crewAgentStatus(asSeat, seat({ runtime: { status: "running" } }))).toEqual({ + tone: "working", + label: "Working", + }); + expect(crewAgentStatus(asSeat, seat({ notStarted: true }))).toEqual({ + tone: "stopped", + label: "Not started", + }); + expect(crewAgentStatus(asSeat, seat({ runtime: { status: "completed" } }))).toEqual({ + tone: "completed", + label: "Completed", + }); + expect(crewAgentStatus(asSeat, seat({ runtime: { status: "interrupted" } }))).toEqual({ + tone: "stopped", + label: "Interrupted", + }); + expect(crewAgentStatus(asSeat, undefined)).toEqual({ tone: "stopped", label: "Unknown" }); + // A solo agent's quiet state stays "Idle"; only seats say how their last run ended. + expect( + crewAgentStatus( + { isSeat: false, replacedBy: null }, + seat({ runtime: { status: "completed" } }), + ), + ).toEqual({ tone: "stopped", label: "Idle" }); + }); }); diff --git a/packages/client-runtime/src/j5/crewState.ts b/packages/client-runtime/src/j5/crewState.ts index df2759b119416..8c96acb5f4ce1 100644 --- a/packages/client-runtime/src/j5/crewState.ts +++ b/packages/client-runtime/src/j5/crewState.ts @@ -120,3 +120,38 @@ export const formatCrewStateSummary = (summary: CrewStateSummary): string | null ); return parts.length === 0 ? null : parts.join(" · "); }; + +/** A spawned agent's status on a row, in the tones upstream's agent rows use. */ +export interface CrewAgentStatus { + readonly tone: "working" | "completed" | "failed" | "stopped"; + readonly label: string; +} + +const STATE_STATUS: Partial> = { + running: { tone: "working", label: "Working" }, + "needs-you": { tone: "working", label: "Needs you" }, + failed: { tone: "failed", label: "Failed" }, + settled: { tone: "completed", label: "Settled" }, + "not-started": { tone: "stopped", label: "Not started" }, + archived: { tone: "stopped", label: "Archived" }, + unknown: { tone: "stopped", label: "Unknown" }, +}; + +/** + * A replaced member says so before anything its last run says; a quiet seat says how its last run + * ended, and a quiet solo agent stays "Idle", as on web. + */ +export const crewAgentStatus = ( + agent: { readonly isSeat: boolean; readonly replacedBy: string | null }, + thread: CrewSeatThread | undefined, +): CrewAgentStatus => { + if (agent.replacedBy !== null) + return { tone: "stopped", label: `Replaced by ${agent.replacedBy}` }; + const state = classifyCrewSeat(thread); + const known = STATE_STATUS[state]; + if (known !== undefined) return known; + const label = agent.isSeat + ? seatQuietLabel({ notStarted: thread?.notStarted, runtime: thread?.runtime }) + : "Idle"; + return { tone: label === "Completed" ? "completed" : "stopped", label }; +}; diff --git a/packages/client-runtime/src/j5/spawnedChildren.test.ts b/packages/client-runtime/src/j5/spawnedChildren.test.ts index 742f63cbf4330..399c7505c08c4 100644 --- a/packages/client-runtime/src/j5/spawnedChildren.test.ts +++ b/packages/client-runtime/src/j5/spawnedChildren.test.ts @@ -6,15 +6,38 @@ import { scopedThreadKey, scopeThreadRef } from "../environment/scoped.ts"; import { groupSpawnedChildren, isSidebarMember, + j5AgentsPillSegment, replaceSpawnedChildren, selectSpawnedChildRows, - spawnedChildrenCountLabel, spawnedChildrenNeedAttention, spawnedChildrenRows, spawnedGroupExpansionKey, stoppableCrew, } from "./spawnedChildren.ts"; +describe("the Agents pill with spawned agents", () => { + const turn = (liveCount: number, total: number) => + ({ liveCount, subagents: Array.from({ length: total }) }) as unknown as Parameters< + typeof j5AgentsPillSegment + >[0]; + const upstream = { label: "1/2", accessibilityLabel: "1 of 2 agents working" }; + + it("leaves upstream's segment alone without spawned agents, and adds them otherwise", () => { + expect(j5AgentsPillSegment(turn(1, 2), upstream, { running: 0, total: 0 })).toBe(upstream); + expect(j5AgentsPillSegment(null, null, { running: 0, total: 0 })).toBeNull(); + expect(j5AgentsPillSegment(turn(1, 2), upstream, { running: 1, total: 3 })).toEqual({ + label: "2/5", + accessibilityLabel: "2 of 5 agents working", + }); + // An idle Crew keeps the pill between turns, when upstream's segment is gone. + expect(j5AgentsPillSegment(turn(0, 2), null, { running: 0, total: 3 })).toEqual({ + label: "3 agents", + accessibilityLabel: "3 agents, none working", + }); + expect(j5AgentsPillSegment(null, null, { running: 0, total: 1 })?.label).toBe("1 agent"); + }); +}); + describe("sidebar membership", () => { it("moves an agent-spawned thread under its spawner unless it is pinned", () => { expect(isSidebarMember({ pinnedAt: null }, true)).toBe(false); @@ -105,8 +128,6 @@ describe("spawned children under a sidebar row", () => { ], ); expect(groups.map((group) => group.needsAttention)).toEqual([false, true, false]); - expect(spawnedChildrenCountLabel(groups)).toBe("3 seats · 1 agent"); - expect(spawnedChildrenCountLabel(groups.slice(2))).toBe("1 agent"); expect(groups[1]!.rows.map(({ child }) => child.threadId)).toEqual(["critic", "builder"]); expect(groupSpawnedChildren([])).toEqual([]); expect(spawnedGroupExpansionKey("env:a", "captain", "crew:crew:1")).toBe( diff --git a/packages/client-runtime/src/j5/spawnedChildren.ts b/packages/client-runtime/src/j5/spawnedChildren.ts index d94818c5f123d..3da92444e914b 100644 --- a/packages/client-runtime/src/j5/spawnedChildren.ts +++ b/packages/client-runtime/src/j5/spawnedChildren.ts @@ -2,6 +2,7 @@ import type { EnvironmentId, ThreadId } from "@t3tools/contracts"; import type { SpawnedChild, SpawnedChildrenEntry } from "@t3tools/contracts/j5"; import { scopedThreadKey, scopeThreadRef } from "../environment/scoped.ts"; +import type { SubagentPillSegment, ThreadTurnSubagents } from "../state/threadSubagents.ts"; import { crewHasRunningSeat, formatCrewStateSummary, @@ -185,18 +186,20 @@ export const stoppableCrew = ( ? group.crew : null; -const counted = (count: number, noun: string) => `${count} ${noun}${count === 1 ? "" : "s"}`; - -/** The collapsed count on the spawner's own row: "3 seats", "2 agents", "2 seats · 1 agent". */ -export const spawnedChildrenCountLabel = ( - groups: ReadonlyArray>, -) => { - let seats = 0; - let agents = 0; - for (const group of groups) - if (group.crew === null) agents += group.rows.length; - else seats += group.rows.length; - return [seats > 0 ? counted(seats, "seat") : null, agents > 0 ? counted(agents, "agent") : null] - .filter((part) => part !== null) - .join(" · "); +/** + * Upstream's Agents pill with a thread's spawned agents (Crew seats and Peer Agents) added to its + * counts. Without any, upstream's segment stands; with some, the pill shows even between turns. + */ +export const j5AgentsPillSegment = ( + turn: ThreadTurnSubagents | null, + upstream: SubagentPillSegment | null, + children: { readonly running: number; readonly total: number }, +): SubagentPillSegment | null => { + if (children.total === 0) return upstream; + const live = (upstream === null || turn === null ? 0 : turn.liveCount) + children.running; + const total = (upstream === null || turn === null ? 0 : turn.subagents.length) + children.total; + if (live > 0) + return { label: `${live}/${total}`, accessibilityLabel: `${live} of ${total} agents working` }; + const agents = `${total} ${total === 1 ? "agent" : "agents"}`; + return { label: agents, accessibilityLabel: `${agents}, none working` }; }; From 55e661c76a54be865d1e4adad98c02cf1a1a1799 Mon Sep 17 00:00:00 2001 From: Jackson Miller Date: Wed, 11 Nov 2026 17:13:23 -0500 Subject: [PATCH 2/3] fix(mobile): the Agents pill and sheet count the same rows the sheet lists Co-Authored-By: Claude Opus 5.5 --- apps/mobile/src/j5/crew/J5ThreadAgents.tsx | 21 ++++++++++++------- .../src/j5/spawnedChildren.test.ts | 6 +++--- .../client-runtime/src/j5/spawnedChildren.ts | 5 +++-- 3 files changed, 19 insertions(+), 13 deletions(-) diff --git a/apps/mobile/src/j5/crew/J5ThreadAgents.tsx b/apps/mobile/src/j5/crew/J5ThreadAgents.tsx index f41c3e334f789..ad3324e76b91d 100644 --- a/apps/mobile/src/j5/crew/J5ThreadAgents.tsx +++ b/apps/mobile/src/j5/crew/J5ThreadAgents.tsx @@ -58,12 +58,8 @@ const childCountsAtom = Atom.family((key: string) => { }).pipe(Atom.withLabel(`mobile-j5:spawned-child-counts:${key}`)); }); -/** Upstream's Agents pill segment, counting the Crew seats and Peer Agents the thread spawned. */ -export function useJ5AgentsPillSegment( - ref: ScopedThreadRef | null, - turn: ThreadTurnSubagents | null, - upstream: SubagentPillSegment | null, -): SubagentPillSegment | null { +/** How many of the thread's spawned agents the sheet lists, and how many of those are running. */ +function useJ5AgentCounts(ref: ScopedThreadRef | null) { const children = useThreadSpawnedChildren(ref); const counts = useAtomValue( childCountsAtom( @@ -74,12 +70,21 @@ export function useJ5AgentsPillSegment( ), ); const [running = 0, total = 0] = counts.split("/").map(Number); - return j5AgentsPillSegment(turn, upstream, { running, total }); + return { running, total }; +} + +/** Upstream's Agents pill segment, counting the Crew seats and Peer Agents the thread spawned. */ +export function useJ5AgentsPillSegment( + ref: ScopedThreadRef | null, + turn: ThreadTurnSubagents | null, + upstream: SubagentPillSegment | null, +): SubagentPillSegment | null { + return j5AgentsPillSegment(turn, upstream, useJ5AgentCounts(ref)); } /** Whether the sheet lists spawned agents, so upstream's empty text stays only for an empty sheet. */ export function useHasJ5Agents(ref: ScopedThreadRef): boolean { - return useThreadSpawnedChildren(ref).length > 0; + return useJ5AgentCounts(ref).total > 0; } /** diff --git a/packages/client-runtime/src/j5/spawnedChildren.test.ts b/packages/client-runtime/src/j5/spawnedChildren.test.ts index 399c7505c08c4..4bb8ce734ea01 100644 --- a/packages/client-runtime/src/j5/spawnedChildren.test.ts +++ b/packages/client-runtime/src/j5/spawnedChildren.test.ts @@ -29,10 +29,10 @@ describe("the Agents pill with spawned agents", () => { label: "2/5", accessibilityLabel: "2 of 5 agents working", }); - // An idle Crew keeps the pill between turns, when upstream's segment is gone. + // An idle Crew keeps the pill between turns, counting an older turn's subagents the sheet lists. expect(j5AgentsPillSegment(turn(0, 2), null, { running: 0, total: 3 })).toEqual({ - label: "3 agents", - accessibilityLabel: "3 agents, none working", + label: "5 agents", + accessibilityLabel: "5 agents, none working", }); expect(j5AgentsPillSegment(null, null, { running: 0, total: 1 })?.label).toBe("1 agent"); }); diff --git a/packages/client-runtime/src/j5/spawnedChildren.ts b/packages/client-runtime/src/j5/spawnedChildren.ts index 3da92444e914b..71a6a7f985d8c 100644 --- a/packages/client-runtime/src/j5/spawnedChildren.ts +++ b/packages/client-runtime/src/j5/spawnedChildren.ts @@ -196,8 +196,9 @@ export const j5AgentsPillSegment = ( children: { readonly running: number; readonly total: number }, ): SubagentPillSegment | null => { if (children.total === 0) return upstream; - const live = (upstream === null || turn === null ? 0 : turn.liveCount) + children.running; - const total = (upstream === null || turn === null ? 0 : turn.subagents.length) + children.total; + // The sheet lists every subagent of the turn, even one upstream's pill no longer counts. + const live = (turn?.liveCount ?? 0) + children.running; + const total = (turn?.subagents.length ?? 0) + children.total; if (live > 0) return { label: `${live}/${total}`, accessibilityLabel: `${live} of ${total} agents working` }; const agents = `${total} ${total === 1 ? "agent" : "agents"}`; From e0c3d61e2485a551c72bfac9445efa5b04bca3c1 Mon Sep 17 00:00:00 2001 From: Jackson Miller Date: Wed, 11 Nov 2026 17:16:32 -0500 Subject: [PATCH 3/3] perf(mobile): the open thread re-reads its agents without re-rendering on other servers' changes Co-Authored-By: Claude Opus 5.5 --- apps/mobile/src/j5/crew/spawnedChildren.ts | 28 +++++++++++++++------- 1 file changed, 20 insertions(+), 8 deletions(-) diff --git a/apps/mobile/src/j5/crew/spawnedChildren.ts b/apps/mobile/src/j5/crew/spawnedChildren.ts index 0d737177c2ff9..a00f75ed2f37a 100644 --- a/apps/mobile/src/j5/crew/spawnedChildren.ts +++ b/apps/mobile/src/j5/crew/spawnedChildren.ts @@ -130,17 +130,29 @@ const EMPTY: ReadonlyArray = []; * so it stays current even when no list has the thread on screen. */ export function useThreadSpawnedChildren(ref: ScopedThreadRef | null): ReadonlyArray { - const connections = useAtomValue(threadReadConnectionsAtom); - const revisions = useAtomValue(placementRevisionsAtom); const environmentId = ref?.environmentId; const threadId = ref?.threadId; - // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- asks the thread's server for the agents under it, again when placements change. + // Subscribed here rather than read in render, so a revision on any server doesn't re-render + // the thread screen; only this thread's server's placements re-read it. + // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- asks the thread's server for the agents under it, again when its connection or placements change. useEffect(() => { - store.setConnections(connections); - if (environmentId !== undefined && threadId !== undefined) - store.request([scopeThreadRef(environmentId, threadId)], true); - // oxlint-disable-next-line react/exhaustive-effect-dependencies -- a moved revision re-reads the thread. - }, [connections, revisions, environmentId, threadId]); + if (environmentId === undefined || threadId === undefined) return; + const target = scopeThreadRef(environmentId, threadId); + const read = () => { + store.setConnections(appAtomRegistry.get(threadReadConnectionsAtom)); + store.request([target], true); + }; + read(); + const offConnections = appAtomRegistry.subscribe(threadReadConnectionsAtom, read); + const offPlacements = appAtomRegistry.subscribe( + j5Environment.rereadOn("crew", "fleet")({ environmentId }), + read, + ); + return () => { + offConnections(); + offPlacements(); + }; + }, [environmentId, threadId]); const key = ref === null ? null : scopedThreadKey(ref); const read = () => (key === null ? EMPTY : (store.getSnapshot().get(key)?.children ?? EMPTY)); return useSyncExternalStore(store.subscribe, read, read);